@k8ordo/framework 2.3.1 → 4.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.
Files changed (65) hide show
  1. package/README.md +28 -13
  2. package/dist/cli.mjs +3 -3
  3. package/dist/generated.d.mts +13 -13
  4. package/dist/headers-BxB_jJVk.mjs +73 -0
  5. package/dist/index.d.mts +3 -2
  6. package/dist/index.mjs +1 -1
  7. package/dist/paths-type-DXpmjaOr.d.mts +43 -0
  8. package/dist/runtime/app-router.mjs +21 -8
  9. package/dist/runtime/browser-payloads.mjs +1 -1
  10. package/dist/runtime/client-files.d.mts +6 -5
  11. package/dist/runtime/client-files.mjs +17 -9
  12. package/dist/runtime/client-ready.d.mts +7 -1
  13. package/dist/runtime/client-ready.mjs +2 -1
  14. package/dist/runtime/cookies.d.mts +2 -0
  15. package/dist/runtime/cookies.mjs +2 -1
  16. package/dist/runtime/ended.d.mts +7 -0
  17. package/dist/runtime/ended.mjs +14 -0
  18. package/dist/runtime/entry.browser.mjs +1 -1
  19. package/dist/runtime/entry.rsc.d.mts +38 -2
  20. package/dist/runtime/entry.rsc.mjs +97 -31
  21. package/dist/runtime/entry.ssr.d.mts +7 -1
  22. package/dist/runtime/entry.ssr.mjs +12 -6
  23. package/dist/runtime/guard.d.mts +15 -10
  24. package/dist/runtime/guard.mjs +8 -2
  25. package/dist/runtime/mount.mjs +1 -1
  26. package/dist/runtime/page-boundary.mjs +2 -2
  27. package/dist/runtime/params.d.mts +5 -4
  28. package/dist/runtime/params.mjs +2 -2
  29. package/dist/runtime/payload.d.mts +19 -4
  30. package/dist/runtime/payload.mjs +20 -5
  31. package/dist/runtime/prefetch.d.mts +29 -8
  32. package/dist/runtime/prefetch.mjs +95 -24
  33. package/dist/runtime/redirect.d.mts +13 -7
  34. package/dist/runtime/redirect.mjs +25 -9
  35. package/dist/runtime/request-scope.d.mts +37 -2
  36. package/dist/runtime/request-scope.mjs +60 -3
  37. package/dist/runtime/request.d.mts +6 -1
  38. package/dist/runtime/request.mjs +7 -2
  39. package/dist/runtime/route.d.mts +4 -2
  40. package/dist/runtime/route.mjs +13 -5
  41. package/dist/runtime/server.d.mts +5 -5
  42. package/dist/runtime/server.mjs +2 -2
  43. package/dist/runtime/shell.d.mts +2 -1
  44. package/dist/serve.d.mts +4 -0
  45. package/dist/serve.mjs +29 -14
  46. package/dist/static-Be3xIqd8.d.mts +62 -0
  47. package/dist/{static-file-BAjwBMMl.mjs → static-file-BS-WEiwu.mjs} +311 -134
  48. package/dist/{static-host-B-1fAfAw.mjs → static-host-tIDLqV8c.mjs} +1 -1
  49. package/dist/vercel.d.mts +18 -1
  50. package/dist/vercel.mjs +131 -19
  51. package/dist/vite.d.mts +6 -3
  52. package/dist/vite.mjs +366 -156
  53. package/docs/GUIDE.md +173 -46
  54. package/docs/llms.txt +129 -65
  55. package/docs/references/actions.md +14 -5
  56. package/docs/references/boundaries.md +23 -2
  57. package/docs/references/csp.md +91 -2
  58. package/docs/references/deploy.md +154 -25
  59. package/docs/references/errors.md +57 -12
  60. package/docs/references/guards.md +100 -29
  61. package/docs/references/params.md +234 -126
  62. package/docs/references/routing.md +358 -75
  63. package/package.json +18 -13
  64. package/dist/shared-dir-CNXFRZgP.mjs +0 -9
  65. package/dist/static-DnbgGIoy.d.mts +0 -61
@@ -1,27 +1,25 @@
1
- import { fileRequest, routeRequestOf } from "./request.mjs";
2
- import { answer, inPhase, signingNonce, withRequest, writingFile } from "./request-scope.mjs";
3
- import { methodNotAllowed, routeAnswerFor, runRoute } from "./route.mjs";
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";
6
- import { isPayloadPath, pagePathFor } from "./payload-path.mjs";
7
1
  import { noticeCancel } from "./cancel.mjs";
2
+ import { SAID_NOT_FOUND } from "./ended.mjs";
8
3
  import { runGuards } from "./guard.mjs";
9
4
  import { PageShown } from "./page-shown.mjs";
10
5
  import { watchPage } from "./page-watch.mjs";
11
6
  import { parseCatchAllParams, parseParams } from "./params.mjs";
12
- import { Redirect, resolveRedirects } from "./redirect.mjs";
7
+ import { NOT_FOUND_SEGMENT } from "./pathname.mjs";
8
+ 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";
9
+ import { isPayloadPath, pagePathFor } from "./payload-path.mjs";
10
+ import { Redirect, redirectResponse, resolveRedirects } from "./redirect.mjs";
13
11
  import { renderMatch, renderNotFound } from "./render.mjs";
12
+ import { fileRequest, routeRequestOf } from "./request.mjs";
13
+ import { answer, currentCookies, inPhase, signingNonce, withRequest, writingFile } from "./request-scope.mjs";
14
+ import { methodNotAllowed, routeAnswerFor, runRoute } from "./route.mjs";
14
15
  import { shellParams } from "./shell.mjs";
15
16
  import { isNotFound, normalizePathname, withBase, withoutBase } from "@k8ordo/router";
16
17
  import { jsx } from "react/jsx-runtime";
18
+ import "virtual:k8ordo/locales";
17
19
  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";
20
+ import { catchAllSchemas, fallbacks, guards, pageModules, paramSchemas, paths, redirects, routeModules, routes, searchReaders } from "virtual:k8ordo/routes";
19
21
  // src/runtime/entry.rsc.tsx
20
22
  const redirectFor = resolveRedirects(redirects);
21
- const redirectResponse = (to, status) => new Response(null, {
22
- status,
23
- headers: { location: to }
24
- });
25
23
  /**
26
24
  * Where Vite serves the application, as the build was told (`base`). A host
27
25
  * serving the client build's files needs it to find them — `serve` reads it
@@ -33,6 +31,62 @@ const base = import.meta.env.BASE_URL;
33
31
  * serves a build into files — as a static host would — or runs the handler.
34
32
  */
35
33
  const mode = import.meta.env.K8ORDO_MODE === "static" ? "static" : "server";
34
+ const filePayloads = /* @__PURE__ */ new WeakMap();
35
+ /**
36
+ * The payload a document written into a file was rendered from: what a
37
+ * request for that page's payload would answer, byte for byte, without
38
+ * rendering the page a second time. The build into files writes it beside
39
+ * the HTML, so a page reads its data once per build, and the HTML and the
40
+ * payload of a page can never be two renders that disagree. Kept by the
41
+ * answer itself, which under `'static'` is the handler's own — nothing there
42
+ * can add a header or a cookie for `answer()` to rebuild it around.
43
+ * `undefined` for any other answer, a running server's included.
44
+ */
45
+ const payloadOf = (response) => filePayloads.get(response);
46
+ /**
47
+ * The headers `framework({ headers })` declared for every response. Whatever
48
+ * serves the build's files reads them from here, since a file never passes
49
+ * through the handler.
50
+ */
51
+ const everyAnswer = import.meta.env.K8ORDO_HEADERS;
52
+ const declaredEntries = Object.entries(everyAnswer);
53
+ /**
54
+ * `response` carrying the declared headers it does not already have: what a
55
+ * guard.ts or a route.ts set for this request stays. Under `'static'` the
56
+ * answer becomes a file, which has no headers of its own to carry.
57
+ */
58
+ const withDeclared = (response) => {
59
+ if (import.meta.env.K8ORDO_MODE === "static") return response;
60
+ const missing = declaredEntries.filter(([name]) => !response.headers.has(name));
61
+ if (missing.length === 0) return response;
62
+ const merged = new Headers(response.headers);
63
+ for (const [name, value] of missing) merged.set(name, value);
64
+ return new Response(response.body, {
65
+ status: response.status,
66
+ statusText: response.statusText,
67
+ headers: merged
68
+ });
69
+ };
70
+ /**
71
+ * What a `paths.ts` answers when asked for its parameter's values, given the
72
+ * params above it as the build spelled them. The build into files, and
73
+ * `vite dev`, ask through here, from the RSC environment, so the file runs
74
+ * as the pages do — the application's aliases, and the module instances the
75
+ * pages read their data through. The params above are first read by the
76
+ * schemas of the layouts in the directories above the file's, and the file
77
+ * receives what they produced; when one of them refuses, the file is not
78
+ * asked and the answer is `null`. Otherwise whatever it returned is handed
79
+ * back as it is, as `values`: the build is what says a value is not one.
80
+ */
81
+ const pathValues = async (file, above) => {
82
+ const supply = paths[file];
83
+ if (supply === void 0) throw new Error(`${file} is not a paths.ts of this build`);
84
+ const accepted = parseParams(supply.schemas, above);
85
+ if (accepted === null) return null;
86
+ const { default: values } = await supply.load();
87
+ if (typeof values !== "function") throw new TypeError(`${file} has to export default a function returning its parameter's values`);
88
+ return { values: await values(accepted.params) };
89
+ };
36
90
  const NO_PARAMS = {
37
91
  params: {},
38
92
  enter: (fn) => fn()
@@ -195,13 +249,15 @@ const renderFailed = (error) => new Response(error instanceof Error ? error.mess
195
249
  * calls it per request; mode: 'static' calls it at build time, for each
196
250
  * route's HTML and again for its payload, and writes the answers to files.
197
251
  * What it knows of the mode is compiled in (`K8ORDO_MODE`): whether a page
198
- * gets the request, and whether a failed render may still stream.
252
+ * gets the request, and whether a failed render may still stream. `host` is
253
+ * what the caller offers beside the request — its `waitUntil` — and may be
254
+ * left out: the build, `vite dev` and `vite preview` hand none.
199
255
  */
200
- function handler(request) {
201
- return withRequest(request, async () => answer(await (import.meta.env.K8ORDO_MODE === "static" ? writingFile(() => respond(request).catch((error) => {
256
+ function handler(request, host) {
257
+ return withRequest(request, async () => withDeclared(answer(await (import.meta.env.K8ORDO_MODE === "static" ? writingFile(() => respond(request).catch((error) => {
202
258
  reportFailed("answering", new URL(request.url).pathname, error);
203
259
  return renderFailed(error);
204
- })) : respond(request))));
260
+ })) : respond(request)))), host);
205
261
  }
206
262
  const reportFailed = (doing, pathname, error) => {
207
263
  console.error(`k8ordo: ${doing} %s failed`, pathname, error);
@@ -220,22 +276,22 @@ const respond = async (request) => {
220
276
  const { match, parsed, leaf, shell } = found;
221
277
  const declared = match === null ? null : redirectFor(match.pattern, pathname);
222
278
  if (declared !== null) return answerRedirect(request, declared);
223
- if (match !== null && leaf !== void 0 && routeModules[match.pattern] !== void 0) return answerRoute(request, match, parsed, leaf, wantsPayload);
224
- const refused = await refusedBeforePage(request, url, found);
225
- if (refused !== null) return refused;
226
- const isAction = request.method === "POST";
279
+ const ended = match !== null && leaf !== void 0 && routeModules[match.pattern] !== void 0 ? await answerRoute(request, match, parsed, leaf, wantsPayload) : await refusedBeforePage(wantsPayload ? pageRequestOf(request, url, pathname) : request, found);
280
+ if (ended instanceof Response) return ended;
281
+ const disowned = ended === SAID_NOT_FOUND;
282
+ const isAction = request.method === "POST" && !disowned;
227
283
  const addressed = request.headers.get(ACTION_ID_HEADER) !== null;
228
284
  const temporaryReferences = createTemporaryReferenceSet();
229
285
  const action = isAction ? await parsed.enter(() => inPhase("action", () => runAction(request, temporaryReferences))) : {};
230
286
  if (action.redirect !== void 0 && !addressed) return redirectResponse(action.redirect, 303);
231
287
  const answersPayload = wantsPayload || addressed;
232
288
  const contentType = answersPayload ? PAYLOAD_TYPE : HTML_TYPE;
233
- const missing = match === null || match.pattern.endsWith("/*");
289
+ const missing = disowned || match === null || match.pattern.endsWith("/*");
234
290
  if (request.method === "HEAD" && missing) return new Response(null, {
235
291
  status: 404,
236
292
  headers: { "content-type": contentType }
237
293
  });
238
- const routeRequest = import.meta.env.K8ORDO_MODE === "server" ? routeRequestOf(request) : fileRequest;
294
+ const routeRequest = import.meta.env.K8ORDO_MODE === "server" ? routeRequestOf(request, currentCookies()) : fileRequest;
239
295
  const ssr = await import.meta.viteRsc.loadModule("ssr", "index");
240
296
  const readSearch = match === null || missing || leaf === void 0 ? void 0 : searchReaderOf(match.pattern, leaf);
241
297
  const search = readSearch?.(url.searchParams);
@@ -268,8 +324,9 @@ const respond = async (request) => {
268
324
  const page = match === null || missing || action.redirect !== void 0 || shown === void 0 ? null : watchPage(componentOf(shown), /* @__PURE__ */ jsx(PageShown, {}));
269
325
  let showsPage = page?.followed === true;
270
326
  let status = missing ? 404 : 200;
271
- let { enter } = parsed;
272
- let rendered = render(action.redirect === void 0 ? match === null ? renderNotFound(routes, pathname, routeRequest) : renderMatch(missing ? await withNotFound(match) : shell === void 0 ? match : {
327
+ const disownedBy = disowned ? await nearestNotFound() : null;
328
+ let { enter } = disownedBy ?? parsed;
329
+ let rendered = render(disownedBy === null ? action.redirect === void 0 ? match === null ? renderNotFound(routes, pathname, routeRequest) : renderMatch(missing ? await withNotFound(match) : shell === void 0 ? match : {
273
330
  ...match,
274
331
  params: shell.known
275
332
  }, {
@@ -279,7 +336,7 @@ const respond = async (request) => {
279
336
  page: page?.Page,
280
337
  search,
281
338
  shell: shell !== void 0
282
- }) : null, enter, readSearch === void 0 ? void 0 : url.search, shell === void 0 ? void 0 : (await nearestNotFound()).tree);
339
+ }) : null : disownedBy.tree, enter, readSearch === void 0 ? void 0 : url.search, shell === void 0 ? void 0 : (await nearestNotFound()).tree);
283
340
  if (page !== null && (!answersPayload || request.method === "HEAD")) {
284
341
  const answered = await pageAnswer(rendered, page);
285
342
  ({rendered} = answered);
@@ -348,11 +405,13 @@ const answerRoute = async (request, match, parsed, module, wantsPayload) => {
348
405
  params: parsed.params
349
406
  }));
350
407
  };
408
+ const pageRequestOf = (request, url, pathname) => request.method === "GET" || request.method === "HEAD" ? new Request(new URL(`${withBase(pathname)}${url.search}`, url), request) : request;
351
409
  /**
352
410
  * What answers a page's request before anything renders, if anything does: a
353
411
  * method a page does not take, a Server Action from another origin, a guard.
354
412
  */
355
- const refusedBeforePage = async (request, url, { match, parsed }) => {
413
+ const refusedBeforePage = async (request, { match, parsed }) => {
414
+ const url = new URL(request.url);
356
415
  if (!METHODS.includes(request.method)) return new Response("method not allowed", {
357
416
  status: 405,
358
417
  headers: { allow: METHODS.join(", ") }
@@ -398,15 +457,19 @@ const answerHtml = async (ssr, rendered, enter, { status, showsPage, carriesForm
398
457
  }
399
458
  });
400
459
  }
401
- const [forHtml, forNamed] = rendered.stream.tee();
402
- await drain(forNamed);
460
+ const [forHtml, forFile] = rendered.stream.tee();
461
+ const payload = await new Response(forFile).arrayBuffer();
462
+ const linked = /* @__PURE__ */ new Set();
403
463
  let body;
404
464
  try {
405
465
  const html = await enter(() => ssr.renderHtml(forHtml, {
406
466
  nonce: signingNonce(),
407
467
  showsPage,
408
468
  carriesFormState,
409
- named: [...rendered.named.values()]
469
+ named: [...rendered.named.values()],
470
+ linked: (href) => {
471
+ linked.add(href);
472
+ }
410
473
  }));
411
474
  body = await new Response(html).arrayBuffer();
412
475
  } catch (error) {
@@ -414,15 +477,18 @@ const answerHtml = async (ssr, rendered, enter, { status, showsPage, carriesForm
414
477
  }
415
478
  const failed = rendered.failures[0];
416
479
  if (failed !== void 0) return renderFailed(failed);
417
- return new Response(body, {
480
+ const response = new Response(body, {
418
481
  status,
419
482
  headers: {
420
483
  "content-type": HTML_TYPE,
421
484
  [NONCE_HEADER]: signingNonce(),
422
485
  [CLIENT_DEPS_HEADER]: clientDepsHeader(rendered.named.values()),
486
+ [SERVER_STYLESHEETS_HEADER]: serverStylesheetsHeader(linked),
423
487
  ...headers
424
488
  }
425
489
  });
490
+ filePayloads.set(response, payload);
491
+ return response;
426
492
  };
427
493
  /**
428
494
  * Where a page that said notFound() is sent: the catch-all the table answers
@@ -491,4 +557,4 @@ const renderPayload = (payload, enter, temporaryReferences) => {
491
557
  */
492
558
  const drain = (stream) => stream.pipeTo(new WritableStream()).catch(() => void 0);
493
559
  if (import.meta.hot) import.meta.hot.accept();
494
- export { base, handler as default, mode };
560
+ export { base, handler as default, everyAnswer as headers, mode, pathValues, payloadOf };
@@ -1,4 +1,5 @@
1
1
  import { ClientDeps } from "./payload.mjs";
2
+ import "virtual:k8ordo/locales";
2
3
  /**
3
4
  * The script every page's HTML loads, and so the client every payload is
4
5
  * rendered for. Exported for the RSC entry, which renders the payloads:
@@ -12,7 +13,7 @@ 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, showsPage, carriesFormState, named }: {
16
+ export declare function renderHtml(rscStream: ReadableStream<Uint8Array>, { nonce, showsPage, carriesFormState, named, linked }: {
16
17
  /**
17
18
  * The request's: every script written here carries it. What else does,
18
19
  * the application signed, and the policy that names it is the
@@ -32,4 +33,9 @@ export declare function renderHtml(rscStream: ReadableStream<Uint8Array>, { nonc
32
33
  * to its end: the HTML links each, rendered or not.
33
34
  */
34
35
  readonly named?: readonly ClientDeps[];
36
+ /**
37
+ * Under mode: 'static', handed each stylesheet a Server Component of the
38
+ * payload links, as the walk meets it: every one before the HTML is read.
39
+ */
40
+ readonly linked?: (href: string) => void;
35
41
  }): Promise<ReadableStream>;
@@ -1,14 +1,15 @@
1
- import { CLIENT_STYLESHEETS } from "./stylesheets.mjs";
2
- import { whenClientReady } from "./client-ready.mjs";
3
1
  import { AppRouter } from "./app-router.mjs";
4
2
  import { noticeCancel } from "./cancel.mjs";
3
+ import { whenClientReady } from "./client-ready.mjs";
5
4
  import { DocumentRoot } from "./document-root.mjs";
6
- import { PageShownContext } from "./page-shown.mjs";
7
5
  import { scriptsBeforeStylesheetsStream } from "./head-scripts.mjs";
6
+ import { PageShownContext } from "./page-shown.mjs";
7
+ import { CLIENT_STYLESHEETS } from "./stylesheets.mjs";
8
8
  import { use } from "react";
9
+ import { preinit, preloadModule } from "react-dom";
9
10
  import { jsx } from "react/jsx-runtime";
11
+ import "virtual:k8ordo/locales";
10
12
  import { createFromReadableStream, getClientEntryUrl } from "@vitejs/plugin-rsc/ssr";
11
- import { preinit, preloadModule } from "react-dom";
12
13
  import { renderToReadableStream } from "react-dom/server.edge";
13
14
  import { injectRSCPayload } from "rsc-html-stream/server";
14
15
  import assetsManifest from "virtual:vite-rsc/assets-manifest";
@@ -51,7 +52,7 @@ const linkClientDeps = (named) => {
51
52
  * one round trip. It is also what lets a prerendered `404.html` come alive —
52
53
  * there is no payload file at a URL the application does not have.
53
54
  */
54
- async function renderHtml(rscStream, { nonce, showsPage, carriesFormState, named = [] }) {
55
+ async function renderHtml(rscStream, { nonce, showsPage, carriesFormState, named = [], linked }) {
55
56
  const [forRender, forHydration] = rscStream.tee();
56
57
  let forHtml = forRender;
57
58
  let formState;
@@ -66,7 +67,12 @@ async function renderHtml(rscStream, { nonce, showsPage, carriesFormState, named
66
67
  linkClientDeps(named);
67
68
  reading ??= createFromReadableStream(forHtml, { nonce });
68
69
  const payload = use(reading);
69
- ready ??= whenClientReady([payload.tree, payload.notFound], { rows: import.meta.env.K8ORDO_MODE === "static" ? "wait" : "follow" });
70
+ ready ??= whenClientReady([payload.tree, payload.notFound], {
71
+ rows: import.meta.env.K8ORDO_MODE === "static" ? "wait" : "follow",
72
+ element: linked === void 0 ? void 0 : ({ type, props }) => {
73
+ if (type === "link" && props.precedence === "vite-rsc/importer-resources" && typeof props.href === "string") linked(props.href);
74
+ }
75
+ });
70
76
  use(ready);
71
77
  return /* @__PURE__ */ jsx(AppRouter, { arrived: payload });
72
78
  }
@@ -1,28 +1,33 @@
1
- import { ParamsOf } from "@k8ordo/router";
1
+ import { SaidNotFound } from "./ended.mjs";
2
+ import { Match, ParamsOf } from "@k8ordo/router";
2
3
  /**
3
- * What a `guard.ts` receives: the request, and the params of the pattern its
4
- * directory puts it under, as the strings the pathname carried — a guard runs
5
- * above the page and every layout, where no schema has typed them.
4
+ * What a `guard.ts` receives: the request for the page — a client
5
+ * navigation's payload request too, under the page's URL — and the params of
6
+ * the pattern its directory puts it under, as the pathname carried them — a
7
+ * string each, a rest param its segments — since a guard runs above the page
8
+ * and every layout, where no schema has typed them.
6
9
  */
7
10
  export type GuardContext<P extends string = string> = {
8
11
  readonly request: Request;
9
12
  readonly params: ParamsOf<P>;
10
13
  };
11
14
  /**
12
- * What a `guard.ts` default-exports. A `Response` ends the request there — a
13
- * redirect, a `401` — and returning nothing lets it through to what answers
14
- * below. There is no `next()` to run the page and rewrite its answer: a page
15
- * streams, and its headers leave before its body is written.
15
+ * What a `guard.ts` default-exports. `redirect(url)` ends the request there
16
+ * with a `303`, `notFound()` with the nearest not-found.tsx under 404, and a
17
+ * `Response` returned — a `401`, a `403` — is the answer itself; returning
18
+ * nothing lets it through to what answers below. There is no `next()` to run
19
+ * the page and rewrite its answer: a page streams, and its headers leave
20
+ * before its body is written.
16
21
  */
17
22
  export type Guard<P extends string = string> = (context: GuardContext<P>) => Response | void | Promise<Response | void>;
18
23
  type AnyGuard = (context: {
19
24
  readonly request: Request;
20
- readonly params: Readonly<Record<string, string>>;
25
+ readonly params: Match['params'];
21
26
  }) => unknown;
22
27
  /**
23
28
  * Runs the guards along a pattern, outer first, one at a time: an outer guard
24
29
  * that ends the request leaves the inner ones unrun, which is what lets an
25
30
  * inner guard assume what an outer one checked.
26
31
  */
27
- export declare const runGuards: (guards: readonly AnyGuard[], context: Parameters<AnyGuard>[0]) => Promise<Response | null>;
32
+ export declare const runGuards: (guards: readonly AnyGuard[], context: Parameters<AnyGuard>[0]) => Promise<Response | SaidNotFound | null>;
28
33
  export {};
@@ -1,3 +1,4 @@
1
+ import { endedBy } from "./ended.mjs";
1
2
  import { inPhase } from "./request-scope.mjs";
2
3
  // src/runtime/guard.ts
3
4
  /**
@@ -7,9 +8,14 @@ import { inPhase } from "./request-scope.mjs";
7
8
  */
8
9
  const runGuards = async (guards, context) => {
9
10
  for (const guard of guards) {
10
- const answer = await inPhase("guard", () => guard(context));
11
+ let answer;
12
+ try {
13
+ answer = await inPhase("guard", () => guard(context));
14
+ } catch (error) {
15
+ return endedBy(error);
16
+ }
11
17
  if (answer === void 0) continue;
12
- if (!(answer instanceof Response)) throw new TypeError("a guard.ts returns a Response to end the request, or nothing to let it through");
18
+ if (!(answer instanceof Response)) throw new TypeError("a guard.ts ends the request with redirect() or notFound(), or by returning a Response, and returns nothing to let it through");
13
19
  return answer;
14
20
  }
15
21
  return null;
@@ -1,6 +1,6 @@
1
- import { hydrateAs } from "./hydrating-pathname.mjs";
2
1
  import { AppRouter } from "./app-router.mjs";
3
2
  import { DocumentRoot } from "./document-root.mjs";
3
+ import { hydrateAs } from "./hydrating-pathname.mjs";
4
4
  import { normalizePathname, withoutBase } from "@k8ordo/router";
5
5
  import { jsx } from "react/jsx-runtime";
6
6
  import { hydrateRoot } from "react-dom/client";
@@ -1,8 +1,8 @@
1
1
  "use client";
2
- import { saysNotFound } from "./says-not-found.mjs";
3
2
  import { FallbackCatch } from "./fallback-boundary.mjs";
4
- import { reloadDocument } from "./reload.mjs";
5
3
  import { isNavigated } from "./recover.mjs";
4
+ import { reloadDocument } from "./reload.mjs";
5
+ import { saysNotFound } from "./says-not-found.mjs";
6
6
  import { Component } from "react";
7
7
  // src/runtime/page-boundary.tsx
8
8
  /** Whether the boundary answers `error` with a document load. */
@@ -1,3 +1,4 @@
1
+ import { Match } from "@k8ordo/router";
1
2
  /**
2
3
  * A route file's `paramsSchema` export, in the one shape every validation library
3
4
  * agrees on (Standard Schema). The framework runs it; the router only types
@@ -23,8 +24,8 @@ export type ParsedParams = {
23
24
  };
24
25
  /**
25
26
  * Runs the schemas along a matched stack — outer layouts first, the page
26
- * last — over the raw params, each replacing the strings it names with what
27
- * it produced. `null` means some schema refused, which is the pattern not
27
+ * last — over the raw params (a string each, a rest param its segments), each
28
+ * replacing the ones it names with what it produced. `null` means some schema refused, which is the pattern not
28
29
  * answering this pathname at all.
29
30
  *
30
31
  * A schema may write to the async context it runs in — `@k8ordo/i18n`
@@ -34,7 +35,7 @@ export type ParsedParams = {
34
35
  * never to the caller: the static build calls the handler for every page
35
36
  * from one context.
36
37
  */
37
- export declare const parseParams: (schemas: readonly ParamsSchema[], raw: Readonly<Record<string, string>>) => ParsedParams | null;
38
+ export declare const parseParams: (schemas: readonly ParamsSchema[], raw: Match['params']) => ParsedParams | null;
38
39
  /**
39
40
  * The layouts' schemas above a not-found, run over the catch-all's params for
40
41
  * what they write — never to refuse it: a catch-all answers what nothing else
@@ -44,5 +45,5 @@ export declare const parseParams: (schemas: readonly ParamsSchema[], raw: Readon
44
45
  * strings the pathname carried either way, which is what a not-found's type
45
46
  * says.
46
47
  */
47
- export declare const parseCatchAllParams: (schemas: readonly ParamsSchema[], raw: Readonly<Record<string, string>>) => ParsedParams;
48
+ export declare const parseCatchAllParams: (schemas: readonly ParamsSchema[], raw: Match['params']) => ParsedParams;
48
49
  export {};
@@ -2,8 +2,8 @@ import { AsyncLocalStorage, AsyncResource } from "node:async_hooks";
2
2
  // src/runtime/params.ts
3
3
  /**
4
4
  * Runs the schemas along a matched stack — outer layouts first, the page
5
- * last — over the raw params, each replacing the strings it names with what
6
- * it produced. `null` means some schema refused, which is the pattern not
5
+ * last — over the raw params (a string each, a rest param its segments), each
6
+ * replacing the ones it names with what it produced. `null` means some schema refused, which is the pattern not
7
7
  * answering this pathname at all.
8
8
  *
9
9
  * A schema may write to the async context it runs in — `@k8ordo/i18n`
@@ -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 };
@@ -25,18 +25,38 @@ export declare const prefetchTargetOf: (target: EventTarget | null) => URL | nul
25
25
  * returns what stops it.
26
26
  */
27
27
  export declare const prefetchOnIntent: (prefetch: (url: URL) => Promise<unknown>) => (() => void);
28
+ /**
29
+ * How long a link stays on screen before it is fetched ahead, in
30
+ * milliseconds. A link scrolled past is not one the visitor stopped at, and a
31
+ * link that just came into view may not be the one they tap.
32
+ */
33
+ export declare const IN_VIEW_DWELL = 1000;
34
+ /** What watches the links on screen. */
35
+ export type InView = {
36
+ /** Stops watching: nothing more is fetched. */
37
+ readonly stop: () => void;
38
+ /**
39
+ * Says where a page change is loading — a pathname in the table's terms,
40
+ * as `usePendingPathname` names it — or that none is (`null`). While one
41
+ * loads nothing more is fetched, and a prefetch on its way to another page
42
+ * is called off, its link put first in line again.
43
+ */
44
+ readonly pending: (pathname: string | null) => void;
45
+ };
28
46
  /**
29
47
  * Prefetches the links on screen (`prefetchInView`) while the primary pointer
30
- * is coarse, and returns what stops it.
48
+ * is coarse.
31
49
  */
32
- export declare const prefetchInViewUnderTouch: (prefetch: (url: URL) => Promise<unknown>) => (() => void);
50
+ export declare const prefetchInViewUnderTouch: (prefetch: (url: URL, signal: AbortSignal) => Promise<unknown>) => InView;
33
51
  /**
34
52
  * Prefetches the links on screen, one at a time, in the order they came into
35
- * view, and returns what stops it. A link that leaves before its turn is
36
- * passed over, so a fast scroll fetches little; one at a time, so a page
37
- * visited while they load shares the connection with one prefetch at most.
53
+ * view, once each has stayed there `IN_VIEW_DWELL` and the document has
54
+ * loaded. A link that leaves before its turn is passed over, so a fast
55
+ * scroll fetches little; one at a time, so a page visited while they load
56
+ * shares the connection with one prefetch at most, and with none once the
57
+ * page change is known (`pending`).
38
58
  */
39
- export declare const prefetchInView: (prefetch: (url: URL) => Promise<unknown>) => (() => void);
59
+ export declare const prefetchInView: (prefetch: (url: URL, signal: AbortSignal) => Promise<unknown>) => InView;
40
60
  /**
41
61
  * Where a page's load is handed to navigations from. Two kinds, by what a
42
62
  * page's payload is:
@@ -58,9 +78,10 @@ export declare const prefetchInView: (prefetch: (url: URL) => Promise<unknown>)
58
78
  export type PageCache<T> = {
59
79
  /**
60
80
  * Starts loading `key` unless a usable load of it is held, and returns the
61
- * held load.
81
+ * held load. `signal` aborting forgets a load this call started, while it
82
+ * is on its way and no navigation waits for it.
62
83
  */
63
- readonly prefetch: (key: string, priority: RequestPriority) => Promise<T>;
84
+ readonly prefetch: (key: string, priority: RequestPriority, signal?: AbortSignal) => Promise<T>;
64
85
  /**
65
86
  * What a navigation to `key` renders: a usable load held, or one started
66
87
  * for it. While it is on its way, `signal` aborting aborts it, as it would