@nifrajs/web 3.1.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/dist/build-plan.d.ts +228 -0
  2. package/dist/build-plan.d.ts.map +1 -0
  3. package/dist/build-plan.js +514 -0
  4. package/dist/build-plan.js.map +1 -0
  5. package/dist/build-vite.d.ts +2 -1
  6. package/dist/build-vite.d.ts.map +1 -1
  7. package/dist/build-vite.js.map +1 -1
  8. package/dist/build.d.ts +2 -197
  9. package/dist/build.d.ts.map +1 -1
  10. package/dist/build.js +61 -502
  11. package/dist/build.js.map +1 -1
  12. package/dist/chunk-names.d.ts.map +1 -1
  13. package/dist/chunk-names.js +3 -2
  14. package/dist/chunk-names.js.map +1 -1
  15. package/dist/dev-ssr-graph.d.ts.map +1 -1
  16. package/dist/dev-ssr-graph.js +63 -28
  17. package/dist/dev-ssr-graph.js.map +1 -1
  18. package/dist/diagnostic.d.ts.map +1 -1
  19. package/dist/diagnostic.js +9 -2
  20. package/dist/diagnostic.js.map +1 -1
  21. package/dist/fonts-google.d.ts.map +1 -1
  22. package/dist/fonts-google.js +3 -1
  23. package/dist/fonts-google.js.map +1 -1
  24. package/dist/fs.d.ts.map +1 -1
  25. package/dist/fs.js +2 -1
  26. package/dist/fs.js.map +1 -1
  27. package/dist/index.d.ts +15 -609
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +22 -1935
  30. package/dist/index.js.map +1 -1
  31. package/dist/internal/codegen.d.ts +68 -0
  32. package/dist/internal/codegen.d.ts.map +1 -0
  33. package/dist/internal/codegen.js +317 -0
  34. package/dist/internal/codegen.js.map +1 -0
  35. package/dist/internal/head-merge.d.ts +2 -0
  36. package/dist/internal/head-merge.d.ts.map +1 -1
  37. package/dist/internal/head-merge.js +17 -1
  38. package/dist/internal/head-merge.js.map +1 -1
  39. package/dist/internal/parity.d.ts +7 -0
  40. package/dist/internal/parity.d.ts.map +1 -1
  41. package/dist/internal/parity.js +212 -30
  42. package/dist/internal/parity.js.map +1 -1
  43. package/dist/internal/render-document.d.ts +372 -0
  44. package/dist/internal/render-document.d.ts.map +1 -0
  45. package/dist/internal/render-document.js +744 -0
  46. package/dist/internal/render-document.js.map +1 -0
  47. package/dist/internal/runtime-contract.d.ts +48 -0
  48. package/dist/internal/runtime-contract.d.ts.map +1 -0
  49. package/dist/internal/runtime-contract.js +27 -0
  50. package/dist/internal/runtime-contract.js.map +1 -0
  51. package/dist/internal/web-app.d.ts +171 -0
  52. package/dist/internal/web-app.d.ts.map +1 -0
  53. package/dist/internal/web-app.js +844 -0
  54. package/dist/internal/web-app.js.map +1 -0
  55. package/dist/islands.d.ts +48 -0
  56. package/dist/islands.d.ts.map +1 -1
  57. package/dist/islands.js +79 -0
  58. package/dist/islands.js.map +1 -1
  59. package/dist/module-graph.d.ts.map +1 -1
  60. package/dist/module-graph.js +22 -9
  61. package/dist/module-graph.js.map +1 -1
  62. package/dist/nano.d.ts +125 -0
  63. package/dist/nano.d.ts.map +1 -0
  64. package/dist/nano.js +190 -0
  65. package/dist/nano.js.map +1 -0
  66. package/dist/plugins/css-modules.js +2 -2
  67. package/dist/plugins/css-modules.js.map +1 -1
  68. package/dist/plugins/kit.d.ts +12 -0
  69. package/dist/plugins/kit.d.ts.map +1 -1
  70. package/dist/plugins/kit.js +62 -12
  71. package/dist/plugins/kit.js.map +1 -1
  72. package/dist/plugins/postcss.js +2 -2
  73. package/dist/plugins/postcss.js.map +1 -1
  74. package/dist/plugins/scss.js +2 -2
  75. package/dist/plugins/scss.js.map +1 -1
  76. package/dist/plugins/stylex.d.ts +70 -0
  77. package/dist/plugins/stylex.d.ts.map +1 -0
  78. package/dist/plugins/stylex.js +166 -0
  79. package/dist/plugins/stylex.js.map +1 -0
  80. package/dist/plugins/svg.js +2 -2
  81. package/dist/plugins/svg.js.map +1 -1
  82. package/dist/router.d.ts +1 -1
  83. package/dist/router.js +23 -23
  84. package/dist/router.js.map +1 -1
  85. package/dist/vite.d.ts.map +1 -1
  86. package/dist/vite.js +26 -10
  87. package/dist/vite.js.map +1 -1
  88. package/package.json +39 -3
  89. package/src/build-plan.ts +741 -0
  90. package/src/build-vite.ts +1 -4
  91. package/src/build.ts +84 -716
  92. package/src/chunk-names.ts +3 -2
  93. package/src/dev-ssr-graph.ts +63 -28
  94. package/src/diagnostic.ts +14 -2
  95. package/src/fonts-google.ts +3 -1
  96. package/src/fs.ts +2 -1
  97. package/src/index.ts +73 -2705
  98. package/src/internal/codegen.ts +400 -0
  99. package/src/internal/head-merge.ts +19 -1
  100. package/src/internal/parity.ts +215 -35
  101. package/src/internal/render-document.ts +1116 -0
  102. package/src/internal/runtime-contract.ts +54 -0
  103. package/src/internal/web-app.ts +1114 -0
  104. package/src/islands.ts +85 -0
  105. package/src/module-graph.ts +23 -9
  106. package/src/nano.ts +246 -0
  107. package/src/plugins/css-modules.ts +2 -2
  108. package/src/plugins/kit.ts +65 -12
  109. package/src/plugins/postcss.ts +2 -2
  110. package/src/plugins/scss.ts +2 -2
  111. package/src/plugins/stylex.ts +298 -0
  112. package/src/plugins/svg.ts +2 -2
  113. package/src/router.ts +24 -24
  114. package/src/vite.ts +33 -9
package/dist/index.js CHANGED
@@ -7,28 +7,32 @@
7
7
  * the adapter interprets them. That keeps this package both framework-agnostic and free
8
8
  * of DOM types: it is pure server orchestration + string building.
9
9
  */
10
- import { NIFRA_BACKEND_MOUNT, } from "@nifrajs/core/mount";
11
- import { isSameOriginPath, server, status as statusResult, urlPartsOf, } from "@nifrajs/core/server";
12
- import { boundaryDescriptors, resolveStaticBoundaries, startDynamicBoundaries, } from "./boundary.js";
13
- import { DEFERRED_ERROR_CODE, DEFERRED_RUNTIME, defer, MAP_DEFERRED_SOURCE, ndjsonStream, prepareDeferred, } from "./deferred.js";
14
- import { isDraftEnabled } from "./draft.js";
15
- import { trustedHeadAttributes } from "./internal/head-attributes.js";
16
- // Head resolution/merging. Defined in an internal module so `@nifrajs/web/client` can export the same
17
- // two functions to the generated client entry without dragging THIS module (and its server code) into
18
- // the browser graph - see internal/head-merge.ts. Re-exported here so the public API is unchanged.
19
- import { mergeHeads, resolveMeta } from "./internal/head-merge.js";
20
- import { jsStringLiteral } from "./internal/js-string.js";
21
- import { EXECUTABLE_SCRIPT_TYPES, INERT_SCRIPT_TYPES } from "./internal/script-types.js";
22
- import { ISR_REVALIDATE_HEADER, ISR_REVALIDATE_TAGS_HEADER, serializeISRTags } from "./isr.js";
23
- import { generateLlmsTxt } from "./llms-txt.js";
24
- import { ACTION_GLOBAL, BOUNDARY_GLOBAL, DATA_GLOBAL, LAYOUT_DATA_GLOBAL, ROOT_ATTRIBUTE, ROUTE_GLOBAL, } from "./render-seam.js";
25
- import { createMatcher, DATA_HEADER, NAV_FROM_HEADER, PRERENDERED_GLOBAL, REDIRECT_HEADER, RETAIN_HEADER, REVALIDATE_HEADER, STATUS_HEADER, } from "./router.js";
26
- import { searchOf, searchOfChain } from "./search.js";
27
10
  // Draft / preview mode - a signed cookie that flips `ctx.draft` for loaders + bypasses ISR for editors.
28
11
  export { assertStaticBoundaryImports, boundaryDescriptors, boundaryModeKey, MemoryStaticBoundaryCache, resolveDynamicBoundaries, resolveStaticBoundaries, startDynamicBoundaries, } from "./boundary.js";
12
+ export { assertRenderAdapterConformance, RenderAdapterConformanceError, } from "./conformance.js";
13
+ // Deferred loader data (`defer()` + the `Deferred<T>` type) - consumed by the adapter's `<Await>`.
14
+ export { defer } from "./deferred.js";
29
15
  export { DRAFT_COOKIE, disableDraft, enableDraft, isDraftEnabled, previewEndpoint, } from "./draft.js";
30
16
  // Font optimization - a CLS-safe `@font-face` generator + a preload `<link>` for self-hosted fonts.
31
17
  export { fontFace, fontPreload, } from "./fonts.js";
18
+ export { generateClientEntry, generateRouteSearchTypes, generateServerManifest, } from "./internal/codegen.js";
19
+ // Generated client entries intentionally import the browser router from the client subpath:
20
+ // `import { createClientRouter, createMatcher, mergeHeads, resolveMeta } from "@nifrajs/web/client"`.
21
+ export { mergeHeads, resolveMeta } from "./internal/head-merge.js";
22
+ export { canonical, gone, jsonLd, notFound, openGraph, redirect, renderPage, renderPageResult, revalidate, serializeData, statusPage, unsafeInlineScript, } from "./internal/render-document.js";
23
+ export { DEFAULT_DEV_PORT, PRE_HYDRATION_GUARD, } from "./internal/runtime-contract.js";
24
+ /**
25
+ * The two file-name conventions that decide what never reaches a browser: a `*.server` module is
26
+ * EMPTIED in the client build, a `*.fn` module is REPLACED with client stubs.
27
+ *
28
+ * Exported because more than the bundlers need them. `nifra dev --bun` cannot transform (Bun's dev
29
+ * bundler takes no plugins) so it must REFUSE instead, and a refusal driven by its own hand-written
30
+ * glob drifts from the transform - which is how `.fn.mts` came to be stubbed by both build pipelines
31
+ * and waved through by the guard that exists to stop it leaking. Anything deciding "is this module
32
+ * server-only" should import the matcher rather than re-encode it.
33
+ */
34
+ export { SERVER_FN_MODULE, SERVER_ONLY_MODULE } from "./internal/server-boundary.js";
35
+ export { createWebApp, } from "./internal/web-app.js";
32
36
  // ISR (incremental static regeneration): a pluggable cache store + the `withISR` stale-while-revalidate
33
37
  // wrapper for rendered SSR responses.
34
38
  export { ISR_REVALIDATE_HEADER, ISR_REVALIDATE_TAGS_HEADER, ISR_STATUS_HEADER, KVCacheStore, MemoryCacheStore, revalidateEndpoint, withISR, } from "./isr.js";
@@ -42,1930 +46,13 @@ export { resolvePublicPath, servePublicDir, } from "./public-dir.js";
42
46
  // Keyed query-cache (agnostic) - a `query(key, fn)` primitive (dedup + staleness + invalidation + GC)
43
47
  // consumed by the per-adapter `useQuery`/`createQuery` bindings.
44
48
  export { createMutation, createQueryClient, hashQueryKey, } from "./query.js";
49
+ export { ACTION_GLOBAL, BOUNDARY_GLOBAL, DATA_GLOBAL, LAYOUT_DATA_GLOBAL, ROOT_ATTRIBUTE, ROUTE_GLOBAL, setSsrModuleLoader, ssrModuleLoader, } from "./render-seam.js";
45
50
  // Agnostic client-side router core (pure + DOM-free) - consumed by per-adapter Router bindings.
46
51
  // `DATA_HEADER` marks a navigation's data-only GET; `createWebApp` answers it with loader JSON.
47
52
  export { createClientRouter, createMatcher, DATA_HEADER, NAV_FROM_HEADER, REDIRECT_HEADER, RETAIN_HEADER, REVALIDATE_HEADER, STATUS_HEADER, } from "./router.js";
48
- // Deferred loader data (`defer()` + the `Deferred<T>` type) - consumed by the adapter's `<Await>`.
49
- export { defer, mergeHeads, resolveMeta };
50
- export { assertRenderAdapterConformance, RenderAdapterConformanceError, } from "./conformance.js";
51
- export { ACTION_GLOBAL, BOUNDARY_GLOBAL, DATA_GLOBAL, LAYOUT_DATA_GLOBAL, ROOT_ATTRIBUTE, ROUTE_GLOBAL, setSsrModuleLoader, ssrModuleLoader, } from "./render-seam.js";
52
53
  // The search-derivation primitive: parse a URL query, validate it against a route's `searchSchema`
53
54
  // (fail-closed to defaults), or return the raw parsed query when there is none. Both the server (loader
54
55
  // ctx + `renderPage`) and a client adapter mount call this with the same URL + schema, so the two sides
55
56
  // produce the identical value by construction. An adapter's `useSearch` binding reads its result.
56
57
  export { searchOf, searchOfChain, serializeSearch } from "./search.js";
57
- /**
58
- * Pre-hydration form guard - a tiny inline script flushed in `<head>` (it runs in the window between
59
- * first paint and the island bundle taking over). It neutralizes the one real hydration footgun: a
60
- * JS-only form (a hand-wired `onSubmit` with no native fallback) submitting *natively* before its
61
- * handler is attached, which navigates the browser to a broken `?field=…` GET of the current page.
62
- *
63
- * It blocks ONLY that shape - an effective-GET form whose action targets the current document - and
64
- * only until hydration commits (`data-nifra-hydrated`, set by the client entry). Method-`post` forms
65
- * (progressive enhancement: the native POST hits the route `action`) and GET forms with a real action
66
- * (a search box → `/search`) pass through untouched. Opt out per-form with `data-native`. Static text
67
- * (no interpolation), so it can't carry injected markup. See the Hydration guide.
68
- */
69
- export const PRE_HYDRATION_GUARD = "(function(){addEventListener('submit',function(e){var f=e.target;" +
70
- "if(!f||f.tagName!=='FORM'||f.hasAttribute('data-native'))return;" +
71
- "if(document.documentElement.hasAttribute('data-nifra-hydrated'))return;" +
72
- "var m=(f.getAttribute('method')||'get').toLowerCase();if(m==='post')return;" +
73
- "var a=f.getAttribute('action');" +
74
- "if(!a||a===''||a==='#'||a===location.pathname||a===location.href)e.preventDefault()" +
75
- "},true)})()";
76
- /**
77
- * The single default port for the dev server (`@nifrajs/web/dev`, `@nifrajs/web/vite`) **and**
78
- * `nifra start`. Deliberately uncommon: `3000`/`5173`/`8080` collide with whatever else is running
79
- * (Next, Vite, a stray Node API). `4321` rarely is - and being the *same* constant across `nifra dev`
80
- * and `nifra start` means a project's URL doesn't change between commands. Override per-run with
81
- * `--port <n>` or the `PORT` env var. */
82
- export const DEFAULT_DEV_PORT = 4321;
83
- // Shared, stateless - allocated once at module load, not per render/stream.
84
- const TEXT_ENCODER = new TextEncoder();
85
- // XSS-safe `<script>` JSON escaping in a SINGLE pass: `<`/`>` would break out of the
86
- // script element; U+2028/U+2029 are valid JSON but historically break JS string literals. Built via
87
- // fromCharCode so no raw separator chars live in this source. One regex + one output string replaces
88
- // the prior four sequential `replaceAll` full-string passes.
89
- const LINE_SEP = String.fromCharCode(0x2028);
90
- const PARA_SEP = String.fromCharCode(0x2029);
91
- const SCRIPT_ESCAPE = new RegExp(`[<>${LINE_SEP}${PARA_SEP}]`, "g");
92
- const SCRIPT_ESCAPE_MAP = {
93
- "<": "\\u003c",
94
- ">": "\\u003e",
95
- [LINE_SEP]: "\\u2028",
96
- [PARA_SEP]: "\\u2029",
97
- };
98
- const NODE_RESPONSE_BODY = Symbol.for("nifra.response.body");
99
- const RESPONSE_RESULT = Symbol.for("nifra.response.result");
100
- /**
101
- * A control-flow value that renders as plain data - what `redirect()` returns, and what core's
102
- * `status(...)` returns. Recognized here rather than imported: core keeps its own predicate internal,
103
- * and the registry symbol is the contract between them (two copies of core must still agree).
104
- */
105
- const isResponseResult = (value) => typeof value === "object" &&
106
- value !== null &&
107
- value[RESPONSE_RESULT] === true &&
108
- typeof value.toResponse === "function";
109
- /** A returned/thrown value that ends the request as-is: either shape of control-flow signal. */
110
- const isControlFlow = (value) => value instanceof Response || isResponseResult(value);
111
- /**
112
- * Server: render a full HTML document for a page - the adapter's hydration head + the SSR
113
- * markup (**streamed**) + the serialized loader data + the client module - as a `Response`.
114
- * The shell (`<head>` + the open container) flushes first, the adapter's app stream follows,
115
- * then the tail (data globals + client entry). Pure Web Standards, so it returns straight from
116
- * a nifra route handler and streams on any fetch runtime (Bun/Node/Deno/Workers).
117
- */
118
- export function renderPage(options) {
119
- const page = renderPageResult(options);
120
- return page instanceof Promise ? page.then((p) => p.toResponse()) : page.toResponse();
121
- }
122
- export function renderPageResult(options) {
123
- const { adapter, chain, data, actionData, clientEntry, preload = [], styles = [], prerenderedPaths = [], revalidate, revalidateTags = [], routeId, status = 200, title = "nifra", head, rootId = "root", hydrate = true, islandScripts = [], nonce, boundaries, headers: extraHeaders, } = options;
124
- if (nonce !== undefined && nonce.trim() === "") {
125
- throw new TypeError("[nifra/web] renderPage nonce must be non-empty when provided");
126
- }
127
- const nonceAttr = nonce === undefined ? "" : ` nonce="${escapeAttr(nonce)}"`;
128
- const route = routeId === undefined ? "" : `window.${ROUTE_GLOBAL}=${serializeData(routeId)};`;
129
- // The SSG prerendered-path set (when an app declares it) - the client reads it to fetch a static
130
- // `_data.json` on soft-nav into a prerendered route instead of hitting the worker. Empty ⇒ omitted.
131
- const prerendered = prerenderedPaths.length === 0
132
- ? ""
133
- : `window.${PRERENDERED_GLOBAL}=${serializeData(prerenderedPaths)};`;
134
- // Split deferred values: the component sees markers (id + promise) to `<Await>`; the serialized
135
- // data carries `{__nifra_deferred: id}` placeholders (promises don't serialize). `actionData` may
136
- // also `defer()` - split it too, continuing the id space so a single registry settles both. The
137
- // inline registry runtime is emitted only when something defers, so non-deferred output is unchanged.
138
- const { forComponent, forClient, deferred } = prepareDeferred(data);
139
- // Each layout's data is split in turn, each continuing the id space, so a `defer()` in a layout
140
- // settles through the SAME registry as the page's rather than colliding on ids.
141
- const layoutSplits = [];
142
- if (options.layoutData !== undefined) {
143
- let offset = deferred.length;
144
- for (const entry of options.layoutData) {
145
- const split = prepareDeferred(entry, offset);
146
- offset += split.deferred.length;
147
- layoutSplits.push(split);
148
- }
149
- }
150
- const layoutDeferred = layoutSplits.flatMap((split) => split.deferred);
151
- const actionSplit = actionData === undefined
152
- ? undefined
153
- : prepareDeferred(actionData, deferred.length + layoutDeferred.length);
154
- const boundarySplit = boundaries === undefined
155
- ? undefined
156
- : prepareDeferred(boundaries, deferred.length + layoutDeferred.length + (actionSplit?.deferred.length ?? 0));
157
- // On the common page-only path (no layout loader, no action) reuse `deferred` directly instead of
158
- // allocating a fresh spread array every request.
159
- const allDeferred = layoutDeferred.length === 0 && actionSplit === undefined && boundarySplit === undefined
160
- ? deferred
161
- : [
162
- ...deferred,
163
- ...layoutDeferred,
164
- ...(actionSplit ? actionSplit.deferred : []),
165
- ...(boundarySplit ? boundarySplit.deferred : []),
166
- ];
167
- // Omitted entirely when no layout has a loader - a page-only app emits exactly what it did before.
168
- const layoutTail = options.layoutData === undefined
169
- ? ""
170
- : `window.${LAYOUT_DATA_GLOBAL}=${serializeData(layoutSplits.map((split) => split.forClient))};`;
171
- // Only emit the action global when an action actually ran, so plain GET output is unchanged.
172
- const action = actionSplit === undefined
173
- ? ""
174
- : `window.${ACTION_GLOBAL}=${serializeData(actionSplit.forClient)};`;
175
- const boundaryTail = boundarySplit === undefined
176
- ? ""
177
- : `window.${BOUNDARY_GLOBAL}=${serializeData(boundarySplit.forClient)};`;
178
- const deferredRuntime = allDeferred.length > 0 ? `<script${nonceAttr}>${DEFERRED_RUNTIME}</script>` : "";
179
- // The regex only injects the CSP nonce into the (constant) hydration head; with no nonce it's a
180
- // no-op that still scans the whole script every request. Skip it on the common no-nonce path.
181
- // The request-invariant document pieces. With a caller-supplied per-route cache (and no per-request
182
- // nonce, which would bake into them) they're built once and reused; the per-request seams - the
183
- // deferred runtime in the shell, the action/layout-data globals and the serialized loader data in
184
- // the tail - are always assembled fresh. Byte-identical to building the whole document inline.
185
- const slot = nonce === undefined && options.assemblyCache !== undefined ? options.assemblyCache : {};
186
- if (slot.shellPre === undefined) {
187
- // Matched-route chunk preloads, concatenated directly. De-duped against the entry, which is
188
- // preloaded separately below.
189
- let preloadLinks = "";
190
- for (const url of preload) {
191
- if (url !== clientEntry)
192
- preloadLinks += `<link rel="modulepreload" href="${escapeAttr(url)}">`;
193
- }
194
- // The matched route's stylesheets - `<link rel="stylesheet">` in `<head>` so CSS arrives with the
195
- // first paint (no FOUC). Render-blocking by design, and emitted regardless of `hydrate` (a static
196
- // or `_error` page still wants its styles). In dev (Vite) CSS is injected client-side instead.
197
- let styleLinks = "";
198
- for (const url of styles)
199
- styleLinks += `<link rel="stylesheet" href="${escapeAttr(url)}">`;
200
- // Island bundles are referenced only by a `<script type="module">` at the END of `<body>`, so the
201
- // browser doesn't discover them until the whole page is parsed. `modulepreload` them in `<head>`
202
- // so the fetch starts immediately, in parallel with parsing - regardless of `hydrate`.
203
- let islandPreloads = "";
204
- for (const src of islandScripts)
205
- islandPreloads += `<link rel="modulepreload" href="${escapeAttr(src)}">`;
206
- // Runs in the first-paint→hydration window to swallow a JS-only form's broken native submit. Only
207
- // on a hydrating page (a static/_error page has no client handlers, so no footgun).
208
- const hydrationGuard = hydrate ? `<script${nonceAttr}>${PRE_HYDRATION_GUARD}</script>` : "";
209
- // `<html>` attributes. `lang` defaults to `"en"`; `dir` is omitted entirely when unset, which IS
210
- // HTML's `ltr` default. Both attribute-escaped. `client.ts`'s `applyHead` mirrors this exact
211
- // defaulting on soft-nav, so a hard load and a client navigation produce the same `<html>`.
212
- const htmlAttrs = ` lang="${escapeAttr(head?.lang ?? "en")}"${head?.dir === undefined ? "" : ` dir="${escapeAttr(head.dir)}"`}`;
213
- // Marks the container for the client entry when the id is not the one the entry falls back to.
214
- const rootMarker = rootId === "root" ? "" : ` ${ROOT_ATTRIBUTE}`;
215
- // A non-hydrated page omits the adapter's hydration bootstrap entirely (Solid's `_$HY` registry
216
- // script, etc.) - there is no client takeover to feed, so it's dead bytes on a static document.
217
- // The nonce rewrite only runs when a nonce is set; with none it was a whole-string no-op scan.
218
- const rawHydrationHead = hydrate ? adapter.hydrationHead(nonce) : "";
219
- const hydrationHead = nonce === undefined
220
- ? rawHydrationHead
221
- : rawHydrationHead.replace(/<script(?![^>]*\bnonce=)(?=[\s>])/g, `<script${nonceAttr}`);
222
- // Shell up to the deferred-runtime seam: on a hydrating page that seam sits after the entry +
223
- // route-chunk preloads; a non-hydrating page has no runtime insertion at all.
224
- const entryPreloads = hydrate
225
- ? `<link rel="modulepreload" href="${escapeAttr(clientEntry ?? "")}">${preloadLinks}`
226
- : "";
227
- slot.shellPre = `<!doctype html><html${htmlAttrs}><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${hydrationGuard}<title>${escapeHtml(head?.title ?? title)}</title>${headTags(head)}${styleLinks}${entryPreloads}`;
228
- slot.shellPost = `${islandPreloads}${hydrationHead}</head><body><div id="${escapeAttr(rootId)}"${rootMarker}>`;
229
- // Island bundles load regardless of `hydrate` - a static page (hydrate:false) ships no framework
230
- // client but can still mount no-framework islands (`@nifrajs/web/islands`).
231
- let islandTags = "";
232
- for (const src of islandScripts)
233
- islandTags += `<script type="module" src="${escapeAttr(src)}"${nonceAttr}></script>`;
234
- if (hydrate) {
235
- slot.tailPre = `<script${nonceAttr}>${route}`;
236
- slot.tailMid = prerendered;
237
- slot.tailData = `window.${DATA_GLOBAL}=`;
238
- slot.tailPost = `</script><script type="module" src="${escapeAttr(clientEntry ?? "")}"${nonceAttr}></script>${islandTags}</body></html>`;
239
- }
240
- else {
241
- slot.tailPre = "";
242
- slot.tailMid = "";
243
- slot.tailData = "";
244
- slot.tailPost = `${islandTags}</body></html>`;
245
- }
246
- }
247
- // The deferred runtime rides only on a hydrating page (a static page has no client takeover), and
248
- // only when something actually deferred - matching the pre-cache emission exactly.
249
- const runtimeSeam = hydrate && allDeferred.length > 0 ? deferredRuntime : "";
250
- const shellHtml = `${slot.shellPre}${runtimeSeam}${slot.shellPost}`;
251
- // Closes the hydration container; deferred resolve scripts go AFTER it (outside `#root`) so they
252
- // aren't part of the adapter's hydrated tree (an inline script inside it breaks hydration).
253
- const closeRootHtml = "</div>";
254
- // Tail - the loader-data globals + the client module. Module scripts defer (run after parse), so
255
- // the data global + every streamed deferred resolution are set before the entry hydrates.
256
- const tailHtml = hydrate
257
- ? `${slot.tailPre}${action}${slot.tailMid}${layoutTail}${boundaryTail}${slot.tailData}${serializeData(forClient)}${slot.tailPost}`
258
- : slot.tailPost;
259
- const headers = { "content-type": "text/html; charset=utf-8" };
260
- // Caller-supplied headers (a terminal status page's `cache-control`, say). Applied before the
261
- // framework's own below, so `content-type` and the ISR channel stay authoritative - a caller must
262
- // not be able to mislabel the document or forge the freshness header by passing them here.
263
- if (extraHeaders !== undefined) {
264
- for (const [name, value] of new Headers(extraHeaders)) {
265
- if (name !== "content-type")
266
- headers[name] = value;
267
- }
268
- }
269
- // ISR: advertise the route's freshness so a `withISR` wrapper can set this page's cache TTL. A
270
- // dedicated header (not the action-revalidation `x-nifra-revalidate`) so the TTL channel never aliases
271
- // the client's path-list channel.
272
- if (revalidate !== undefined)
273
- headers[ISR_REVALIDATE_HEADER] = String(revalidate);
274
- const serializedTags = serializeISRTags(revalidateTags);
275
- if (serializedTags !== undefined)
276
- headers[ISR_REVALIDATE_TAGS_HEADER] = serializedTags;
277
- const renderProps = {
278
- data: forComponent,
279
- actionData: actionSplit?.forComponent,
280
- // `params`/`path` thread the matched route + URL to the adapter's `useParams`/`useLocation` so they
281
- // render SSR-correct. Spread only when supplied (exactOptionalPropertyTypes) - an adapter with no
282
- // router bindings simply never reads them.
283
- ...(options.params !== undefined ? { params: options.params } : {}),
284
- ...(options.path !== undefined ? { path: options.path } : {}),
285
- // Same rule for `search`: the validated query the adapter's `useSearch` reads, spread only when the
286
- // caller supplied it (a non-router render never has it).
287
- ...(options.search !== undefined ? { search: options.search } : {}),
288
- // Spread only when present, so a page-only render produces exactly the props it did before.
289
- ...(options.layoutData !== undefined
290
- ? { layoutData: layoutSplits.map((split) => split.forComponent) }
291
- : {}),
292
- ...(boundarySplit !== undefined
293
- ? { boundaries: boundarySplit.forComponent }
294
- : {}),
295
- };
296
- // Fast path: nothing `defer()`s and the adapter can render synchronously to a string → buffer the
297
- // whole document in one pass. Progressive streaming only benefits pages with deferred boundaries
298
- // (those take the streaming path below); for a plain page the streaming pipeline + the framework's
299
- // streaming renderer are pure overhead vs a single sync render + concat. A buffered string body also
300
- // gets an automatic Content-Length. A render throw surfaces here exactly as the streaming path's
301
- // shell-readiness `await` does, so the `_error` boundary still maps it to a status.
302
- if (allDeferred.length === 0 && adapter.renderToString !== undefined) {
303
- const out = adapter.renderToString(chain, renderProps);
304
- return typeof out === "string"
305
- ? new BufferedRenderedPage(shellHtml + out + closeRootHtml + tailHtml, status, headers)
306
- : out.then((bodyHtml) => new BufferedRenderedPage(shellHtml + bodyHtml + closeRootHtml + tailHtml, status, headers));
307
- }
308
- return renderStreamedPage(adapter, chain, renderProps, shellHtml, closeRootHtml, allDeferred, tailHtml, status, headers, nonceAttr).then((response) => new ResponseRenderedPage(response));
309
- }
310
- async function renderStreamedPage(adapter, chain, renderProps, shellHtml, closeRootHtml, allDeferred, tailHtml, status, headers, nonceAttr) {
311
- // Streaming path - required for `defer()` (progressive `<Await>` resolution) and used by any adapter
312
- // that doesn't implement `renderToString`. Awaiting `renderToStream` resolves on shell-readiness
313
- // (React: on-shell-ready; Solid: synchronously), so a shell-render throw surfaces before any byte is
314
- // sent. A *mid*-stream failure errors the body instead.
315
- const enc = TEXT_ENCODER;
316
- const shell = enc.encode(shellHtml);
317
- const closeRoot = enc.encode(closeRootHtml);
318
- const tail = enc.encode(tailHtml);
319
- const appStream = await adapter.renderToStream(chain, renderProps);
320
- const body = streamDocument(shell, appStream, closeRoot, allDeferred, tail, enc, nonceAttr);
321
- return new Response(body, { status, headers });
322
- }
323
- class BufferedRenderedPage {
324
- [RESPONSE_RESULT] = true;
325
- body;
326
- status;
327
- headers;
328
- constructor(body, status, headers) {
329
- this.body = body;
330
- this.status = status;
331
- this.headers = headers;
332
- }
333
- toResponse() {
334
- return htmlResponse(this.body, { status: this.status, headers: this.headers });
335
- }
336
- toNodeBody() {
337
- return { status: this.status, headers: this.headers, body: this.body };
338
- }
339
- }
340
- class ResponseRenderedPage {
341
- [RESPONSE_RESULT] = true;
342
- response;
343
- constructor(response) {
344
- this.response = response;
345
- }
346
- toResponse() {
347
- return this.response;
348
- }
349
- }
350
- function htmlResponse(body, init) {
351
- const response = new Response(body, init);
352
- // @nifrajs/node can write buffered HTML straight to ServerResponse with `end(body)`, avoiding a Web
353
- // Response stream drain on Node. Non-enumerable + Symbol.for keeps this invisible to Web runtimes and
354
- // cross-package without adding a runtime dependency from @nifrajs/node to @nifrajs/web.
355
- Object.defineProperty(response, NODE_RESPONSE_BODY, { value: body });
356
- return response;
357
- }
358
- /**
359
- * Assemble the document stream: `shell` → the app `stream` (forwarded chunk-by-chunk, so a streaming
360
- * renderer's progressive flushing is preserved) → `closeRoot` → one `__nifraResolve`/`__nifraReject`
361
- * script per deferred value (emitted once its promise settles - by now the app stream has awaited
362
- * the same Suspense boundaries - and placed OUTSIDE `#root`) → `tail`. A mid-stream app error errors
363
- * the result (the body breaks) rather than silently truncating a 200.
364
- */
365
- function streamDocument(shell, stream, closeRoot, deferred, tail, enc, nonceAttr) {
366
- return new ReadableStream({
367
- async start(controller) {
368
- const reader = stream.getReader();
369
- try {
370
- controller.enqueue(shell);
371
- for (;;) {
372
- const { done, value } = await reader.read();
373
- if (done)
374
- break;
375
- controller.enqueue(value);
376
- }
377
- controller.enqueue(closeRoot);
378
- // Stream each resolution as ITS OWN promise settles - NOT in array order. A slow
379
- // defer() must not block a faster one; each script self-addresses by id, so order is irrelevant.
380
- await Promise.all(deferred.map(async (d) => {
381
- try {
382
- const value = serializeData(await d.promise);
383
- controller.enqueue(enc.encode(`<script${nonceAttr}>window.__nifraResolve(${d.id},${value})</script>`));
384
- }
385
- catch (err) {
386
- // A rejected deferred streams __nifraReject (the client `<Await>` surfaces it) - it must
387
- // not break the whole body. Redact: stream a stable opaque code, never the raw error
388
- // text; log the real reason server-side.
389
- console.error("[nifra/web] deferred value rejected:", err);
390
- controller.enqueue(enc.encode(`<script${nonceAttr}>window.__nifraReject(${d.id},${serializeData(DEFERRED_ERROR_CODE)})</script>`));
391
- }
392
- }));
393
- controller.enqueue(tail);
394
- controller.close();
395
- }
396
- catch (err) {
397
- controller.error(err);
398
- }
399
- finally {
400
- reader.releaseLock();
401
- }
402
- },
403
- });
404
- }
405
- /** A same-origin destination is an absolute path: one leading `/`, but NOT `//` (protocol-relative →
406
- * another origin), and nothing a URL parser resolves off-origin. Everything else (absolute URL with
407
- * a scheme, `//host`, `javascript:`, a bare relative `foo`) requires `external: true`. The predicate
408
- * lives in the kernel - see `isSameOriginPath` - so this gate and the auth guards' `redirectTo`
409
- * cannot drift apart. */
410
- /**
411
- * Build a redirect - return it from a route `action` for the Post/Redirect/Get pattern (POST
412
- * mutates, 303 sends the browser to a fresh GET, so a reload doesn't re-submit). Defaults to 303
413
- * (See Other); pass `{ status: 307 }` or `{ status: 308 }` to preserve the method.
414
- *
415
- * **Secure by default:** `location` must be a same-origin path (begins with `/`, not `//`). An
416
- * off-origin/absolute destination throws unless you pass `{ external: true }` - this closes the
417
- * open-redirect footgun of `return redirect(formData.get("next"))` on the no-JS (native-form) path,
418
- * which serves the action's control-flow value verbatim.
419
- *
420
- * Returns a plain render, not a `Response`. A redirect is a status line and one header - the most
421
- * body-less response there is - and building a `Response` for it costs the whole Web object plus, on
422
- * Node, a stream drained back out. As data it renders on the same lane a handler's return takes.
423
- * `redirect(...)` is still returned or thrown from exactly the same places; only `.status` /
424
- * `.headers` are gone from the value, replaced by `options.headers` and the request's `c.set`.
425
- *
426
- * @param options redirect status, extra headers, and whether an off-origin destination is intentional.
427
- */
428
- export function redirect(location, options = {}) {
429
- if (options.external !== true && !isSameOriginPath(location)) {
430
- throw new Error(`[nifra/web] redirect(${JSON.stringify(location)}) is not a same-origin path. Use a path beginning with "/" (not "//", no backslash or control character), or redirect(location, { external: true }) for a deliberate off-origin redirect. This guards against open redirects from unvalidated input.`);
431
- }
432
- // Reject CR/LF in the Location explicitly - defense-in-depth (response splitting / header
433
- // injection). Spec-correct runtimes' Headers setter throws on CR/LF, but `external: true` lets
434
- // unvalidated input reach this sink, so we don't rely on the runtime. Same posture as
435
- // serializeCookie / the SSE frame formatter, which strip CRLF at their sinks.
436
- if (/[\r\n]/.test(location)) {
437
- throw new Error(`[nifra/web] redirect location contains a CR/LF character - refusing to emit a header-injecting redirect.`);
438
- }
439
- return statusResult(options.status ?? 303, undefined, {
440
- headers: options.headers === undefined ? { location } : { ...options.headers, location },
441
- });
442
- }
443
- /**
444
- * The signatures a **duplicate module instance** produces during SSR, across engines.
445
- *
446
- * Two copies of React (or of `@nifrajs/core`) at the SAME version still fail, because module identity
447
- * is path-based: hooks read a dispatcher off the copy that rendered, and the component imported the
448
- * other one. The error that surfaces names a React internal, so it reads as a React bug and the actual
449
- * cause - two directories - is a long inference away. Naming the cause at the point of failure is the
450
- * difference between that and a five-second read.
451
- */
452
- const DUPLICATE_INSTANCE_SIGNATURES = [
453
- /resolveDispatcher\(\)/,
454
- /Invalid hook call/,
455
- /Cannot read propert(?:y|ies) of null \(reading '(?:use[A-Z]\w*)'\)/,
456
- /null is not an object \(evaluating '.*\.use[A-Z]\w*'\)/,
457
- ];
458
- /**
459
- * Append the likely cause to an SSR error that carries a duplicate-instance signature.
460
- *
461
- * Deliberately does NOT claim the resolved paths: `@nifrajs/web` is framework-agnostic and does not
462
- * depend on React, so it cannot resolve the copies without guessing. It names the condition and the
463
- * command that reports the paths, which is the actionable part. Returns the error untouched when the
464
- * signature does not match, so an ordinary render error reads exactly as before.
465
- */
466
- function withDuplicateInstanceHint(err) {
467
- if (!(err instanceof Error))
468
- return err;
469
- if (!DUPLICATE_INSTANCE_SIGNATURES.some((rx) => rx.test(err.message)))
470
- return err;
471
- const augmented = new Error(`${err.message}\n\n[nifra/web] This signature usually means TWO COPIES of an identity-sensitive package (react, react-dom, or @nifrajs/core) are installed at different paths. Module identity is path-based, so matching versions do NOT fix it - the copies must resolve to the same directory. Run \`nifra check\` to list the paths.`, { cause: err });
472
- augmented.name = err.name;
473
- // `stack` is optional under exactOptionalPropertyTypes; assigning `undefined` would replace a real
474
- // stack with nothing on engines that always populate it.
475
- if (err.stack !== undefined)
476
- augmented.stack = err.stack;
477
- return augmented;
478
- }
479
- /**
480
- * An action's control-flow value passes straight through - except a redirect on a client-submit data
481
- * request: fetch would follow the 3xx into HTML the client can't use, so the redirect rides the
482
- * X-Nifra-Redirect header on a 204 and the client navigates. One conversion shared by the returned-
483
- * and thrown- paths, so `return redirect()` and `throw redirect()` agree.
484
- *
485
- * Takes either shape: `redirect()` is a plain render, while a hand-rolled `new Response(...)` from an
486
- * action still arrives as a `Response`. The rewrite stays on the lane its input was on - a plain
487
- * redirect converts to a plain 204, and never materializes the `Response` it is replacing.
488
- */
489
- function actionResponse(result, isDataRequest) {
490
- if (!isDataRequest)
491
- return result;
492
- if (isResponseResult(result)) {
493
- const plain = result.plain;
494
- // No `plain` means a carrier that only knows how to build a `Response` (not one of ours) - fall
495
- // back rather than guess at its status.
496
- if (plain === undefined)
497
- return actionResponse(result.toResponse(), isDataRequest);
498
- if (plain.status < 300 || plain.status >= 400)
499
- return result;
500
- const location = plain.headers?.location ?? "/";
501
- return statusResult(204, undefined, { headers: { [REDIRECT_HEADER]: location } });
502
- }
503
- if (result.status >= 300 && result.status < 400) {
504
- const location = result.headers.get("location") ?? "/";
505
- return statusResult(204, undefined, { headers: { [REDIRECT_HEADER]: location } });
506
- }
507
- return result;
508
- }
509
- /**
510
- * Narrow the route's params to the ones a layout owns.
511
- *
512
- * A layout wraps a URL prefix, so anything deeper belongs to a route beneath it. Handing it the full
513
- * set would let a layout read a param it does not own - which reads fine until the layout is reused
514
- * under a route that has no such param and the value silently becomes `undefined`.
515
- */
516
- function scopeParams(params, owned) {
517
- if (owned === undefined)
518
- return params; // hand-built manifest with no scope info: unchanged behaviour
519
- if (owned.length === 0)
520
- return EMPTY_LAYOUT_PARAMS;
521
- const scoped = {};
522
- for (const name of owned) {
523
- const value = params[name];
524
- if (value !== undefined)
525
- scoped[name] = value;
526
- }
527
- return scoped;
528
- }
529
- const EMPTY_LAYOUT_PARAMS = Object.freeze({});
530
- const EMPTY_RETAIN = new Set();
531
- /**
532
- * Marks an error as coming from a LAYOUT loader, carrying that layout's id.
533
- *
534
- * The boundary that catches it must be at or above the failing layout's own segment. The route's
535
- * innermost `_error` may live BELOW the layout that failed, and rendering there would wrap the
536
- * boundary in a layout whose data never arrived - so the page would render inside a component that
537
- * threw. A registry symbol, matching the other cross-module brands here.
538
- */
539
- const LAYOUT_ERROR_ID = Symbol.for("nifra.web.layout-error-id");
540
- const tagLayoutError = (err, layoutId) => {
541
- if (typeof err === "object" && err !== null && !(LAYOUT_ERROR_ID in err)) {
542
- Object.defineProperty(err, LAYOUT_ERROR_ID, { value: layoutId, enumerable: false });
543
- }
544
- return err;
545
- };
546
- const layoutErrorId = (err) => typeof err === "object" && err !== null
547
- ? err[LAYOUT_ERROR_ID]
548
- : undefined;
549
- const STATUS_SIGNAL = Symbol.for("nifra.web.status-signal");
550
- /** Reason phrases for the plain-text fallback, used only when the app authored no `_<status>` and no
551
- * `_404` page. Deliberately not exhaustive - anything unlisted falls back to "Error", which is more
552
- * useful than shipping a table of every RFC status for a body almost nobody will see. */
553
- const STATUS_TEXT = {
554
- 400: "Bad Request",
555
- 401: "Unauthorized",
556
- 402: "Payment Required",
557
- 403: "Forbidden",
558
- 404: "Not Found",
559
- 410: "Gone",
560
- 451: "Unavailable For Legal Reasons",
561
- 500: "Internal Server Error",
562
- };
563
- function isStatusSignal(value) {
564
- return value instanceof Response && STATUS_SIGNAL in value;
565
- }
566
- function statusSignal(status, options) {
567
- if (!Number.isInteger(status) || status < 400 || status > 599) {
568
- throw new Error(`[nifra/web] statusPage(${JSON.stringify(status)}) must be an integer 4xx or 5xx status. Use redirect() for 3xx, and return data for a successful render.`);
569
- }
570
- const response = new Response(null, { status });
571
- // Non-enumerable so the brand never lands in a structured clone or a JSON log of the response.
572
- Object.defineProperty(response, STATUS_SIGNAL, {
573
- value: { status, ...(options.headers !== undefined ? { headers: options.headers } : {}) },
574
- enumerable: false,
575
- });
576
- throw response;
577
- }
578
- /**
579
- * Render the nearest `_404` page at status **404**. `throw` it from a loader when the record does not
580
- * exist.
581
- *
582
- * This is the fix for the soft 404: a matched route whose loader finds nothing has otherwise no way to
583
- * answer 404, so the path of least resistance is to return empty data and render "not found" inside a
584
- * **200**. That looks correct in a browser and is invisible in review, which is why it ships and stays
585
- * shipped - while search engines penalise it and keep the dead URL indexed.
586
- *
587
- * Returns `never`: these throw, so a loader narrows without a redundant `return`, and the type states
588
- * the thing the "loaders `throw` redirect, actions `return` it" rule already trips people on.
589
- */
590
- export function notFound(options = {}) {
591
- return statusSignal(404, options);
592
- }
593
- /**
594
- * Render a terminal page at status **410 Gone**. `throw` it from a loader for a record that existed and
595
- * was deliberately removed - a withdrawn listing, a deleted post.
596
- *
597
- * 410 is not a pedantic 404: it tells a crawler to **drop** the URL rather than re-fetch it for weeks
598
- * on the assumption the 404 was transient. Uses `_410.tsx` if the app has one, otherwise `_404`.
599
- */
600
- export function gone(options = {}) {
601
- return statusSignal(410, options);
602
- }
603
- /**
604
- * Render a terminal page at any 4xx/5xx status - the escape hatch behind {@link notFound} and
605
- * {@link gone} (402, 451, …). Uses `_<status>.tsx` if present, otherwise `_404`.
606
- */
607
- export function statusPage(status, options = {}) {
608
- return statusSignal(status, options);
609
- }
610
- /**
611
- * Return this from an action to declare which routes the mutation changed (alongside the action's
612
- * `data`). `createWebApp` sets the `X-Nifra-Revalidate` response header; after the submit the client
613
- * marks those cached routes stale - refetching the active one and any mounted fetcher showing them -
614
- * so a mutation can refresh views beyond the one that was submitted. `data` is still surfaced to the
615
- * component as `actionData` (the wrapper is transparent to `ActionData<typeof action>`).
616
- */
617
- export function revalidate(paths, data) {
618
- return { __nifraRevalidate: paths, data };
619
- }
620
- /**
621
- * Serialize loader data for embedding inside an inline `<script>`. `JSON.stringify` alone
622
- * is NOT safe there: a string containing `</script>` or `<!--` would break out of the
623
- * script element (an XSS vector). Escape `<`/`>` to `\uXXXX`, plus the U+2028/U+2029
624
- * separators.
625
- */
626
- export function serializeData(data) {
627
- const serialized = JSON.stringify(data ?? null);
628
- // Most loader payloads contain no script-sensitive characters. Guard with chained `indexOf`
629
- // rather than a regex `.test`: each probe is a native memchr-style scan, measured ~7x faster than
630
- // the regex scan on V8 for a multi-KB payload (and the engine rejects the two >0xFF separator
631
- // probes in O(1) when the string is internally one-byte, which serialized JSON almost always is).
632
- // The same four characters are probed as the SCRIPT_ESCAPE class, so any payload the regex would
633
- // escape still takes the escape path - this is only a cheaper detector, never a security
634
- // relaxation.
635
- const needsEscape = serialized.indexOf("<") !== -1 ||
636
- serialized.indexOf(">") !== -1 ||
637
- serialized.indexOf(LINE_SEP) !== -1 ||
638
- serialized.indexOf(PARA_SEP) !== -1;
639
- return needsEscape
640
- ? serialized.replace(SCRIPT_ESCAPE, (ch) => SCRIPT_ESCAPE_MAP[ch] ?? ch)
641
- : serialized;
642
- }
643
- function escapeHtml(value) {
644
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
645
- }
646
- /**
647
- * Escape a `<script>` element's text content so it cannot break out of the element. Per the HTML spec,
648
- * a script's text may contain any character EXCEPT the sequences that the parser treats as element
649
- * boundaries: `</` (which would begin the end tag - `</script>` is the obvious XSS vector, but ANY `</`
650
- * starts script-data-end-tag parsing), and the comment/CDATA edges `<!--` / `]]>`. We escape the `<`
651
- * (and the `>` of `]]>`) to its JS unicode escape: inside a JS/JSON string literal `<` is the
652
- * identical character, so a JSON-LD payload is byte-equivalent after parsing - but the raw `<`/`>` the
653
- * HTML tokenizer scans for is gone. This is the JSON-LD-in-HTML rule (content is JSON, never raw HTML),
654
- * mirroring {@link serializeData}'s posture for the data-global script. Idempotent on already-safe text.
655
- */
656
- function escapeScriptContent(content) {
657
- // Order matters: rewrite `]]>` first (its `>` becomes `>`), then every `<` (covers `</` and
658
- // `<!--` in one pass). `<` → `<`; the lone `>` of `]]>` → `>`. A bare `>` elsewhere is
659
- // harmless in script data, so only the `]]>` close is targeted for `>`.
660
- return content.replaceAll("]]>", "]]\\u003e").replaceAll("<", "\\u003c");
661
- }
662
- function escapeAttr(value) {
663
- return value
664
- .replaceAll("&", "&amp;")
665
- .replaceAll('"', "&quot;")
666
- .replaceAll("<", "&lt;")
667
- .replaceAll(">", "&gt;");
668
- }
669
- /** Serialize attributes that passed the shared SSR/client head trust policy. */
670
- function tagAttrs(tag, attrs) {
671
- const trusted = trustedHeadAttributes(tag, attrs);
672
- if (trusted === null)
673
- return null;
674
- let out = "";
675
- for (const [name, value] of trusted) {
676
- if (out !== "")
677
- out += " ";
678
- out += value === true ? name : `${name}="${escapeAttr(value)}"`;
679
- }
680
- return out;
681
- }
682
- // Memoize the serialized head-tag string by the resolved `Meta` object's identity. A STATIC route
683
- // `meta` is returned by-reference from resolveMeta, so the same object recurs every request → cache
684
- // hit, and the invariant string is serialized once per route, not per request. A FUNCTION `meta`
685
- // builds a fresh object each request (new identity) → miss → recompute, exactly as needed (its
686
- // content can vary). WeakMap so a route module that's GC'd takes its entry with it.
687
- const headTagsCache = new WeakMap();
688
- function assertExecutableScriptType(type) {
689
- if (!EXECUTABLE_SCRIPT_TYPES.has(type)) {
690
- throw new TypeError(`[nifra/web] executable inline scripts accept ${[...EXECUTABLE_SCRIPT_TYPES].map((t) => JSON.stringify(t)).join(" or ")}; received ${JSON.stringify(type)}`);
691
- }
692
- }
693
- /** Render a route's `meta`/`link`/`script` as managed (`data-nifra`) head tags. Title is set
694
- * separately. XSS-safe by construction: every attribute flows through the shared tag-specific trust
695
- * policy then value escaping, and each `script[].content` through `escapeScriptContent`
696
- * (breakout-escaped) - so loader-derived strings (LLM-authored `og:*`, user content) can't inject markup
697
- * or close the tag early. String concatenation (no intermediate `.map()` arrays + spread) - parity with
698
- * the already concat-based preloadLinks/styleLinks/islandPreloads loops; byte-identical output. Result
699
- * is memoized per resolved-`Meta` identity (static meta → serialized once per route). */
700
- function headTags(head) {
701
- if (head === undefined)
702
- return "";
703
- const cached = headTagsCache.get(head);
704
- if (cached !== undefined)
705
- return cached;
706
- let out = "";
707
- if (head.meta !== undefined)
708
- for (const m of head.meta) {
709
- const attrs = tagAttrs("meta", m);
710
- if (attrs !== null)
711
- out += `<meta${attrs === "" ? "" : ` ${attrs}`} data-nifra>`;
712
- }
713
- if (head.link !== undefined)
714
- for (const l of head.link) {
715
- const attrs = tagAttrs("link", l);
716
- if (attrs !== null)
717
- out += `<link${attrs === "" ? "" : ` ${attrs}`} data-nifra>`;
718
- }
719
- // `<script>` slot - JSON-LD + other inert head scripts. `type` is attribute-escaped; `content` is
720
- // breakout-escaped (`escapeScriptContent`) so a `</script>` (or `<!--`/`]]>`) payload can't close the
721
- // element early. Managed (`data-nifra`) so a soft-nav's `applyHead` cleanly replaces it.
722
- if (head.script !== undefined)
723
- for (const s of head.script) {
724
- const type = s.type ?? "application/ld+json";
725
- if (!INERT_SCRIPT_TYPES.has(type)) {
726
- throw new TypeError(`[nifra/web] head.script only accepts inert JSON script types; received ${JSON.stringify(type)}. Use unsafeInlineScript() with a CSP nonce for executable code.`);
727
- }
728
- out += `<script type="${type}" data-nifra>${escapeScriptContent(s.content)}</script>`;
729
- }
730
- if (head.unsafeScript !== undefined)
731
- for (const s of head.unsafeScript) {
732
- if (s.unsafe !== true || s.nonce.trim() === "") {
733
- throw new TypeError("[nifra/web] executable inline scripts require a non-empty CSP nonce");
734
- }
735
- // `type` is validated, not escaped, for the same reason as the inert slot above: an unknown
736
- // value here is a bug, and escaping one would emit a nonsense script type rather than say so.
737
- // It was interpolated raw while the `nonce` beside it was escaped, so a descriptor built by hand
738
- // - `unsafeScript` is a public field, the helper is only a convenience - could close the
739
- // attribute and inject markup. Measured: `type: '"><img src=x onerror=alert(1)>'` reached the
740
- // document. An injection in the slot whose whole purpose is to make script emission trustworthy.
741
- assertExecutableScriptType(s.type);
742
- out += `<script type="${s.type}" nonce="${escapeAttr(s.nonce)}" data-nifra>${escapeScriptContent(s.content)}</script>`;
743
- }
744
- headTagsCache.set(head, out);
745
- return out;
746
- }
747
- /**
748
- * A `<link rel="canonical">` descriptor for a route's `meta.link`. The canonical URL tells search
749
- * engines which URL is authoritative for a page (deduping query-string / tracking variants).
750
- *
751
- * ```ts
752
- * export const meta = (a) => ({ link: [canonical(`https://site.com/posts/${a.params.slug}`)] })
753
- * ```
754
- */
755
- export function canonical(href) {
756
- return { rel: "canonical", href };
757
- }
758
- /**
759
- * Build the Open Graph `<meta property="og:*">` entries for a route's `meta.meta`. Returns only the
760
- * properties you supplied (plus `og:type`, defaulting to `"website"`), so it composes with other meta.
761
- *
762
- * ```ts
763
- * export const meta = { meta: [...openGraph({ title: "Nifra", image: "https://site.com/og.png" })] }
764
- * ```
765
- */
766
- export function openGraph(input) {
767
- const tags = [];
768
- const add = (property, content) => {
769
- if (content !== undefined)
770
- tags.push({ property, content });
771
- };
772
- add("og:title", input.title);
773
- add("og:description", input.description);
774
- add("og:image", input.image);
775
- add("og:url", input.url);
776
- // `og:type` always present (the spec's required property) - default "website" when unset.
777
- tags.push({ property: "og:type", content: input.type ?? "website" });
778
- return tags;
779
- }
780
- /**
781
- * Build a JSON-LD `<script type="application/ld+json">` entry for a route's `meta.script` from a plain
782
- * object. `JSON.stringify` produces the body; the head renderer breakout-escapes it (see
783
- * `escapeScriptContent`), so a string field containing `</script>` is embedded safely.
784
- *
785
- * ```ts
786
- * export const meta = {
787
- * script: [jsonLd({ "@context": "https://schema.org", "@type": "Article", headline: "Hi" })],
788
- * }
789
- * ```
790
- */
791
- export function jsonLd(data) {
792
- return { type: "application/ld+json", content: JSON.stringify(data) };
793
- }
794
- /**
795
- * Deliberately unsafe escape hatch for executable inline code. The required nonce keeps the result
796
- * compatible with a strict CSP and makes the security-sensitive choice visible at the call site.
797
- */
798
- export function unsafeInlineScript(content, options) {
799
- if (options.nonce.trim() === "") {
800
- throw new TypeError("[nifra/web] unsafeInlineScript requires a non-empty CSP nonce");
801
- }
802
- const type = options.type ?? "module";
803
- // Checked here as well as at emit: the type union is compile-time only, and this helper is the one
804
- // place a caller is told what it may pass. Failing at the call site names the argument; failing at
805
- // render names a document.
806
- assertExecutableScriptType(type);
807
- return {
808
- unsafe: true,
809
- type,
810
- nonce: options.nonce,
811
- content,
812
- };
813
- }
814
- /**
815
- * Re-issue `request` with `prefix` removed from its pathname.
816
- *
817
- * Needed because two conventions exist and both are reasonable. `createWebApp`'s auto-mount assumes a
818
- * backend that declares FULL paths (`server().post("/api/sync")`), which is right when the backend is
819
- * only ever mounted here. A backend that also runs standalone declares paths WITHOUT the prefix and
820
- * lets its own shell supply it - and mounting one of those here used to require the caller to wrap it
821
- * in a `Proxy` that rewrote every URL. Two apps wrote that same wrapper independently, which is the
822
- * signal that it belonged in the framework.
823
- *
824
- * The `Request` is rebuilt rather than mutated (`url` is read-only), preserving method, headers, body,
825
- * and duplex streaming - the body is passed through unread, so a large or streamed upload is untouched.
826
- */
827
- function stripMountPrefix(request, prefix) {
828
- const url = new URL(request.url);
829
- const rest = url.pathname.slice(prefix.length);
830
- url.pathname = rest === "" ? "/" : rest;
831
- // `url.href`, not the `URL`: this type set only declares the string and Request overloads.
832
- return new Request(url.href, request);
833
- }
834
- /**
835
- * Resolve the explicit symbol-keyed backend mount interface. The symbol seam forwards platform
836
- * context without making web depend on client.
837
- */
838
- function backendMountOf(api) {
839
- if ((typeof api !== "object" && typeof api !== "function") || api === null)
840
- return undefined;
841
- const explicit = api[NIFRA_BACKEND_MOUNT];
842
- if (typeof explicit !== "function")
843
- return undefined;
844
- return (request, platform) => explicit.call(api, request, platform);
845
- }
846
- // `createWebApp` reaches the same Request object through the mount hook and the page route. Cache the
847
- // allocation-light core split once so API mounting, path hydration, search parsing, and SSG fallback
848
- // checks do not each rescan the absolute URL. WeakMap keeps this bounded to requests that are alive.
849
- const REQUEST_URL_PARTS = new WeakMap();
850
- const urlPartsFor = (request) => {
851
- const cached = REQUEST_URL_PARTS.get(request);
852
- if (cached !== undefined)
853
- return cached;
854
- const parts = urlPartsOf(request.url);
855
- REQUEST_URL_PARTS.set(request, parts);
856
- return parts;
857
- };
858
- /**
859
- * Build a nifra app from a route manifest: every route SSRs its layout chain via `renderPage`,
860
- * and a wildcard catch-all renders `_404` (or a plain 404). Reuses @nifrajs/core's router +
861
- * lifecycle, so matching, params, and precedence are battle-tested. fs-free - feed it a
862
- * manifest from `discoverRoutes` (`@nifrajs/web/fs`) at startup, so the served app stays portable.
863
- *
864
- * **Typed platform bindings.** Pass `Env` - `createWebApp<Env>({ … })` - to declare the app's Workers
865
- * bindings ONCE. It seeds the returned `Server`'s context with `{ env: Env }` (exactly as the backend's
866
- * `server<Env>()` does), so `app.fetch(req, { env })` / `toFetchHandler(app)` type-check the `env`
867
- * argument against the declared shape - no per-binding cast at the edge entry. Per-route loaders/actions
868
- * stay typed independently of this call: annotate them with `@nifrajs/client`'s `LoaderArgs<Api, Env>`
869
- * (same `Env`) so `ctx.env.MY_KV` is typed there too. Omit the parameter and `Env` is `unknown` - the
870
- * secure default; validate at the trust boundary before use.
871
- */
872
- export function createWebApp(options) {
873
- const { adapter, manifest, clientEntry, title, api } = options;
874
- const titleOption = title === undefined ? {} : { title };
875
- // Draft/preview: when a `draftSecret` is configured, each request's signed `__nifra_draft` cookie is
876
- // verified once and surfaced to loaders/actions as `ctx.draft`. No secret ⇒ always `false` (sync, free).
877
- const draftFlag = (req) => options.draftSecret === undefined
878
- ? Promise.resolve(false)
879
- : isDraftEnabled(req, options.draftSecret);
880
- // Per-route preload chunks (spread into renderPage; omitted when unmapped, for exactOptionalPropertyTypes).
881
- const preloadOf = (id) => {
882
- const chunks = options.routePreload?.[id];
883
- return chunks ? { preload: chunks } : {};
884
- };
885
- // The matched route's stylesheet links (spread into renderPage). Per-route when the build mapped it
886
- // (`routeStyles[id]` - only the chain's CSS; an empty array ⇒ no `<link>`), else the aggregate
887
- // `styles`. Omitted entirely when CSS-free (for exactOptionalPropertyTypes).
888
- const stylesOf = (id) => {
889
- const perRoute = options.routeStyles?.[id];
890
- if (perRoute !== undefined)
891
- return { styles: perRoute };
892
- return options.styles && options.styles.length > 0 ? { styles: options.styles } : {};
893
- };
894
- // Seed the context with the declared `Env` so `app.fetch(req, { env })` / `toFetchHandler(app)` type
895
- // the platform bindings (see the `createWebApp` doc). The runtime `env` still arrives per-request via
896
- // `app.fetch(req, { env })`; this is a compile-time-only seed (`server<Env>()` casts, doesn't store).
897
- const app = server(options.server);
898
- // Before the mount hooks and before every page route, so the order-scoped hooks (`derive`,
899
- // `beforeHandle`, assurance evidence) actually bind to them - see the `use` option. A caller
900
- // cannot do this after the fact: by the time this function returns, the routes are declared.
901
- options.use?.(app);
902
- // Auto-mount the in-process backend over HTTP at `apiPrefix` (default `/api`), BEFORE page routing.
903
- // `onRequest` runs on the raw request ahead of the router, so this wins over the page wildcard `/*`
904
- // for every method (POST/GET/PUT/…) - not just the GET page routes - and a backend 404 (`/api/none`)
905
- // surfaces as the backend's own response, never the page 404. We dispatch the SAME `Request` object
906
- // (its body unread) so streamed/large bodies pass through untouched; the backend defines its routes
907
- // at the full prefixed path (`server().post("/api/sync", …)`), matching the `inProcessClient` call
908
- // sites. `apiPrefix: ""` opts out; a non-mountable `api` (no symbol mount) is left pages-only. The hook
909
- // is registered ONLY when both hold, so a pages-only app keeps core's synchronous no-hook fast path.
910
- const apiPrefix = options.apiPrefix ?? "/api";
911
- const apiStrip = options.apiStrip === true;
912
- const mountedApi = backendMountOf(api);
913
- // Longest path first, so a more specific mount (`/api/auth`) is tried before a broader one (`/api`)
914
- // regardless of the order they were declared in.
915
- const mounts = [...(options.mounts ?? [])].sort((a, b) => b.path.length - a.path.length);
916
- const underPrefix = (pathname, prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`);
917
- if (mounts.length > 0 || (apiPrefix !== "" && mountedApi !== undefined)) {
918
- app.onRequest((req, platform) => {
919
- const { pathname } = urlPartsFor(req);
920
- // Sub-app mounts win over the backend prefix: they are the more specific declaration, and an
921
- // auth handler mounted at `/api/auth` must not be swallowed by the backend mounted at `/api`.
922
- for (const mount of mounts) {
923
- if (!underPrefix(pathname, mount.path))
924
- continue;
925
- return mount.app.fetch(mount.stripPrefix === true ? stripMountPrefix(req, mount.path) : req);
926
- }
927
- // Exactly the prefix (`/api`) or a sub-path (`/api/…`) - NOT a sibling like `/apixyz` that merely
928
- // shares the prefix as a string head. Dispatch the original `req` (body intact) to the backend.
929
- if (mountedApi !== undefined && apiPrefix !== "" && underPrefix(pathname, apiPrefix)) {
930
- return mountedApi(apiStrip ? stripMountPrefix(req, apiPrefix) : req, platform);
931
- }
932
- return undefined; // not an API path → continue to page routing
933
- });
934
- }
935
- // SSG `fallback: "404"`: the set of concrete paths that actually exist for those routes. An unlisted
936
- // path under a `"404"` route is rejected (it isn't a static file, and the route declared it shouldn't
937
- // SSR on demand). O(1) membership via a Set.
938
- const prerenderedSet = new Set(options.prerenderedPaths ?? []);
939
- const matchManifestRoute = createMatcher(manifest.routes.map((route) => ({ routeId: route.id, pattern: route.pattern })));
940
- const routeById = new Map(manifest.routes.map((route) => [route.id, route]));
941
- // Load a route's layout modules (outermost layout → innermost), keeping each module whole so the
942
- // render path can take both its `default` (the component chain) AND its `meta` (the sitewide head it
943
- // contributes). Loaded lazily - the data-only and 405 branches return before any layout is needed.
944
- const loadLayoutModules = async (route) => {
945
- const modules = await Promise.all(
946
- // layoutIds only reference layouts present in the manifest (buildManifest invariant).
947
- route.layoutIds.map((id) => manifest.layouts[id].load()));
948
- // A layout is not a form target, so an `action` there is a mistake with no meaning to give it.
949
- // A `loader`, by contrast, now runs (see `runLayoutChain`).
950
- for (let i = 0; i < modules.length; i++) {
951
- if (modules[i].action === undefined)
952
- continue;
953
- const id = route.layoutIds[i];
954
- throw new Error(`[nifra/web] "${manifest.layouts[id].file}" exports an \`action\`, but layouts do not run one - only route files do. Move the mutation into the route that submits to it.`);
955
- }
956
- return modules;
957
- };
958
- /**
959
- * Run a route's layout-chain loaders, honouring declared gates.
960
- *
961
- * Returns once every **gate** has resolved, with the non-gate loaders still in flight, so the caller
962
- * can start the page loader at exactly the right moment: after anything that might reject the
963
- * request, alongside anything that merely fetches.
964
- *
965
- * The ordering is the security-relevant part. Parallel loaders are NOT an authorization boundary -
966
- * a page loader running concurrently with a guard has already queried by the time the guard says no.
967
- * Remix documents that as a footgun; here it is a declaration instead. `export const gate = true`
968
- * makes a layout blocking for everything beneath it, and nothing beneath a rejected gate runs.
969
- *
970
- * Each layout receives only the params it OWNS ({@link RouteEntry.layoutParams}), not the route's
971
- * full set, so a layout at `orgs/[org]/` cannot read a param belonging to a route below it.
972
- */
973
- /**
974
- * Layout indices a client navigation asked to keep, from {@link RETAIN_HEADER}.
975
- *
976
- * The CLIENT decides retainability: it knows each layout's scoped params (shipped in the bootstrap)
977
- * and both the old and new match, so it can tell whether a layout's own prefix changed - without the
978
- * server re-matching a path the client already matched.
979
- *
980
- * It is a HINT, not an instruction. The client is asking to keep data it already holds, which is
981
- * harmless for data and unacceptable for a guard, so `runLayoutChain` refuses to skip a gate no
982
- * matter what arrives here. Anything unparseable is ignored rather than rejected: the worst case of
983
- * a bad hint is a loader that runs when it need not.
984
- */
985
- const retainedIndices = (header) => {
986
- if (header === null || header === "")
987
- return EMPTY_RETAIN;
988
- const out = new Set();
989
- for (const part of header.split(",")) {
990
- // Digits only. `Number("")` is 0 and `Number(" ")` is 0, so a stray comma would otherwise read
991
- // as "retain index 0" and silently skip the outermost layout.
992
- if (!/^\d+$/.test(part))
993
- continue;
994
- out.add(Number(part));
995
- }
996
- return out;
997
- };
998
- /**
999
- * Validate a data-navigation's retain request against the manifest and its declared source path.
1000
- * A client may ask to retain every slot it currently has; the server only honours indices whose
1001
- * layout identity and owned params are unchanged. Hard document GETs never retain anything.
1002
- */
1003
- const validatedRetainedIndices = (req, route, params) => {
1004
- if (req.headers.get(DATA_HEADER) === null)
1005
- return EMPTY_RETAIN;
1006
- const requested = retainedIndices(req.headers.get(RETAIN_HEADER));
1007
- const from = req.headers.get(NAV_FROM_HEADER);
1008
- if (requested.size === 0 || from === null)
1009
- return EMPTY_RETAIN;
1010
- let fromPath;
1011
- try {
1012
- const current = new URL(req.url);
1013
- const source = new URL(from, current);
1014
- if (source.origin !== current.origin)
1015
- return EMPTY_RETAIN;
1016
- fromPath = source.pathname + source.search;
1017
- }
1018
- catch {
1019
- return EMPTY_RETAIN;
1020
- }
1021
- const previousMatch = matchManifestRoute(fromPath);
1022
- if (previousMatch === null)
1023
- return EMPTY_RETAIN;
1024
- const previous = routeById.get(previousMatch.routeId);
1025
- if (previous === undefined)
1026
- return EMPTY_RETAIN;
1027
- const valid = new Set();
1028
- for (const index of requested) {
1029
- if (route.layoutIds[index] !== previous.layoutIds[index])
1030
- continue;
1031
- const owned = route.layoutParams?.[index] ?? [];
1032
- const previouslyOwned = previous.layoutParams?.[index] ?? [];
1033
- if (owned.length !== previouslyOwned.length ||
1034
- owned.some((name, i) => name !== previouslyOwned[i]) ||
1035
- owned.some((name) => params[name] !== previousMatch.params[name])) {
1036
- continue;
1037
- }
1038
- valid.add(index);
1039
- }
1040
- return valid;
1041
- };
1042
- // The validated (or raw-parsed) search a route's loader context receives; `searchOf` fails closed to
1043
- // the schema's defaults on hostile input, so this never throws on an attacker-picked query.
1044
- const loaderSearch = (searchSchema, request) => searchOf(searchSchema, urlPartsFor(request).search);
1045
- // The route's EFFECTIVE search once its layout chain is loaded: the layout schemas merged with the
1046
- // page's (page-wins), the same chain the client mount builds for `useSearch`. Used for the page loader's
1047
- // `ctx.search` and the render's `RenderProps.search`, so both agree with the client and with each other.
1048
- const searchChainOf = (layoutMods, mod, request) => searchOfChain([...layoutMods.map((m) => m.searchSchema), mod.searchSchema], urlPartsFor(request).search);
1049
- const runLayoutChain = async (route, ctx, retain = new Set()) => {
1050
- const modules = await loadLayoutModules(route);
1051
- if (!modules.some((m) => m.loader !== undefined)) {
1052
- // Nothing to run: no array is produced, so a page-only app serializes nothing extra and its
1053
- // HTML is byte-identical to before this feature.
1054
- return { modules, layoutData: undefined, retained: [], pending: Promise.resolve() };
1055
- }
1056
- const results = new Array(modules.length).fill(null);
1057
- const retained = [];
1058
- const pending = [];
1059
- for (let i = 0; i < modules.length; i++) {
1060
- const loader = modules[i]?.loader;
1061
- if (loader === undefined)
1062
- continue;
1063
- // Unchanged scope: the client keeps what it has. A GATE is never skipped - it is a guard, and a
1064
- // guard that only runs when the URL prefix changed is not a guard.
1065
- if (retain.has(i) && modules[i]?.gate !== true) {
1066
- retained.push(i);
1067
- continue;
1068
- }
1069
- const scoped = {
1070
- ...ctx,
1071
- params: scopeParams(ctx.params, route.layoutParams?.[i]),
1072
- };
1073
- if (modules[i]?.gate === true) {
1074
- // Blocking: awaited here, so a throw propagates before anything deeper is started.
1075
- try {
1076
- results[i] = await loader(scoped);
1077
- }
1078
- catch (err) {
1079
- throw tagLayoutError(err, route.layoutIds[i]);
1080
- }
1081
- continue;
1082
- }
1083
- const layoutId = route.layoutIds[i];
1084
- const index = i;
1085
- // The loader is invoked INSIDE the async function, not before it. `Promise.resolve(loader(x))`
1086
- // would let a synchronously-throwing loader escape past the rejection handler entirely - the
1087
- // exception happens while evaluating the argument, before any promise exists to reject.
1088
- pending.push((async () => {
1089
- try {
1090
- results[index] = await loader(scoped);
1091
- }
1092
- catch (err) {
1093
- throw tagLayoutError(err, layoutId);
1094
- }
1095
- })());
1096
- }
1097
- return { modules, layoutData: results, retained, pending: Promise.all(pending) };
1098
- };
1099
- /** Run only blocking layout gates before a route action. Non-gate loaders fetch render data and
1100
- * therefore run after the mutation when a native POST needs a fresh document. */
1101
- const runLayoutGates = async (route, ctx) => {
1102
- const modules = await loadLayoutModules(route);
1103
- for (let i = 0; i < modules.length; i++) {
1104
- const mod = modules[i];
1105
- if (mod?.gate !== true || mod.loader === undefined)
1106
- continue;
1107
- try {
1108
- await mod.loader({
1109
- ...ctx,
1110
- params: scopeParams(ctx.params, route.layoutParams?.[i]),
1111
- });
1112
- }
1113
- catch (err) {
1114
- throw tagLayoutError(err, route.layoutIds[i]);
1115
- }
1116
- }
1117
- return modules;
1118
- };
1119
- // Build a route's render chain + its merged `<head>` from the already-loaded layout modules + the
1120
- // page module. The chain is `[…layout components, page]`; the head merges each layout's `meta`
1121
- // export (outermost→innermost) with the page's (last), so a `head`/`meta` on `_layout.tsx`
1122
- // contributes sitewide tags. `metaArgs` (loader data + params) feed function-form `meta`s.
1123
- const resolveChainAndHead = (layoutModules, page, metaArgs) => {
1124
- const chain = [...layoutModules.map((m) => m.default), page.default];
1125
- const heads = [
1126
- ...layoutModules.map((m) => resolveMeta(m.meta, metaArgs)),
1127
- resolveMeta(page.meta, metaArgs),
1128
- ];
1129
- return { chain, head: mergeHeads(heads) };
1130
- };
1131
- // Dir a special-file id lives in: `_error`→"" , `a/b/_error`→"a/b" (and likewise for `_layout`).
1132
- const dirOfId = (id, suffix) => id === suffix ? "" : id.slice(0, id.length - suffix.length - 1);
1133
- /**
1134
- * Choose the `_error` boundary for a failure, respecting where a LAYOUT loader failed.
1135
- *
1136
- * A route error uses the nearest boundary, as it always has. A layout error must not: the nearest
1137
- * boundary can sit BELOW the layout that threw, and rendering there would wrap the boundary in that
1138
- * very layout - the one whose loader just failed and whose data therefore never arrived.
1139
- */
1140
- const boundaryFor = (route, err) => {
1141
- const ids = route.errorIds ?? [];
1142
- const failing = layoutErrorId(err);
1143
- if (failing === undefined)
1144
- return ids.at(-1);
1145
- const layoutDir = dirOfId(failing, "_layout");
1146
- // Deepest boundary at or ABOVE the failing layout's directory.
1147
- for (let i = ids.length - 1; i >= 0; i--) {
1148
- const errDir = dirOfId(ids[i], "_error");
1149
- if (errDir === "" || errDir === layoutDir || layoutDir.startsWith(`${errDir}/`))
1150
- return ids[i];
1151
- }
1152
- return undefined;
1153
- };
1154
- // The request's origin (scheme + host + port, NO trailing slash) - the one server fact `meta()` needs
1155
- // for absolute `canonical`/`og:url`/`og:image` but can't otherwise see (it also runs on the client).
1156
- // `URL.origin` is exactly that shape; it matches the browser's `location.origin` for the same URL, so
1157
- // a soft-nav's `applyHead` resolves an identical `<head>` (no hydration drift). A malformed `req.url`
1158
- // (shouldn't happen on a real request) degrades to `""` - the documented unknown-origin default -
1159
- // rather than throwing during render.
1160
- const originOf = (req) => {
1161
- try {
1162
- return new URL(req.url).origin;
1163
- }
1164
- catch {
1165
- return "";
1166
- }
1167
- };
1168
- // The request's `pathname + search` - threaded into `renderPage` so an adapter's `useLocation`/
1169
- // `useSearchParams` render the current URL server-side and hydrate against the client's initial state
1170
- // (which the client entry seeds from `location.pathname + location.search`). No hash: it never reaches
1171
- // the server. A malformed `req.url` degrades to "/" rather than throwing during render.
1172
- const pathOf = (req) => {
1173
- try {
1174
- const parts = urlPartsFor(req);
1175
- return parts.pathname + parts.search;
1176
- }
1177
- catch {
1178
- return "/";
1179
- }
1180
- };
1181
- /**
1182
- * Render the **nearest `_error` boundary** when a route's loader throws (the agnostic, server-side
1183
- * half of error UI - works on every adapter, no client takeover). The boundary renders in place of
1184
- * the page, wrapped by the layouts **at or above** its segment (deeper layouts are dropped). It's
1185
- * served **non-hydrated** at status 500: a terminal page, and rendering a boundary (not the page the
1186
- * client maps this route to) would otherwise hydrate-mismatch. The component receives `{ name,
1187
- * message }` - never the stack (no internals leak into HTML).
1188
- */
1189
- const renderError = async (route, errorId, err) => {
1190
- const errDir = dirOfId(errorId, "_error");
1191
- const keptLayoutIds = route.layoutIds.filter((id) => {
1192
- const ld = dirOfId(id, "_layout");
1193
- return ld === "" || ld === errDir || errDir.startsWith(`${ld}/`);
1194
- });
1195
- const layouts = await Promise.all(keptLayoutIds.map((id) => manifest.layouts[id].load().then((m) => m.default)));
1196
- const { default: errComp } = await (manifest.errors?.[errorId]).load();
1197
- const e = err instanceof Error ? err : new Error(String(err));
1198
- return renderPageResult({
1199
- adapter,
1200
- chain: [...layouts, errComp],
1201
- data: { name: e.name, message: e.message },
1202
- clientEntry,
1203
- routeId: errorId,
1204
- status: 500,
1205
- hydrate: false,
1206
- ...titleOption,
1207
- });
1208
- };
1209
- // The 404 response - the `_404` page (status 404) or a plain-text fallback. Shared by the wildcard
1210
- // catch-all (unmatched paths) and the `fallback: "404"` enforcement (unlisted paths under a route
1211
- // that opted out of on-demand SSR).
1212
- const renderNotFound = (path) => renderTerminalStatus(404, path);
1213
- /**
1214
- * Render a terminal-status page: the `_<status>` page if the app authored one, else `_404`, else
1215
- * plain text. Shared by the wildcard catch-all, `fallback: "404"` enforcement, and a loader's
1216
- * `notFound()` / `gone()` / `statusPage()`, so all of them resolve the page and set the status
1217
- * through one path rather than forking.
1218
- *
1219
- * Hydrates, following the `_404` precedent rather than `_error`'s non-hydrated 500: these are
1220
- * ordinary pages the client router can own, and a 404 arrived at by clicking a link should behave
1221
- * like any other route.
1222
- */
1223
- const renderTerminalStatus = async (status, path, extraHeaders) => {
1224
- const page = manifest.statusPages?.[String(status)] ?? manifest.notFound;
1225
- if (page === undefined) {
1226
- const headers = new Headers(extraHeaders);
1227
- headers.set("content-type", "text/plain; charset=utf-8");
1228
- return new Response(STATUS_TEXT[status] ?? "Error", { status, headers });
1229
- }
1230
- // The routeId decides which preload/style bundle and which client component this maps to, so it
1231
- // must name the page actually rendered - `_410` when `_410.tsx` exists, `_404` when it fell back.
1232
- const routeId = manifest.statusPages?.[String(status)] !== undefined ? `_${status}` : "_404";
1233
- const loaded = (await page.load());
1234
- const component = loaded.default;
1235
- return renderPageResult({
1236
- adapter,
1237
- chain: [component],
1238
- data: null,
1239
- clientEntry,
1240
- routeId,
1241
- // The page hydrates, so besides `path` its SSR `search` must equal the client mount's derivation for
1242
- // this routeId (`searchOf(searchSchema, url.search)`), or a status page reading `useSearch` drifts.
1243
- // Only when `path` is present (a real URL); a schema-less status page then gets the raw parsed query.
1244
- ...(path !== undefined
1245
- ? {
1246
- search: searchOf(loaded.searchSchema, path.includes("?") ? path.slice(path.indexOf("?")) : ""),
1247
- }
1248
- : {}),
1249
- // The page hydrates, so its SSR `path` must equal the client's initial
1250
- // `location.pathname+search` (an unmatched path yields no params → `{}`), or a `useLocation`
1251
- // on it would drift.
1252
- ...(path !== undefined ? { path } : {}),
1253
- status,
1254
- ...(extraHeaders !== undefined ? { headers: extraHeaders } : {}),
1255
- ...preloadOf(routeId),
1256
- ...stylesOf(routeId),
1257
- prerenderedPaths: options.prerenderedPaths ?? [],
1258
- ...titleOption,
1259
- });
1260
- };
1261
- /**
1262
- * Answer a loader's terminal-status signal, in whichever form the caller asked for.
1263
- *
1264
- * A hard navigation wants the document, so it gets the rendered boundary. A client-side navigation
1265
- * fetched DATA, not a document, so it gets an empty body plus the status on `X-Nifra-Status`, and
1266
- * the client router renders the same boundary from its own manifest. Sending the HTML back to a
1267
- * soft-nav would be answering a different question than the one asked - and skipping the header
1268
- * entirely is what leaves a crawler seeing a correct 404 while a user who clicked a link sees a
1269
- * blank page.
1270
- */
1271
- const renderStatusSignal = (req, signal) => {
1272
- const { status, headers } = signal[STATUS_SIGNAL];
1273
- if (req.headers.get(DATA_HEADER) !== null) {
1274
- const responseHeaders = new Headers(headers);
1275
- responseHeaders.set(STATUS_HEADER, String(status));
1276
- return new Response(null, { status, headers: responseHeaders });
1277
- }
1278
- return renderTerminalStatus(status, pathOf(req), headers);
1279
- };
1280
- for (const route of manifest.routes) {
1281
- // A dynamic route whose `getStaticPaths` declared `fallback: "404"` - only its prerendered paths
1282
- // exist; anything else 404s (computed once per route, not per request).
1283
- const is404Fallback = options.staticFallbacks?.[route.pattern] === "404";
1284
- // Per-route document-assembly cache (see RenderAssemblyCache): filled on the first GET render and
1285
- // reused while the route + layout MODULE IDENTITIES are unchanged. Attached only when every meta
1286
- // in the chain is static - a `meta(data)` function makes the head per-request, so those routes
1287
- // always assemble fresh. A module reload (dev HMR) yields new module objects, dropping the slot.
1288
- let assemblySlot;
1289
- let assemblySlotMod;
1290
- let assemblySlotLayouts;
1291
- const assemblyCacheFor = (mod, lms) => {
1292
- if (typeof mod.meta === "function")
1293
- return {};
1294
- for (const m of lms)
1295
- if (typeof m.meta === "function")
1296
- return {};
1297
- const layoutsUnchanged = assemblySlotLayouts !== undefined &&
1298
- assemblySlotLayouts.length === lms.length &&
1299
- assemblySlotLayouts.every((m, i) => m === lms[i]);
1300
- if (assemblySlotMod !== mod || !layoutsUnchanged) {
1301
- assemblySlot = {};
1302
- assemblySlotMod = mod;
1303
- assemblySlotLayouts = lms;
1304
- }
1305
- return { assemblyCache: assemblySlot };
1306
- };
1307
- app.register("GET", route.pattern, undefined, async (c) => {
1308
- // Enforce `fallback: "404"` before any work: an unlisted path under this route doesn't exist.
1309
- // Covers hard navigation directly; a client soft-nav's data fetch gets the 404, throws, and the
1310
- // history layer falls back to a full-page navigation (which lands here again, as a document).
1311
- if (is404Fallback && !prerenderedSet.has(urlPartsFor(c.req).pathname)) {
1312
- return renderNotFound(pathOf(c.req));
1313
- }
1314
- const mod = await route.load();
1315
- const draft = await draftFlag(c.req);
1316
- let data;
1317
- let layoutData;
1318
- let boundaryStates;
1319
- let layoutModules;
1320
- let layoutRetained = [];
1321
- try {
1322
- const ctx = {
1323
- params: c.params,
1324
- request: c.req,
1325
- req: c.req,
1326
- api,
1327
- env: c.env,
1328
- draft,
1329
- search: loaderSearch(mod.searchSchema, c.req),
1330
- };
1331
- // Layout loaders run for BOTH the document and the data-only request. A gate that only ran on
1332
- // the document path would be bypassed by adding the data header, which is exactly the request
1333
- // a client navigation makes - a guard has to hold on the path an attacker can pick.
1334
- //
1335
- // `runLayoutChain` returns once every GATE has resolved, with the non-gate loaders still in
1336
- // flight. So the page loader starts as late as correctness requires and as early as speed
1337
- // allows, and both are awaited together below.
1338
- const run = await runLayoutChain(route, ctx, validatedRetainedIndices(c.req, route, c.params));
1339
- layoutModules = run.modules;
1340
- layoutRetained = run.retained;
1341
- const boundaryDefinitions = [
1342
- ...run.modules.flatMap((layout) => layout.boundaries ?? []),
1343
- ...(mod.boundaries ?? []),
1344
- ];
1345
- if (boundaryDefinitions.length > 0)
1346
- boundaryDescriptors(boundaryDefinitions);
1347
- const effectiveSearch = searchChainOf(run.modules, mod, c.req);
1348
- const boundaryBatch = boundaryDefinitions.length === 0
1349
- ? undefined
1350
- : startDynamicBoundaries(boundaryDefinitions, {
1351
- request: c.req,
1352
- params: c.params,
1353
- api,
1354
- env: c.env,
1355
- draft,
1356
- search: effectiveSearch,
1357
- signal: c.req.signal,
1358
- });
1359
- const staticBoundaryPromise = boundaryDefinitions.length === 0
1360
- ? Promise.resolve(undefined)
1361
- : resolveStaticBoundaries(boundaryDefinitions, { phase: "build", origin: originOf(c.req) }, options.staticBoundaryCache);
1362
- // Boundary data is attached as one Deferred marker per slot. The shell can render
1363
- // immediately with each slot pending, while the existing deferred protocol emits the first
1364
- // completed sibling independently instead of waiting for the slowest boundary.
1365
- // The page loader gets the EFFECTIVE search (layout chain + page, page-wins), now that the layout
1366
- // modules are loaded - so `ctx.search` includes a layout's shared keys (`?org`), matching `useSearch`.
1367
- const [pageData, , staticBoundaries] = await Promise.all([
1368
- mod.loader ? mod.loader({ ...ctx, search: effectiveSearch }) : null,
1369
- run.pending, // a non-gate layout loader that rejects must still surface, not go unhandled
1370
- staticBoundaryPromise,
1371
- ]);
1372
- data = pageData;
1373
- layoutData = run.layoutData;
1374
- if (boundaryBatch !== undefined) {
1375
- const streamed = { ...boundaryBatch.initial, ...(staticBoundaries ?? {}) };
1376
- for (const entry of boundaryBatch.pending) {
1377
- const initial = streamed[entry.name];
1378
- if (initial !== undefined)
1379
- streamed[entry.name] = { ...initial, data: defer(entry.promise) };
1380
- }
1381
- boundaryStates = streamed;
1382
- }
1383
- else if (staticBoundaries !== undefined) {
1384
- boundaryStates = staticBoundaries;
1385
- }
1386
- }
1387
- catch (err) {
1388
- // A terminal-status signal (`notFound()` / `gone()` / `statusPage(n)`) renders a boundary at
1389
- // that status. Checked BEFORE the pass-through below: a signal IS a `Response`, so the order
1390
- // is what keeps a hand-rolled `throw new Response(...)` served verbatim, as it always was.
1391
- if (isStatusSignal(err))
1392
- return renderStatusSignal(c.req, err);
1393
- // A thrown control-flow signal (a guard's `redirect(...)`, an explicit error response) - let
1394
- // it propagate to core, which renders it as-is, whether it is a plain render or a
1395
- // hand-rolled `Response`. Real errors render the nearest `_error` boundary, if any; with
1396
- // none, rethrow (unchanged 500 behavior).
1397
- if (isControlFlow(err))
1398
- throw err;
1399
- // Let reporting plugins observe the data-layer failure before it's rendered/rethrown/500'd.
1400
- if (options.onLoaderError !== undefined) {
1401
- try {
1402
- options.onLoaderError(err, { request: c.req, params: c.params, route: route.pattern });
1403
- }
1404
- catch {
1405
- // A faulty reporter must never break error rendering.
1406
- }
1407
- }
1408
- const errorId = boundaryFor(route, err);
1409
- if (errorId === undefined)
1410
- throw err;
1411
- // A soft-nav data fetch can't render a boundary - 500 so the client falls back to a full-page
1412
- // navigation, which lands here as a document and renders the `_error` page.
1413
- if (c.req.headers.get(DATA_HEADER) !== null) {
1414
- return new Response("Internal Server Error", {
1415
- status: 500,
1416
- headers: { "content-type": "text/plain; charset=utf-8" },
1417
- });
1418
- }
1419
- return renderError(route, errorId, withDuplicateInstanceHint(err));
1420
- }
1421
- // A loader may RETURN its control-flow signal instead of throwing it - `return redirect(...)`
1422
- // reads naturally and must not silently serialize the signal as loader data. Mirror the catch
1423
- // above exactly: a status signal renders its boundary, any other signal (a redirect, a
1424
- // hand-rolled response) passes through to core verbatim - so return and throw are
1425
- // interchangeable.
1426
- if (isStatusSignal(data))
1427
- return renderStatusSignal(c.req, data);
1428
- if (isControlFlow(data))
1429
- return data;
1430
- // Client-side navigation asks (via the X-Nifra-Data header) for just the loader data - no full
1431
- // document, no layout chain. A route with deferred data streams NDJSON (critical data first,
1432
- // then each deferred value as it settles); otherwise one JSON (the fast path). Same loader,
1433
- // same auth - only the transport differs.
1434
- if (c.req.headers.get(DATA_HEADER) !== null) {
1435
- const pageSplit = prepareDeferred(data);
1436
- const layoutSplits = [];
1437
- let offset = pageSplit.deferred.length;
1438
- for (const entry of layoutData ?? []) {
1439
- const split = prepareDeferred(entry, offset);
1440
- layoutSplits.push(split);
1441
- offset += split.deferred.length;
1442
- }
1443
- const deferred = [...pageSplit.deferred, ...layoutSplits.flatMap((split) => split.deferred)];
1444
- const boundarySplit = boundaryStates === undefined
1445
- ? undefined
1446
- : prepareDeferred(boundaryStates, deferred.length);
1447
- const allDeferred = [
1448
- ...deferred,
1449
- ...(boundarySplit === undefined ? [] : boundarySplit.deferred),
1450
- ];
1451
- const payload = layoutData === undefined && boundarySplit === undefined
1452
- ? pageSplit.forClient
1453
- : {
1454
- v: 1,
1455
- data: pageSplit.forClient,
1456
- layoutData: layoutSplits.map((split) => split.forClient),
1457
- retained: layoutRetained,
1458
- ...(boundarySplit === undefined ? {} : { boundaries: boundarySplit.forClient }),
1459
- };
1460
- // Bare value when there is no layout data - the pre-envelope shape, so a client running older
1461
- // code against a newer server keeps working.
1462
- if (allDeferred.length === 0) {
1463
- return Response.json(payload ?? null);
1464
- }
1465
- return new Response(ndjsonStream(payload, allDeferred), {
1466
- headers: { "content-type": "application/x-ndjson; charset=utf-8" },
1467
- });
1468
- }
1469
- const chainLayoutModules = layoutModules ?? (await loadLayoutModules(route));
1470
- const { chain, head } = resolveChainAndHead(chainLayoutModules, mod, {
1471
- data,
1472
- params: c.params,
1473
- origin: originOf(c.req),
1474
- });
1475
- const hydrateRoute = mod.hydrate !== false;
1476
- try {
1477
- // `await` so a shell-render throw (renderToStream rejects before any byte) is caught here and
1478
- // can render the `_error` page - not just a loader throw. Mid-stream (post-shell) throws can't
1479
- // be recovered to a full page; the per-adapter client boundary catches client render errors.
1480
- return await renderPageResult({
1481
- adapter,
1482
- chain,
1483
- data,
1484
- head,
1485
- clientEntry,
1486
- routeId: route.id,
1487
- params: c.params,
1488
- path: pathOf(c.req),
1489
- // The effective (layout chain + page) search, matching the page loader's `ctx.search` above and
1490
- // the client mount - so `useSearch` renders SSR-correct and hydrates with no drift. `layoutModules`
1491
- // is loaded by now (the loader try succeeded to reach here).
1492
- search: searchChainOf(layoutModules ?? [], mod, c.req),
1493
- hydrate: hydrateRoute,
1494
- ...(layoutData !== undefined ? { layoutData } : {}),
1495
- ...(boundaryStates !== undefined ? { boundaries: boundaryStates } : {}),
1496
- ...preloadOf(route.id),
1497
- ...stylesOf(route.id),
1498
- prerenderedPaths: options.prerenderedPaths ?? [],
1499
- ...(mod.revalidate !== undefined ? { revalidate: mod.revalidate } : {}),
1500
- ...(mod.revalidateTags !== undefined ? { revalidateTags: mod.revalidateTags } : {}),
1501
- ...(mod.islandScripts !== undefined ? { islandScripts: mod.islandScripts } : {}),
1502
- ...titleOption,
1503
- ...assemblyCacheFor(mod, chainLayoutModules),
1504
- });
1505
- }
1506
- catch (err) {
1507
- // Same precedence as the loader catch above - a `meta()` may signal too.
1508
- if (isStatusSignal(err))
1509
- return renderStatusSignal(c.req, err);
1510
- if (isControlFlow(err))
1511
- throw err;
1512
- // Let reporting plugins observe the data-layer failure before it's rendered/rethrown/500'd.
1513
- if (options.onLoaderError !== undefined) {
1514
- try {
1515
- options.onLoaderError(err, { request: c.req, params: c.params, route: route.pattern });
1516
- }
1517
- catch {
1518
- // A faulty reporter must never break error rendering.
1519
- }
1520
- }
1521
- const errorId = boundaryFor(route, err);
1522
- if (errorId === undefined)
1523
- throw err;
1524
- return renderError(route, errorId, withDuplicateInstanceHint(err));
1525
- }
1526
- });
1527
- // POST runs the route's `action` (mutation). A control-flow return (e.g. a `redirect(...)`)
1528
- // passes straight through; a data return re-renders the page (the loader re-runs for fresh
1529
- // data) with `actionData`. Routes without an action reject POST with 405 - not a stray 404.
1530
- app.register("POST", route.pattern, undefined, async (c) => {
1531
- const mod = await route.load();
1532
- const draft = await draftFlag(c.req);
1533
- if (mod.action === undefined) {
1534
- return new Response("Method Not Allowed", {
1535
- status: 405,
1536
- headers: { allow: "GET", "content-type": "text/plain; charset=utf-8" },
1537
- });
1538
- }
1539
- const actionContext = {
1540
- params: c.params,
1541
- request: c.req,
1542
- req: c.req,
1543
- api,
1544
- env: c.env,
1545
- draft,
1546
- search: loaderSearch(mod.searchSchema, c.req),
1547
- };
1548
- const isDataRequest = c.req.headers.get(DATA_HEADER) !== null;
1549
- let layoutModules;
1550
- let result;
1551
- try {
1552
- // A gate is an authorization boundary for everything beneath its layout, mutations included.
1553
- // Run only gates before the action; ordinary layout data loaders run after a native mutation.
1554
- layoutModules = await runLayoutGates(route, actionContext);
1555
- result = await mod.action(actionContext);
1556
- }
1557
- catch (err) {
1558
- // A THROWN signal is the same control flow as a returned one (`throw redirect()` in a gate
1559
- // or an action) - route it through the same conversion as the returned branch below, so
1560
- // throw and return are interchangeable on the mutation path too.
1561
- if (isControlFlow(err))
1562
- return actionResponse(err, isDataRequest);
1563
- throw err;
1564
- }
1565
- // An action may wrap its data in `revalidate(paths, data)` to declare which routes it changed.
1566
- // Unwrap to the inner data; the paths ride the `X-Nifra-Revalidate` header on the data-mode
1567
- // responses (the client acts on them - a full-page POST re-runs loaders inline, so no header).
1568
- const isRevalidate = result !== null && typeof result === "object" && "__nifraRevalidate" in result;
1569
- const actionResult = isRevalidate ? result.data : result;
1570
- const revalidateHeader = isRevalidate
1571
- ? { [REVALIDATE_HEADER]: result.__nifraRevalidate.join(",") }
1572
- : {};
1573
- if (isControlFlow(actionResult))
1574
- return actionResponse(actionResult, isDataRequest);
1575
- // Client submit wants just the action's data (it revalidates the loader itself); a native
1576
- // form POST re-renders the full page (loader re-runs) with the action data.
1577
- if (isDataRequest) {
1578
- // An action may `defer()` slow parts of its result - stream them (critical data first, then
1579
- // each deferred as it settles) exactly like a loader; a non-deferred action returns one JSON.
1580
- const { forClient, deferred } = prepareDeferred(actionResult);
1581
- if (deferred.length === 0)
1582
- return Response.json(actionResult ?? null, { headers: revalidateHeader });
1583
- return new Response(ndjsonStream(forClient, deferred), {
1584
- headers: { "content-type": "application/x-ndjson; charset=utf-8", ...revalidateHeader },
1585
- });
1586
- }
1587
- // Derived once and shared: the loader's `ctx.search` and the render's `RenderProps.search` are the
1588
- // SAME effective (layout chain + page) value, and the client mount rebuilds it identically. The
1589
- // layout modules are already loaded (the action ran through their gates above).
1590
- const search = searchChainOf(layoutModules, mod, c.req);
1591
- const data = mod.loader
1592
- ? await mod.loader({
1593
- params: c.params,
1594
- request: c.req,
1595
- req: c.req,
1596
- api,
1597
- env: c.env,
1598
- draft,
1599
- search,
1600
- })
1601
- : null;
1602
- const { chain, head } = resolveChainAndHead(layoutModules, mod, {
1603
- data,
1604
- params: c.params,
1605
- origin: originOf(c.req),
1606
- });
1607
- const hydrateRoute = mod.hydrate !== false;
1608
- // A full-page POST streams the action's `defer()`'d parts mid-document behind `<Await>` too -
1609
- // `renderPage` splits `actionData` like loader data (works with JS off; hydrates after).
1610
- return renderPageResult({
1611
- adapter,
1612
- chain,
1613
- data,
1614
- actionData: actionResult,
1615
- head,
1616
- clientEntry,
1617
- routeId: route.id,
1618
- params: c.params,
1619
- path: pathOf(c.req),
1620
- search,
1621
- hydrate: hydrateRoute,
1622
- ...preloadOf(route.id),
1623
- ...stylesOf(route.id),
1624
- prerenderedPaths: options.prerenderedPaths ?? [],
1625
- ...titleOption,
1626
- });
1627
- });
1628
- }
1629
- // Register llms.txt & llms-full.txt
1630
- const llmsOptions = { includeLocalGuidelines: options.publishLocalGuidelines === true };
1631
- app.register("GET", "/llms.txt", undefined, async () => {
1632
- const text = await generateLlmsTxt(false, manifest.routes, api, llmsOptions);
1633
- return new Response(text, {
1634
- headers: { "content-type": "text/plain; charset=utf-8" },
1635
- });
1636
- });
1637
- app.register("GET", "/llms-full.txt", undefined, async () => {
1638
- const text = await generateLlmsTxt(true, manifest.routes, api, llmsOptions);
1639
- return new Response(text, {
1640
- headers: { "content-type": "text/plain; charset=utf-8" },
1641
- });
1642
- });
1643
- // Wildcard catch-all: unmatched paths render `_404` (404), or a plain text 404 if absent.
1644
- app.register("GET", "/*", undefined, (c) => renderNotFound(pathOf(c.req)));
1645
- return app;
1646
- }
1647
- /**
1648
- * Codegen: emit a client-entry module (as source) that lazily imports each route's layout chain
1649
- * (so `Bun.build` with `splitting` code-splits one chunk per route), builds a `patterns` list,
1650
- * then creates the agnostic router store (with a `loadModule` hook), installs history + form
1651
- * interception, loads the initial route's chunk, and hydrates the adapter's stateful Router. The
1652
- * initial route is derived from the URL (falling back to the server-injected route id, e.g.
1653
- * `_404`), so after hydration the Router owns navigation and swaps routes without full reloads.
1654
- * Bun has no `import.meta.glob`, so file-based routing needs this. Write the result to a file and
1655
- * bundle it with `buildClient` / `Bun.build` (+ the adapter's transform).
1656
- */
1657
- export function generateClientEntry(manifest, options) {
1658
- const { clientModule, resolve } = options;
1659
- const loaderRows = [];
1660
- const patternRows = [];
1661
- const statusRoutes = {};
1662
- // Routes whose loader appends a nearest `_error` module (LAST) - the client wraps the page in the
1663
- // adapter's `errorBoundary(fallback)` for these, so a client render error shows the `_error` UI.
1664
- const errorRouteIds = [];
1665
- // Lazy loader returns the raw modules (for both the component chain + the page's `meta` export).
1666
- const lazyLoader = (files) => {
1667
- const imports = files.map((f) => `import(${jsStringLiteral(resolve(f))})`).join(", ");
1668
- return `() => Promise.all([${imports}])`;
1669
- };
1670
- for (const route of manifest.routes) {
1671
- // layoutIds only reference layouts present in the manifest (buildManifest invariant).
1672
- const files = [
1673
- ...route.layoutIds.map((id) => manifest.layouts[id].file),
1674
- route.file,
1675
- ];
1676
- // Append the nearest `_error` file LAST, so loadModule can pull it off the tail and wrap the page.
1677
- const nearestErrorId = route.errorIds?.at(-1);
1678
- const errorFile = nearestErrorId === undefined ? undefined : manifest.errors?.[nearestErrorId]?.file;
1679
- if (errorFile !== undefined) {
1680
- files.push(errorFile);
1681
- errorRouteIds.push(route.id);
1682
- }
1683
- loaderRows.push(` ${JSON.stringify(route.id)}: ${lazyLoader(files)},`);
1684
- patternRows.push(` { routeId: ${JSON.stringify(route.id)}, pattern: ${JSON.stringify(route.pattern)} },`);
1685
- }
1686
- if (manifest.notFound !== undefined) {
1687
- loaderRows.push(` "_404": ${lazyLoader([manifest.notFound.file])},`);
1688
- statusRoutes[404] = "_404";
1689
- }
1690
- for (const [status, entry] of Object.entries(manifest.statusPages ?? {})) {
1691
- const routeId = `_${status}`;
1692
- loaderRows.push(` ${JSON.stringify(routeId)}: ${lazyLoader([entry.file])},`);
1693
- statusRoutes[Number(status)] = routeId;
1694
- }
1695
- return `${[
1696
- // `/client`, never the root: the root's graph carries the server (renderPage, the static-file
1697
- // server), and Vite's dev server evaluates what it is given instead of tree-shaking it.
1698
- 'import { createClientRouter, createMatcher, mergeHeads, resolveMeta } from "@nifrajs/web/client"',
1699
- 'import { applyHead, installForms, installHistory, signalHydrated } from "@nifrajs/web/client"',
1700
- // Namespace import: `errorBoundary` is optional (an adapter may not export it). A namespace member
1701
- // access yields `undefined` if absent - unlike a named import, which would be a link error.
1702
- `import * as __adapter from ${JSON.stringify(clientModule)}`,
1703
- "const { mountRouter } = __adapter",
1704
- // The assurance hook is optional: ordinary client entries pay only for the namespace lookup, while
1705
- // hydration runners get a runtime identity from the exact adapter module that mounted the page. The
1706
- // registry is token-only and lives on a Symbol.for key so it cannot collide with app data.
1707
- "const __hydrationHook = __adapter.hydrationAssuranceHook",
1708
- 'if (__hydrationHook && typeof __hydrationHook.runtimeIdentity === "function") {',
1709
- ' const __runtimeKey = Symbol.for("nifra.hydration.runtime")',
1710
- " const __runtimeState = globalThis[__runtimeKey]",
1711
- " const __identities = __runtimeState && Array.isArray(__runtimeState.identities) ? __runtimeState.identities : []",
1712
- " globalThis[__runtimeKey] = { framework: __hydrationHook.framework, identities: [...__identities, __hydrationHook.runtimeIdentity()] }",
1713
- "}",
1714
- // The `clientModule` contract is a string specifier, so nothing type-checks that the module it
1715
- // names actually exports `mountRouter`. Without this the miss surfaces as
1716
- // "mountRouter is not a function" from inside a bundled chunk, at first paint, naming neither the
1717
- // module nor the requirement - a self-executing entry passes every build and fails only here.
1718
- `if (typeof mountRouter !== "function") throw new Error(${JSON.stringify(`[nifra/web] clientModule ${JSON.stringify(clientModule)} does not export \`mountRouter\`. ` +
1719
- "A client module must export `mountRouter({ router, routes, container })` - it is called by " +
1720
- "the generated bootstrap, so a self-executing entry will not work. Use your adapter's " +
1721
- '`/client` entry (e.g. "@nifrajs/web-react/client"), or re-export mountRouter from it.')})`,
1722
- "const errorBoundary = __adapter.errorBoundary",
1723
- // A hot update that the framework cannot actually apply must end in a reload, not in nothing.
1724
- //
1725
- // Bun's dev server applies React Fast Refresh to JSX modules. For React that patches the component
1726
- // and preserves state. For Preact it does not - the module still LOOKS Fast-Refresh-able, so the
1727
- // update is accepted and then swallowed: `bun:beforeUpdate`/`bun:afterUpdate` both fire, the server
1728
- // logs a rebuild, and the page silently keeps rendering the old code. An edit that appears to do
1729
- // nothing is the worst failure mode in a dev loop - worse than a reload, because there is no signal
1730
- // to act on. An adapter that knows its framework is in that position says so, and the entry turns
1731
- // the swallowed update into an honest full reload.
1732
- 'if (import.meta.hot && __adapter.hotUpdateNeedsReload) import.meta.hot.on("bun:afterUpdate", () => location.reload())',
1733
- `const errorRouteIds = new Set(${JSON.stringify(errorRouteIds)})`,
1734
- // Each route is a lazy loader: dynamic imports → Bun.build (splitting) emits one chunk per
1735
- // route, shared layouts/deps deduped into shared chunks, so a route's code loads only when
1736
- // visited. loadModule caches the [layouts…, page] component chain + the chain's meta list per id.
1737
- "const loaders = {",
1738
- ...loaderRows,
1739
- "}",
1740
- "const chains = {}",
1741
- "const metas = {}",
1742
- // routeId → the page module's `searchSchema` export (or undefined). Populated lazily with
1743
- // chains/metas so the mount can derive this route's typed `search` from the URL, matching the SSR.
1744
- "const searchSchemas = {}",
1745
- // routeId → the page's client-only search keys (`searchClientKeys`, or `[]`). The router reads this
1746
- // by reference to decide when a same-route search change can skip the loader fetch (re-render only).
1747
- "const searchClientKeys = {}",
1748
- // routeId → the page's optional post-hydration client loader/action hooks. Hooks are populated only
1749
- // after the route chunk loads, so routes that do not declare them remain ordinary route modules.
1750
- "const routeHooks = {}",
1751
- "const loadModule = async (id) => {",
1752
- " if (chains[id]) return",
1753
- " const mods = await loaders[id]()",
1754
- // For an error route the `_error` module is appended LAST: wrap the page (now second-to-last) in
1755
- // the adapter's boundary so a client render error renders the `_error` UI. DOM-transparent, so the
1756
- // hydrated tree matches the SSR markup (which has no boundary). Falls back to the plain chain when
1757
- // the adapter has no `errorBoundary`.
1758
- // `metas[id]` is the chain's `meta` exports in head order (outermost layout → … → page), so a
1759
- // soft-nav merges the layout chain's head with the page's - matching the SSR `<head>` (sitewide
1760
- // layout tags persist across client navigation, no flash of page-only head). `_error` carries no
1761
- // head (a terminal boundary), so it's excluded from the meta list for error routes.
1762
- " if (errorBoundary && errorRouteIds.has(id)) {",
1763
- " const fallback = mods[mods.length - 1].default",
1764
- " const page = mods[mods.length - 2].default",
1765
- " const layouts = mods.slice(0, mods.length - 2).map((m) => m.default)",
1766
- " chains[id] = [...layouts, errorBoundary(fallback), page]",
1767
- " metas[id] = mods.slice(0, mods.length - 1).map((m) => m.meta)",
1768
- // The search-schema CHAIN is the layout modules + page (all but the appended `_error`), so a layout's
1769
- // `searchSchema` merges with the page's. Client keys come from the page (second-to-last).
1770
- " searchSchemas[id] = mods.slice(0, mods.length - 1).map((m) => m.searchSchema)",
1771
- " searchClientKeys[id] = mods[mods.length - 2].searchClientKeys ?? []",
1772
- " } else {",
1773
- " chains[id] = mods.map((m) => m.default)",
1774
- " metas[id] = mods.map((m) => m.meta)",
1775
- // The chain is every module (layouts + page); client keys come from the page (the last module).
1776
- " searchSchemas[id] = mods.map((m) => m.searchSchema)",
1777
- " searchClientKeys[id] = mods[mods.length - 1].searchClientKeys ?? []",
1778
- " }",
1779
- " const page = errorRouteIds.has(id) ? mods[mods.length - 2] : mods[mods.length - 1]",
1780
- // Keep interception client-safe: only neutral name/mode metadata crosses into the router. The
1781
- // server-side boundary load function (which may close over secrets) is never stored in the client
1782
- // hook table or serialized into a browser bundle by this wiring.
1783
- " const boundaryMods = errorRouteIds.has(id) ? mods.slice(0, -1) : mods",
1784
- " const boundaries = boundaryMods.flatMap((m) => (m.boundaries ?? []).map((b) => ({ name: b.name, mode: b.mode, hasLoad: b.load !== undefined, ...(b.errorId === undefined ? {} : { errorId: b.errorId }) })))",
1785
- " routeHooks[id] = { clientLoader: page.clientLoader, clientAction: page.clientAction, boundaries }",
1786
- "}",
1787
- "const patterns = [",
1788
- ...patternRows,
1789
- "]",
1790
- // Derive the initial route from the URL (correct on refresh/deep-link); fall back to the
1791
- // server-injected route id for non-pattern routes (e.g. _404, which matches nothing).
1792
- "const matched = createMatcher(patterns)(location.pathname)",
1793
- // Map any `{__nifra_deferred: id}` placeholder in the SSR data to the registry's promise, so the
1794
- // component receives real promises to `<Await>` (a no-op when a page has no deferred data).
1795
- MAP_DEFERRED_SOURCE,
1796
- "const initial = {",
1797
- ` routeId: matched ? matched.routeId : (window.${ROUTE_GLOBAL} ?? ""),`,
1798
- " params: matched ? matched.params : {},",
1799
- // pathname + search (NOT just pathname): the SSR render threads `pathname+search` into
1800
- // `useLocation`/`useSearchParams`, so the hydrating initial state must carry the query too or a
1801
- // page reading the search string would hydrate-mismatch. The #hash is client-only (never SSR'd).
1802
- " path: location.pathname + location.search,",
1803
- ` data: mapDeferred(window.${DATA_GLOBAL}),`,
1804
- // Undefined on a page-only app, which is exactly what the router treats as "no layout data".
1805
- ` layoutData: window.${LAYOUT_DATA_GLOBAL} && window.${LAYOUT_DATA_GLOBAL}.map(mapDeferred),`,
1806
- ` boundaries: mapDeferred(window.${BOUNDARY_GLOBAL}),`,
1807
- // actionData (only set after a form POST) is in the initial state so the binding hydrates
1808
- // consistently with the server-rendered markup; mapped through `mapDeferred` too so a deferred
1809
- // action's placeholders become registry markers (a no-op when the action didn't defer).
1810
- ` actionData: mapDeferred(window.${ACTION_GLOBAL}),`,
1811
- " pending: false,",
1812
- "}",
1813
- `const statusRoutes = ${JSON.stringify(statusRoutes)}`,
1814
- "const router = createClientRouter({ patterns, initial, loadModule, statusRoutes, searchClientKeys, routeHooks })",
1815
- "installHistory(router)",
1816
- "installForms(router)",
1817
- // The container is found in the DOM, not baked in. `rootId` is a per-render option and this entry
1818
- // is a per-build artifact, so a hardcoded id is a guess: `renderPage({ rootId: "app" })` produced a
1819
- // perfect document that hydrated NOTHING, with no diagnostic, because the missing `#root` was
1820
- // swallowed by an `if (root)`. `renderPage` marks a custom container with `ROOT_ATTRIBUTE`; the
1821
- // default `#root` it leaves unmarked, which is what the fallback is for.
1822
- `const root = document.querySelector("body > div[${ROOT_ATTRIBUTE}]") ?? document.getElementById("root")`,
1823
- // Loud, because there is no recoverable case: this entry ships only in a document `renderPage`
1824
- // opened a container in, so reaching here means the document is not the one it was built for.
1825
- `if (!root) throw new Error(${JSON.stringify("[nifra/web] no hydration container found. The generated bootstrap mounts into the element " +
1826
- `renderPage opened the app in - the one marked \`${ROOT_ATTRIBUTE}\` when a custom \`rootId\` ` +
1827
- "is set, `#root` otherwise - and this document has neither. If you emit the document yourself, " +
1828
- 'keep `<div id="root">` around the SSR markup.')})`,
1829
- // Load the initial route's chunk, then hydrate the Router (chain is cached). The initial head
1830
- // is server-rendered; subsequent navigations update it from the matched route's meta + data.
1831
- "loadModule(initial.routeId).then(() => {",
1832
- " mountRouter({ router, routes: chains, searchSchemas, container: root })",
1833
- // Run the optional client loader only after the adapter has mounted the SSR tree. The initial
1834
- // server data is already in `window.__NIFRA_DATA__`, so `serverLoader()` reuses it and cannot
1835
- // duplicate the first request.
1836
- " router.hydrate().catch((error) => console.error('[nifra/web] clientLoader failed:', error))",
1837
- // Next frame: the adapter has committed its initial hydration, so handlers are attached. Flip the
1838
- // document to interactive (`data-nifra-hydrated` + `nifra:hydrated`) for apps to gate pre-hydration UI.
1839
- " requestAnimationFrame(signalHydrated)",
1840
- " router.subscribe(() => {",
1841
- " const s = router.snapshot()",
1842
- // Merge the matched route's chain meta (layouts→page) into one head - same contract as SSR.
1843
- " if (!s.pending) {",
1844
- // `origin: location.origin` matches the SSR `originOf(req)` (both are `URL.origin` for the same
1845
- // page URL), so a soft-nav re-resolves the SAME absolute canonical/og:url - no head drift.
1846
- " const args = { data: s.data, params: s.params, origin: location.origin }",
1847
- " applyHead(mergeHeads((metas[s.routeId] ?? [undefined]).map((m) => resolveMeta(m, args))))",
1848
- " }",
1849
- " })",
1850
- "})",
1851
- ].join("\n")}\n`;
1852
- }
1853
- /**
1854
- * Codegen: emit a `.d.ts` that types cross-route `navigate({ to, search })` against each route's
1855
- * `searchSchema`. It augments the {@link RouteSearch} map with `"<pattern>": SearchOf<typeof import(...)>`
1856
- * for every **static** route (one with no `:param`/`*` segment - a concrete `to` a caller can pass; a
1857
- * dynamic route's concrete path can't match its pattern key, so those keep the loose object form). Written
1858
- * by `nifra sync-routes` next to the route tree and included in the app's `tsconfig`; because it is
1859
- * regenerated from the route files, a `navigate` whose `search` no longer matches the route's schema
1860
- * becomes a `tsc` error - the same drift guarantee as nifra's typed client, no hand-maintained map.
1861
- */
1862
- export function generateRouteSearchTypes(manifest, options) {
1863
- const { resolve, module = "@nifrajs/web" } = options;
1864
- // Static routes only (no `:param` / `*` catch-all): their pattern IS a concrete `to`. Sorted for stable
1865
- // output; a dynamic route falls through to the loose `{ to: string; search?: Record<...> }` form.
1866
- const entries = manifest.routes
1867
- .filter((route) => !/[:*]/.test(route.pattern))
1868
- .map((route) => [route.pattern, resolve(route.file)])
1869
- .sort((a, b) => (a[0] < b[0] ? -1 : 1))
1870
- .map(([pattern, spec]) => ` ${JSON.stringify(pattern)}: SearchOf<typeof import(${JSON.stringify(spec)})>`);
1871
- return `${[
1872
- "// GENERATED by @nifrajs/web generateRouteSearchTypes - typed cross-route navigate({ to, search }).",
1873
- "// Regenerated from the route files; a stale navigate search shape becomes a tsc error. Do not edit.",
1874
- 'import type { SearchOf } from "@nifrajs/web"',
1875
- `declare module ${JSON.stringify(module)} {`,
1876
- " interface RouteSearch {",
1877
- ...entries,
1878
- " }",
1879
- "}",
1880
- "export {}",
1881
- ].join("\n")}\n`;
1882
- }
1883
- /**
1884
- * Codegen: emit a **server manifest** module (as source) for disk-less edge runtimes (Cloudflare
1885
- * Workers, …) - and, with a `target`, any portable server bundle. `discoverRoutes` scans `node:fs`
1886
- * and dynamic-imports each route by a *runtime* path - neither exists on workerd. This instead emits
1887
- * **statically-analyzable** imports of every route/layout/`_error`/terminal status page (so the bundler includes them) and
1888
- * rebuilds the manifest with `buildManifest` - the SAME pure logic `discoverRoutes` feeds, so patterns
1889
- * + layout chains are identical. Eager (`import * as`) by default; `lazy` emits `() => import(...)` so
1890
- * a code-splitting bundler chunks per route. The emitted module exports `manifest` (consumed by
1891
- * `createWebApp`, unchanged) + `clientEntry` (baked). Write it to a file and bundle it into the worker
1892
- * entry (see `buildServer` in `@nifrajs/web/build`).
1893
- */
1894
- // Route source files are emitted as EXTENSIONLESS import specifiers. An explicit `.tsx`/`.ts` in an
1895
- // import is a hard error under a plain `tsc` (TS5097) unless `allowImportingTsExtensions` is set - which
1896
- // only the nifra template tsconfig does - so the generated manifest failed a bare `tsc` with one error
1897
- // per route. Every bundler and `moduleResolution` still resolves the extensionless form to the source
1898
- // file, so dropping the extension costs nothing at build time and makes the output portable. Only a
1899
- // known TS/JS source extension is stripped; the map KEY keeps its extension (it is the route identifier
1900
- // `buildManifest` matches, not an import path).
1901
- const SOURCE_EXTENSION = /\.(?:[mc]?tsx?|[mc]?jsx?)$/;
1902
- function moduleSpecifier(resolved) {
1903
- return resolved.replace(SOURCE_EXTENSION, "");
1904
- }
1905
- export function generateServerManifest(manifest, options) {
1906
- const { resolve, clientEntry, styles, routeStyles, lazy = false } = options;
1907
- // Every unique source file in the manifest (routes + layouts + error/status pages), sorted for stable output.
1908
- const files = [
1909
- ...new Set([
1910
- ...manifest.routes.map((r) => r.file),
1911
- ...Object.values(manifest.layouts).map((l) => l.file),
1912
- ...Object.values(manifest.errors ?? {}).map((e) => e.file),
1913
- ...(manifest.notFound ? [manifest.notFound.file] : []),
1914
- ...Object.values(manifest.statusPages ?? {}).map((page) => page.file),
1915
- ]),
1916
- ].sort();
1917
- const header = [
1918
- "// GENERATED by @nifrajs/web generateServerManifest - route manifest for the disk-less edge",
1919
- "// (no filesystem; route imports are static specifiers the bundler resolves). buildManifest is",
1920
- "// the same pure logic discoverRoutes feeds, so patterns + layout chains match exactly.",
1921
- 'import { buildManifest, type RouteModule } from "@nifrajs/web"',
1922
- ];
1923
- const clientEntryLine = `export const clientEntry = ${JSON.stringify(clientEntry)}`;
1924
- // Baked stylesheet URLs so the server entry can pass them to createWebApp → <link rel="stylesheet">.
1925
- // Always emitted (default empty) so consumers can `import { styles, routeStyles }` unconditionally.
1926
- const stylesLine = `export const styles = ${JSON.stringify(styles ?? [])}`;
1927
- const routeStylesLine = `export const routeStyles = ${JSON.stringify(routeStyles ?? {})}`;
1928
- if (lazy) {
1929
- // Lazy: `() => import("./routes/x")` per route (static specifier → one chunk per route under a
1930
- // code-splitting bundler, loaded on first request). The map keys are the route-relative paths
1931
- // `buildManifest` expects; the importer it builds calls the per-file loader.
1932
- const loaders = files.map((file) => ` ${jsStringLiteral(file)}: () => import(${jsStringLiteral(moduleSpecifier(resolve(file)))}),`);
1933
- return `${[
1934
- ...header,
1935
- "const loaders: Record<string, () => Promise<RouteModule>> = {",
1936
- ...loaders,
1937
- "}",
1938
- clientEntryLine,
1939
- stylesLine,
1940
- routeStylesLine,
1941
- "export const manifest = buildManifest(Object.keys(loaders), (file) => () => loaders[file]())",
1942
- ].join("\n")}\n`;
1943
- }
1944
- // Eager: `import * as` per route (all bundled into the entry, parsed at boot). Index-based
1945
- // identifiers are collision-proof regardless of filename.
1946
- const imports = files.map((file, i) => `import * as m${i} from ${JSON.stringify(moduleSpecifier(resolve(file)))}`);
1947
- const entries = files.map((file, i) => ` ${JSON.stringify(file)}: m${i},`);
1948
- return `${[
1949
- ...header,
1950
- ...imports,
1951
- "const modules: Record<string, RouteModule> = {",
1952
- ...entries,
1953
- "}",
1954
- clientEntryLine,
1955
- stylesLine,
1956
- routeStylesLine,
1957
- "export const manifest = buildManifest(Object.keys(modules), (file) => () => Promise.resolve(modules[file]))",
1958
- ].join("\n")}\n`;
1959
- }
1960
- /**
1961
- * The two file-name conventions that decide what never reaches a browser: a `*.server` module is
1962
- * EMPTIED in the client build, a `*.fn` module is REPLACED with client stubs.
1963
- *
1964
- * Exported because more than the bundlers need them. `nifra dev --bun` cannot transform (Bun's dev
1965
- * bundler takes no plugins) so it must REFUSE instead, and a refusal driven by its own hand-written
1966
- * glob drifts from the transform - which is how `.fn.mts` came to be stubbed by both build pipelines
1967
- * and waved through by the guard that exists to stop it leaking. Anything deciding "is this module
1968
- * server-only" should import the matcher rather than re-encode it.
1969
- */
1970
- export { SERVER_FN_MODULE, SERVER_ONLY_MODULE } from "./internal/server-boundary.js";
1971
58
  //# sourceMappingURL=index.js.map