@k8ordo/framework 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,7 +35,7 @@ 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.1.0 | yes | routing, re-exported by the framework |
38
+ | `@k8ordo/router` | ^1.2.1 | 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
41
  | `vite` | ≥8.0.0 | yes | the build (`framework()` is a Vite plugin) |
@@ -91,8 +91,9 @@ export default async function ProductPage({
91
91
  ```
92
92
 
93
93
  ```bash
94
- vite dev # renders per request, with Fast Refresh
95
- vite build # static: dist/client/ is the site
94
+ vite dev # renders per request, with Fast Refresh
95
+ vite build # static: dist/client/ is the site
96
+ k8ordo generate # only .k8ordo/, the route table and its types, for tsc in CI
96
97
  ```
97
98
 
98
99
  Under `mode: 'server'` the build is a `dist/` that runs on its own — every
package/dist/cli.d.mts ADDED
@@ -0,0 +1 @@
1
+ export {}
package/dist/cli.mjs ADDED
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env node
2
+ import { resolveConfig } from "vite";
3
+ //#region src/cli.ts
4
+ const USAGE = `usage: k8ordo generate
5
+
6
+ Writes .k8ordo/ from the Vite config in this directory, as vite build does
7
+ when it begins, and builds nothing.
8
+ `;
9
+ /**
10
+ * `.k8ordo/` without a build: the config resolved as `vite build` resolves
11
+ * it, and the engine's plugin, which knows the routes directory and the
12
+ * mode, asked to generate. No environment is built and no page rendered, so
13
+ * `paths` and whatever data a page reads are never touched.
14
+ */
15
+ const generate = async () => {
16
+ const config = await resolveConfig({}, "build", "production", "production");
17
+ const engine = config.plugins.find(({ name }) => name === "k8ordo:engine");
18
+ if (engine === void 0) throw new Error(`the Vite config in ${config.root} does not use framework() from @k8ordo/framework/vite, so there is nothing to generate`);
19
+ await engine.api.generate();
20
+ config.logger.info("k8ordo: wrote .k8ordo/");
21
+ };
22
+ const args = process.argv.slice(2);
23
+ if (args.length !== 1 || args[0] !== "generate") {
24
+ process.stderr.write(USAGE);
25
+ process.exitCode = 1;
26
+ } else try {
27
+ await generate();
28
+ } catch (error) {
29
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
30
+ process.exitCode = 1;
31
+ }
32
+ //#endregion
33
+ export {};
@@ -2,8 +2,13 @@ import { Payload } from "./payload.mjs";
2
2
  import { ReactNode } from "react";
3
3
  //#region src/runtime/app-router.d.ts
4
4
  export declare const setDocumentClient: (client: string) => void;
5
- /** What a Server Action's answer does to the document, once it is read. */
6
- export declare const answerAction: (payload: Payload) => Promise<unknown>;
5
+ /** Taken before a Server Action is sent, and handed to `answerAction`. */
6
+ export declare const navigationsApplied: () => number;
7
+ /**
8
+ * What a Server Action's answer does to the document, once it is read.
9
+ * `sent` is `navigationsApplied()` as the action was sent.
10
+ */
11
+ export declare const answerAction: (payload: Payload, sent: number) => Promise<unknown>;
7
12
  export declare const setPayloadReader: (read: (stream: ReadableStream<Uint8Array>) => Promise<Payload>) => void;
8
13
  /**
9
14
  * The client half under the framework: the tree comes from the server, so
@@ -1,5 +1,6 @@
1
1
  "use client";
2
2
  import { payloadPathFor } from "./payload-path.mjs";
3
+ import { whenClientReady } from "./client-ready.mjs";
3
4
  import { ShowNotFound } from "./fallback-boundary.mjs";
4
5
  import { isPayload } from "./is-payload.mjs";
5
6
  import { createPrefetchCache, prefetchTargetOf } from "./prefetch.mjs";
@@ -34,15 +35,36 @@ const setDocumentClient = (client) => {
34
35
  * document load brings the script that can.
35
36
  */
36
37
  const canRender = (payload) => payload.client === documentClient;
37
- /** What a Server Action's answer does to the document, once it is read. */
38
- const answerAction = async (payload) => {
38
+ /**
39
+ * How a payload is waited for before its tree is applied: until the client
40
+ * components it renders have loaded — one still loading suspends where it
41
+ * renders, and a `<Suspense>` the page just brought shows its fallback in a
42
+ * page already on screen — and what the page sends once its data is in,
43
+ * except under a `<Suspense>`, whose fallback stands in for it as a
44
+ * transition leaves it.
45
+ */
46
+ const WHEN_APPLIED = { rows: "leave" };
47
+ /**
48
+ * How many trees navigations have applied — the router's, and `vite dev`'s
49
+ * reload of the page on screen. A Server Action's answer is not counted:
50
+ * answers to actions called in a row apply one after another.
51
+ */
52
+ let navigations = 0;
53
+ /** Taken before a Server Action is sent, and handed to `answerAction`. */
54
+ const navigationsApplied = () => navigations;
55
+ /**
56
+ * What a Server Action's answer does to the document, once it is read.
57
+ * `sent` is `navigationsApplied()` as the action was sent.
58
+ */
59
+ const answerAction = async (payload, sent) => {
39
60
  mounted?.forgetPrefetched();
40
61
  if (payload.redirect !== void 0) {
41
62
  await navigation.navigate(payload.redirect).finished;
42
63
  return;
43
64
  }
44
65
  if (!canRender(payload)) return reloadInstead();
45
- mounted?.apply(payload);
66
+ await whenClientReady([payload.tree, payload.notFound], WHEN_APPLIED);
67
+ if (navigations === sent) mounted?.apply(payload);
46
68
  return payload.returnValue;
47
69
  };
48
70
  let readPayload = () => Promise.reject(/* @__PURE__ */ new Error("k8ordo: payloads are read in the browser only"));
@@ -62,8 +84,9 @@ const setPayloadReader = (read) => {
62
84
  const streams = /* @__PURE__ */ new WeakMap();
63
85
  /**
64
86
  * A page's payload, or `null` when what came back is not one — a file the
65
- * host serves, or a URL nothing answers. Reading it imports the client
66
- * components it names, so a prefetch has those in hand too.
87
+ * host serves, or a URL nothing answers. It resolves once the client
88
+ * components the page renders have loaded, so a prefetch has those in hand
89
+ * too.
67
90
  */
68
91
  const fetchPage = async (payloadPath, signal) => {
69
92
  signal.throwIfAborted();
@@ -75,6 +98,7 @@ const fetchPage = async (payloadPath, signal) => {
75
98
  const response = await fetch(payloadPath, { signal: request.signal });
76
99
  if (!isPayload(response)) return null;
77
100
  const payload = await readPayload(response.body);
101
+ await whenClientReady([payload.tree, payload.notFound], WHEN_APPLIED);
78
102
  streams.set(payload, {
79
103
  cancel: () => {
80
104
  request.abort();
@@ -191,6 +215,7 @@ function AppRouter({ pathname, search, tree, notFound }) {
191
215
  if (payload === null || location.href !== url) return;
192
216
  if (!canRender(payload)) return reloadInstead();
193
217
  markNavigated();
218
+ navigations += 1;
194
219
  const next = hold(streaming.current, payload);
195
220
  searchApplied.current = payload.search;
196
221
  startTransition(() => {
@@ -242,6 +267,7 @@ function AppRouter({ pathname, search, tree, notFound }) {
242
267
  },
243
268
  apply: (next) => {
244
269
  markNavigated();
270
+ navigations += 1;
245
271
  searchApplied.current = next.search;
246
272
  setLatest(hold(streaming.current, next));
247
273
  },
@@ -269,4 +295,4 @@ function AppRouter({ pathname, search, tree, notFound }) {
269
295
  });
270
296
  }
271
297
  //#endregion
272
- export { AppRouter, answerAction, setDocumentClient, setPayloadReader };
298
+ export { AppRouter, answerAction, navigationsApplied, setDocumentClient, setPayloadReader };
@@ -1,5 +1,5 @@
1
1
  import { ACTION_ID_HEADER } from "./payload.mjs";
2
- import { answerAction, setPayloadReader } from "./app-router.mjs";
2
+ import { answerAction, navigationsApplied, setPayloadReader } from "./app-router.mjs";
3
3
  import { createFromFetch, createFromReadableStream, createTemporaryReferenceSet, encodeReply, setServerCallback } from "@vitejs/plugin-rsc/browser";
4
4
  //#region src/runtime/browser-payloads.ts
5
5
  /**
@@ -10,13 +10,14 @@ import { createFromFetch, createFromReadableStream, createTemporaryReferenceSet,
10
10
  const connectAppRouter = () => {
11
11
  setPayloadReader((stream) => createFromReadableStream(stream));
12
12
  setServerCallback(async (id, args) => {
13
+ const sent = navigationsApplied();
13
14
  const temporaryReferences = createTemporaryReferenceSet();
14
15
  const payload = await createFromFetch(fetch(location.href, {
15
16
  method: "POST",
16
17
  headers: { [ACTION_ID_HEADER]: id },
17
18
  body: await encodeReply(args, { temporaryReferences })
18
19
  }), { temporaryReferences });
19
- return answerAction(payload);
20
+ return answerAction(payload, sent);
20
21
  });
21
22
  };
22
23
  //#endregion
@@ -0,0 +1,31 @@
1
+ //#region src/runtime/client-ready.d.ts
2
+ export type ClientReadyOptions = {
3
+ /**
4
+ * What to do with a row still on its way: `'wait'` for it; `'leave'` one
5
+ * inside a `<Suspense>` to that boundary's fallback, as a transition
6
+ * leaves it — a page streaming what it put under a boundary of its own —
7
+ * and wait for the rest; or `'follow'` every one — settle without it, and
8
+ * walk it once it arrives, as an HTML render streaming it does.
9
+ */
10
+ readonly rows: 'wait' | 'leave' | 'follow';
11
+ };
12
+ /**
13
+ * Settles once the client components a payload's trees name have loaded.
14
+ * The Flight client hands each one over as a lazy element type and starts
15
+ * importing it as the payload is read; a render that meets one still loading
16
+ * suspends there, and the nearest `<Suspense>` shows its fallback — in place
17
+ * of the server's HTML on a first render, and in place of a page a
18
+ * navigation has just put on screen.
19
+ *
20
+ * Walks every element's `type` and `props` (`children` and any other prop
21
+ * holding elements), arrays and plain objects, each once, since a payload
22
+ * shares and nests them. A row still on its way (a lazy node: what a page
23
+ * sends once its data is in) is waited for and walked too, except as
24
+ * `rows` says. A row followed is still walked once it arrives, the promise
25
+ * already settled, and a client component it names is read once it has
26
+ * loaded, as one waited for is. What fails — a row the server could not
27
+ * render, a module that would not load — ends the wait there, for the
28
+ * render to meet where an error boundary takes it.
29
+ */
30
+ export declare const whenClientReady: (trees: readonly unknown[], { rows }: ClientReadyOptions) => Promise<void>;
31
+ //#endregion
@@ -0,0 +1,100 @@
1
+ //#region src/runtime/client-ready.ts
2
+ /**
3
+ * The shapes React shares between `React.lazy`, the Flight client and the
4
+ * reconciler, and the only ones read here: an element's `$$typeof`, `type`
5
+ * and `props`, and a lazy's `$$typeof`, `_payload` and `_init` — which
6
+ * returns what it stands for, or throws a thenable while that is on its way.
7
+ */
8
+ const ELEMENT = Symbol.for("react.transitional.element");
9
+ const LAZY = Symbol.for("react.lazy");
10
+ const SUSPENSE = Symbol.for("react.suspense");
11
+ const isObject = (value) => typeof value === "object" && value !== null;
12
+ const isLazy = (value) => isObject(value) && value.$$typeof === LAZY;
13
+ const isElement = (value) => value.$$typeof === ELEMENT;
14
+ const isThenable = (value) => isObject(value) && typeof value.then === "function";
15
+ const isPlain = (value) => {
16
+ const prototype = Object.getPrototypeOf(value);
17
+ return prototype === Object.prototype || prototype === null;
18
+ };
19
+ const whenSettled = (thenable) => new Promise((resolve) => {
20
+ thenable.then(() => {
21
+ resolve();
22
+ }, () => {
23
+ resolve();
24
+ });
25
+ });
26
+ /**
27
+ * Settles once the client components a payload's trees name have loaded.
28
+ * The Flight client hands each one over as a lazy element type and starts
29
+ * importing it as the payload is read; a render that meets one still loading
30
+ * suspends there, and the nearest `<Suspense>` shows its fallback — in place
31
+ * of the server's HTML on a first render, and in place of a page a
32
+ * navigation has just put on screen.
33
+ *
34
+ * Walks every element's `type` and `props` (`children` and any other prop
35
+ * holding elements), arrays and plain objects, each once, since a payload
36
+ * shares and nests them. A row still on its way (a lazy node: what a page
37
+ * sends once its data is in) is waited for and walked too, except as
38
+ * `rows` says. A row followed is still walked once it arrives, the promise
39
+ * already settled, and a client component it names is read once it has
40
+ * loaded, as one waited for is. What fails — a row the server could not
41
+ * render, a module that would not load — ends the wait there, for the
42
+ * render to meet where an error boundary takes it.
43
+ */
44
+ const whenClientReady = async (trees, { rows }) => {
45
+ const seen = /* @__PURE__ */ new WeakSet();
46
+ let waiting = [];
47
+ const settle = async () => {
48
+ while (waiting.length > 0) {
49
+ const round = waiting;
50
+ waiting = [];
51
+ await Promise.all(round.map(({ until }) => whenSettled(until)));
52
+ for (const { again } of round) again();
53
+ }
54
+ };
55
+ const read = (lazy, inside, isType) => {
56
+ let value;
57
+ try {
58
+ value = lazy._init(lazy._payload);
59
+ } catch (thrown) {
60
+ if (!isThenable(thrown)) return;
61
+ const again = () => {
62
+ read(lazy, inside, isType);
63
+ };
64
+ if (isType || rows === "wait" || rows === "leave" && !inside) waiting.push({
65
+ until: thrown,
66
+ again
67
+ });
68
+ else if (rows === "follow") whenSettled(thrown).then(() => {
69
+ again();
70
+ return settle();
71
+ });
72
+ return;
73
+ }
74
+ if (!isType) visit(value, inside);
75
+ };
76
+ const visit = (value, inside) => {
77
+ if (!isObject(value)) return;
78
+ if (isLazy(value)) {
79
+ read(value, inside, false);
80
+ return;
81
+ }
82
+ if (seen.has(value)) return;
83
+ seen.add(value);
84
+ if (Array.isArray(value)) {
85
+ for (const item of value) visit(item, inside);
86
+ return;
87
+ }
88
+ if (isElement(value)) {
89
+ if (isLazy(value.type)) read(value.type, inside, true);
90
+ const below = inside || value.type === SUSPENSE;
91
+ for (const [key, prop] of Object.entries(value.props)) visit(prop, key === "fallback" ? inside : below);
92
+ return;
93
+ }
94
+ if (isPlain(value)) for (const prop of Object.values(value)) visit(prop, inside);
95
+ };
96
+ for (const tree of trees) visit(tree, false);
97
+ await settle();
98
+ };
99
+ //#endregion
100
+ export { whenClientReady };
@@ -1,3 +1,4 @@
1
+ import { whenClientReady } from "./client-ready.mjs";
1
2
  import { AppRouter, setDocumentClient } from "./app-router.mjs";
2
3
  import { connectAppRouter } from "./browser-payloads.mjs";
3
4
  import { mount } from "./mount.mjs";
@@ -8,17 +9,21 @@ import { createFromReadableStream } from "@vitejs/plugin-rsc/browser";
8
9
  import { rscStream } from "rsc-html-stream/client";
9
10
  //#region src/runtime/entry.browser.tsx
10
11
  connectAppRouter();
11
- const payload = await createFromReadableStream(rscStream);
12
- setDocumentClient(payload.client);
13
- await whenRevealed();
14
- mount(document, /* @__PURE__ */ jsx(AppRouter, {
15
- notFound: payload.notFound,
16
- pathname: payload.pathname,
17
- search: payload.search,
18
- tree: payload.tree
19
- }), payload.pathname, {
20
- formState: payload.formState,
21
- onCaughtError: reportCaught
22
- });
12
+ const start = async () => {
13
+ const payload = await createFromReadableStream(rscStream);
14
+ setDocumentClient(payload.client);
15
+ await whenRevealed();
16
+ await whenClientReady([payload.tree, payload.notFound], { rows: "wait" });
17
+ mount(document, /* @__PURE__ */ jsx(AppRouter, {
18
+ notFound: payload.notFound,
19
+ pathname: payload.pathname,
20
+ search: payload.search,
21
+ tree: payload.tree
22
+ }), payload.pathname, {
23
+ formState: payload.formState,
24
+ onCaughtError: reportCaught
25
+ });
26
+ };
27
+ start();
23
28
  //#endregion
24
29
  export {};
@@ -16,7 +16,7 @@ import { shellParams } from "./shell.mjs";
16
16
  import { isNotFound, normalizePathname, withBase, withoutBase } from "@k8ordo/router";
17
17
  import { jsx } from "react/jsx-runtime";
18
18
  import { createTemporaryReferenceSet, decodeAction, decodeFormState, decodeReply, loadServerAction, renderToReadableStream } from "@vitejs/plugin-rsc/rsc/server";
19
- import { catchAllSchemas, fallbacks, guards, paramSchemas, redirects, routeModules, routes, searchReaders } from "virtual:k8ordo/routes";
19
+ import { catchAllSchemas, fallbacks, guards, pageModules, paramSchemas, redirects, routeModules, routes, searchReaders } from "virtual:k8ordo/routes";
20
20
  //#region src/runtime/entry.rsc.tsx
21
21
  const redirectFor = resolveRedirects(redirects);
22
22
  const redirectResponse = (to, status) => new Response(null, {
@@ -34,6 +34,92 @@ const base = import.meta.env.BASE_URL;
34
34
  * serves a build into files — as a static host would — or runs the handler.
35
35
  */
36
36
  const mode = import.meta.env.K8ORDO_MODE === "static" ? "static" : "server";
37
+ const NO_PARAMS = {
38
+ params: {},
39
+ enter: (fn) => fn()
40
+ };
41
+ /**
42
+ * The pattern that answers a pathname. A param a schema refuses is a
43
+ * pathname the pattern does not answer, so the walk goes on to whatever the
44
+ * table declares next — the catch-all in the end. A catch-all answers
45
+ * whatever its params hold: a 404 is already what a refused param means. The
46
+ * layouts' schemas above it still run, for what they write — `/en/missing`
47
+ * renders in the locale its URL names. What answers runs inside
48
+ * `parsed.enter`, so it sees what the schemas of the pattern that answered
49
+ * wrote to the async context, and nothing a refused pattern's did.
50
+ *
51
+ * A page's schema is an export of the page, and the table reads a page only
52
+ * when a request reaches it; `routes.match` decides synchronously, so it is
53
+ * asked for every pattern that fits, and the walk reads each file before
54
+ * running the schemas along its stack, in the table's order.
55
+ */
56
+ const find = async (pathname) => {
57
+ const fits = [];
58
+ routes.match(pathname, (fit) => {
59
+ fits.push(fit);
60
+ return false;
61
+ });
62
+ for (const fit of fits) {
63
+ if (fit.pattern.endsWith("/*")) return {
64
+ match: fit,
65
+ parsed: parseCatchAllParams(catchAllSchemas[fit.pattern] ?? [], fit.params)
66
+ };
67
+ const fallback = fallbacks[fit.pattern];
68
+ const known = fallback === void 0 ? null : shellParams(fit.params, fallback.open);
69
+ if (fallback !== void 0 && known !== null) {
70
+ const accepted = parseParams(fallback.schemas, known);
71
+ if (accepted === null) continue;
72
+ return {
73
+ match: fit,
74
+ parsed: accepted,
75
+ shell: {
76
+ pattern: fit.pattern,
77
+ load: fallback.load,
78
+ known
79
+ }
80
+ };
81
+ }
82
+ const leaf = await (routeModules[fit.pattern] ?? pageModules[fit.pattern])?.();
83
+ const accepted = parseParams(leaf === void 0 ? [] : paramSchemas[fit.pattern]?.(leaf) ?? [], fit.params);
84
+ if (accepted === null) continue;
85
+ return {
86
+ match: fit,
87
+ parsed: accepted,
88
+ leaf
89
+ };
90
+ }
91
+ return {
92
+ match: null,
93
+ parsed: NO_PARAMS
94
+ };
95
+ };
96
+ /** What a route file renders: its default export. */
97
+ const componentOf = (leaf) => leaf.default;
98
+ /**
99
+ * A catch-all's match with its not-found in the leaf's place, read now. The
100
+ * table holds `lazy()` there, which the render would read by itself; read
101
+ * here, a not-found that fails to load fails the request, as a page does,
102
+ * rather than a response already under way.
103
+ */
104
+ const withNotFound = async (match) => {
105
+ const leaf = await pageModules[match.pattern]?.();
106
+ return leaf === void 0 ? match : {
107
+ ...match,
108
+ stack: [...match.stack.slice(0, -1), componentOf(leaf)]
109
+ };
110
+ };
111
+ /**
112
+ * Per page module, what reads its search: `urlReader` builds the codec each
113
+ * time it is called, and a page's is the same for every request.
114
+ */
115
+ const searchReads = /* @__PURE__ */ new WeakMap();
116
+ const searchReaderOf = (pattern, leaf) => {
117
+ const make = searchReaders[pattern];
118
+ if (make === void 0) return void 0;
119
+ const made = searchReads.get(leaf) ?? make(leaf);
120
+ searchReads.set(leaf, made);
121
+ return made;
122
+ };
37
123
  /**
38
124
  * A `redirect.ts` target is written the way the route table is: a pathname
39
125
  * from the application's root, which the URL spells with the base in front.
@@ -119,7 +205,10 @@ const renderFailed = (error) => new Response(error instanceof Error ? error.mess
119
205
  * gets the request, and whether a failed render may still stream.
120
206
  */
121
207
  function handler(request) {
122
- return withRequest(request, async () => answer(await (import.meta.env.K8ORDO_MODE === "static" ? writingFile(() => respond(request)) : respond(request))));
208
+ return withRequest(request, async () => answer(await (import.meta.env.K8ORDO_MODE === "static" ? writingFile(() => respond(request).catch((error) => {
209
+ console.error("k8ordo: answering %s failed", new URL(request.url).pathname, error);
210
+ return renderFailed(error);
211
+ })) : respond(request))));
123
212
  }
124
213
  const respond = async (request) => {
125
214
  const url = new URL(request.url);
@@ -130,35 +219,7 @@ const respond = async (request) => {
130
219
  });
131
220
  const wantsPayload = isPayloadPath(own);
132
221
  const pathname = wantsPayload ? pagePathFor(own) : own;
133
- let parsed = {
134
- params: {},
135
- enter: (fn) => fn()
136
- };
137
- let shell = void 0;
138
- const match = routes.match(pathname, (found) => {
139
- if (found.pattern.endsWith("/*")) {
140
- parsed = parseCatchAllParams(catchAllSchemas[found.pattern] ?? [], found.params);
141
- return true;
142
- }
143
- const fallback = fallbacks[found.pattern];
144
- const known = fallback === void 0 ? null : shellParams(found.params, fallback.open);
145
- if (fallback !== void 0 && known !== null) {
146
- const accepted = parseParams(fallback.schemas, known);
147
- if (accepted === null) return false;
148
- parsed = accepted;
149
- shell = {
150
- pattern: found.pattern,
151
- component: fallback.component,
152
- known
153
- };
154
- return true;
155
- }
156
- shell = void 0;
157
- const accepted = parseParams(paramSchemas[found.pattern] ?? [], found.params);
158
- if (accepted === null) return false;
159
- parsed = accepted;
160
- return true;
161
- });
222
+ const { match, parsed, leaf, shell } = await find(pathname);
162
223
  const declared = match === null ? null : redirectFor(match.pattern, pathname);
163
224
  if (declared !== null) {
164
225
  if (request.method !== "GET" && request.method !== "HEAD") return new Response("method not allowed", {
@@ -167,7 +228,7 @@ const respond = async (request) => {
167
228
  });
168
229
  return redirectResponse(locationOf(declared.to), declared.permanent ? 308 : 307);
169
230
  }
170
- const module = match === null ? void 0 : routeModules[match.pattern];
231
+ const module = match === null || routeModules[match.pattern] === void 0 ? void 0 : leaf;
171
232
  if (match !== null && module !== void 0) {
172
233
  if (wantsPayload) return new Response("not a page", {
173
234
  status: 404,
@@ -208,12 +269,12 @@ const respond = async (request) => {
208
269
  });
209
270
  const routeRequest = import.meta.env.K8ORDO_MODE === "server" ? routeRequestOf(request) : fileRequest;
210
271
  const ssr = await import.meta.viteRsc.loadModule("ssr", "index");
211
- const readSearch = match === null || missing || shell !== void 0 ? void 0 : searchReaders[match.pattern];
272
+ const readSearch = match === null || missing || leaf === void 0 ? void 0 : searchReaderOf(match.pattern, leaf);
212
273
  const search = readSearch?.(url.searchParams);
213
- const nearestNotFound = () => {
274
+ const nearestNotFound = async () => {
214
275
  const nearest = matchNotFound(pathname, shell !== void 0);
215
276
  return {
216
- tree: nearest.match === null ? renderNotFound(routes, pathname, routeRequest) : renderMatch(nearest.match, {
277
+ tree: nearest.match === null ? renderNotFound(routes, pathname, routeRequest) : renderMatch(await withNotFound(nearest.match), {
217
278
  pathname,
218
279
  params: nearest.parsed.params,
219
280
  request: routeRequest
@@ -231,11 +292,12 @@ const respond = async (request) => {
231
292
  formState: action.formState,
232
293
  redirect: action.redirect
233
294
  }, enter, isAction ? temporaryReferences : void 0);
234
- const page = match === null || missing || action.redirect !== void 0 ? null : watchPage(shell?.component ?? match.stack.at(-1), /* @__PURE__ */ jsx(PageShown, {}));
295
+ const shown = shell === void 0 ? leaf : await shell.load();
296
+ const page = match === null || missing || action.redirect !== void 0 || shown === void 0 ? null : watchPage(componentOf(shown), /* @__PURE__ */ jsx(PageShown, {}));
235
297
  let showsPage = page?.followed === true;
236
298
  let status = missing ? 404 : 200;
237
299
  let { enter } = parsed;
238
- let rendered = render(action.redirect === void 0 ? match === null ? renderNotFound(routes, pathname, routeRequest) : renderMatch(shell === void 0 ? match : {
300
+ let rendered = render(action.redirect === void 0 ? match === null ? renderNotFound(routes, pathname, routeRequest) : renderMatch(missing ? await withNotFound(match) : shell === void 0 ? match : {
239
301
  ...match,
240
302
  params: shell.known
241
303
  }, {
@@ -245,7 +307,7 @@ const respond = async (request) => {
245
307
  page: page?.Page,
246
308
  search,
247
309
  shell: shell !== void 0
248
- }) : null, enter, readSearch === void 0 ? void 0 : url.search, shell === void 0 ? void 0 : nearestNotFound().tree);
310
+ }) : null, enter, readSearch === void 0 ? void 0 : url.search, shell === void 0 ? void 0 : (await nearestNotFound()).tree);
249
311
  if (page !== null && (!answersPayload || request.method === "HEAD")) {
250
312
  const [forAnswer, forWatch] = rendered.stream.tee();
251
313
  rendered = {
@@ -260,7 +322,7 @@ const respond = async (request) => {
260
322
  ]));
261
323
  if (rendered.notFound() || isNotFound(threw)) {
262
324
  rendered.abort();
263
- const nearest = nearestNotFound();
325
+ const nearest = await nearestNotFound();
264
326
  status = 404;
265
327
  showsPage = false;
266
328
  ({enter} = nearest);
@@ -289,7 +351,7 @@ const respond = async (request) => {
289
351
  if (import.meta.env.K8ORDO_MODE === "static") {
290
352
  let body;
291
353
  try {
292
- const html = await enter(() => ssr.renderHtml(rendered.stream, signingNonce(), showsPage));
354
+ const html = await enter(() => ssr.renderHtml(rendered.stream, signingNonce(), showsPage, action.formState !== void 0));
293
355
  body = await new Response(html).arrayBuffer();
294
356
  } catch (error) {
295
357
  return renderFailed(rendered.failures[0] ?? error);
@@ -306,7 +368,7 @@ const respond = async (request) => {
306
368
  }
307
369
  });
308
370
  }
309
- const html = await enter(() => ssr.renderHtml(rendered.stream, signingNonce(), showsPage));
371
+ const html = await enter(() => ssr.renderHtml(rendered.stream, signingNonce(), showsPage, action.formState !== void 0));
310
372
  return new Response(html, {
311
373
  status,
312
374
  headers: { "content-type": HTML_TYPE }
@@ -321,10 +383,7 @@ const respond = async (request) => {
321
383
  * value the shell answers.
322
384
  */
323
385
  const matchNotFound = (pathname, forShell) => {
324
- let parsed = {
325
- params: {},
326
- enter: (fn) => fn()
327
- };
386
+ let parsed = NO_PARAMS;
328
387
  const page = normalizePathname(pathname);
329
388
  return {
330
389
  match: routes.match(`${page === "/" ? "" : page}/${NOT_FOUND_SEGMENT}`, (found) => {
@@ -12,5 +12,5 @@ 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: string, showsPage: boolean): Promise<ReadableStream>;
15
+ export declare function renderHtml(rscStream: ReadableStream<Uint8Array>, nonce: string, showsPage: boolean, carriesFormState: boolean): Promise<ReadableStream>;
16
16
  //#endregion
@@ -1,6 +1,8 @@
1
+ import { whenClientReady } from "./client-ready.mjs";
1
2
  import { AppRouter } from "./app-router.mjs";
2
3
  import { noticeCancel } from "./cancel.mjs";
3
4
  import { PageShownContext } from "./page-shown.mjs";
5
+ import { use } from "react";
4
6
  import { jsx } from "react/jsx-runtime";
5
7
  import { createFromReadableStream, getClientEntryUrl } from "@vitejs/plugin-rsc/ssr";
6
8
  import { renderToReadableStream } from "react-dom/server.edge";
@@ -19,23 +21,38 @@ const clientEntry = getClientEntryUrl();
19
21
  * one round trip. It is also what lets a prerendered `404.html` come alive —
20
22
  * there is no payload file at a URL the application does not have.
21
23
  */
22
- async function renderHtml(rscStream, nonce, showsPage) {
23
- const [forHtml, forHydration] = rscStream.tee();
24
- const payload = await createFromReadableStream(forHtml, { nonce });
24
+ async function renderHtml(rscStream, nonce, showsPage, carriesFormState) {
25
+ const [forRender, forHydration] = rscStream.tee();
26
+ let forHtml = forRender;
27
+ let formState;
28
+ if (carriesFormState) {
29
+ const [forState, rest] = forRender.tee();
30
+ forHtml = rest;
31
+ ({formState} = await createFromReadableStream(forState, { nonce }));
32
+ }
33
+ let payload;
34
+ let ready;
35
+ function Root() {
36
+ payload ??= createFromReadableStream(forHtml, { nonce });
37
+ const { notFound, pathname, search, tree } = use(payload);
38
+ ready ??= whenClientReady([tree, notFound], { rows: import.meta.env.K8ORDO_MODE === "static" ? "wait" : "follow" });
39
+ use(ready);
40
+ return /* @__PURE__ */ jsx(AppRouter, {
41
+ notFound,
42
+ pathname,
43
+ search,
44
+ tree
45
+ });
46
+ }
25
47
  const shown = Promise.withResolvers();
26
48
  let readerLeft = false;
27
49
  const htmlStream = await renderToReadableStream(/* @__PURE__ */ jsx(PageShownContext, {
28
50
  value: () => shown.resolve(void 0),
29
- children: /* @__PURE__ */ jsx(AppRouter, {
30
- notFound: payload.notFound,
31
- pathname: payload.pathname,
32
- search: payload.search,
33
- tree: payload.tree
34
- })
51
+ children: /* @__PURE__ */ jsx(Root, {})
35
52
  }), {
36
53
  bootstrapModules: [clientEntry],
37
54
  nonce,
38
- formState: payload.formState,
55
+ formState,
39
56
  progressiveChunkSize: Number.POSITIVE_INFINITY,
40
57
  onError: (error) => {
41
58
  if (!readerLeft) console.error(error);