@nifrajs/web 2.14.1 → 3.2.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 (145) hide show
  1. package/dist/boundary.d.ts +158 -0
  2. package/dist/boundary.d.ts.map +1 -0
  3. package/dist/boundary.js +237 -0
  4. package/dist/boundary.js.map +1 -0
  5. package/dist/build-plan.d.ts +228 -0
  6. package/dist/build-plan.d.ts.map +1 -0
  7. package/dist/build-plan.js +514 -0
  8. package/dist/build-plan.js.map +1 -0
  9. package/dist/build-vite.d.ts +2 -1
  10. package/dist/build-vite.d.ts.map +1 -1
  11. package/dist/build-vite.js +5 -3
  12. package/dist/build-vite.js.map +1 -1
  13. package/dist/build.d.ts +2 -197
  14. package/dist/build.d.ts.map +1 -1
  15. package/dist/build.js +92 -515
  16. package/dist/build.js.map +1 -1
  17. package/dist/chunk-names.d.ts.map +1 -1
  18. package/dist/chunk-names.js +3 -2
  19. package/dist/chunk-names.js.map +1 -1
  20. package/dist/dev-ssr-graph.d.ts.map +1 -1
  21. package/dist/dev-ssr-graph.js +63 -28
  22. package/dist/dev-ssr-graph.js.map +1 -1
  23. package/dist/diagnostic.d.ts.map +1 -1
  24. package/dist/diagnostic.js +9 -2
  25. package/dist/diagnostic.js.map +1 -1
  26. package/dist/fonts-google.d.ts.map +1 -1
  27. package/dist/fonts-google.js +3 -1
  28. package/dist/fonts-google.js.map +1 -1
  29. package/dist/fs.d.ts.map +1 -1
  30. package/dist/fs.js +2 -1
  31. package/dist/fs.js.map +1 -1
  32. package/dist/index.d.ts +16 -589
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +23 -1824
  35. package/dist/index.js.map +1 -1
  36. package/dist/internal/codegen.d.ts +68 -0
  37. package/dist/internal/codegen.d.ts.map +1 -0
  38. package/dist/internal/codegen.js +317 -0
  39. package/dist/internal/codegen.js.map +1 -0
  40. package/dist/internal/fetcher-runtime.d.ts +19 -0
  41. package/dist/internal/fetcher-runtime.d.ts.map +1 -0
  42. package/dist/internal/fetcher-runtime.js +26 -0
  43. package/dist/internal/fetcher-runtime.js.map +1 -0
  44. package/dist/internal/head-merge.d.ts +2 -0
  45. package/dist/internal/head-merge.d.ts.map +1 -1
  46. package/dist/internal/head-merge.js +17 -1
  47. package/dist/internal/head-merge.js.map +1 -1
  48. package/dist/internal/identity-policy.d.ts +51 -0
  49. package/dist/internal/identity-policy.d.ts.map +1 -0
  50. package/dist/internal/identity-policy.js +67 -0
  51. package/dist/internal/identity-policy.js.map +1 -0
  52. package/dist/internal/parity.d.ts +104 -8
  53. package/dist/internal/parity.d.ts.map +1 -1
  54. package/dist/internal/parity.js +472 -56
  55. package/dist/internal/parity.js.map +1 -1
  56. package/dist/internal/query-runtime.d.ts +8 -0
  57. package/dist/internal/query-runtime.d.ts.map +1 -0
  58. package/dist/internal/query-runtime.js +29 -0
  59. package/dist/internal/query-runtime.js.map +1 -0
  60. package/dist/internal/render-document.d.ts +372 -0
  61. package/dist/internal/render-document.d.ts.map +1 -0
  62. package/dist/internal/render-document.js +744 -0
  63. package/dist/internal/render-document.js.map +1 -0
  64. package/dist/internal/runtime-contract.d.ts +48 -0
  65. package/dist/internal/runtime-contract.d.ts.map +1 -0
  66. package/dist/internal/runtime-contract.js +27 -0
  67. package/dist/internal/runtime-contract.js.map +1 -0
  68. package/dist/internal/web-app.d.ts +171 -0
  69. package/dist/internal/web-app.d.ts.map +1 -0
  70. package/dist/internal/web-app.js +844 -0
  71. package/dist/internal/web-app.js.map +1 -0
  72. package/dist/islands.d.ts +50 -2
  73. package/dist/islands.d.ts.map +1 -1
  74. package/dist/islands.js +96 -36
  75. package/dist/islands.js.map +1 -1
  76. package/dist/manifest.d.ts +41 -6
  77. package/dist/manifest.d.ts.map +1 -1
  78. package/dist/manifest.js.map +1 -1
  79. package/dist/module-graph.d.ts.map +1 -1
  80. package/dist/module-graph.js +22 -9
  81. package/dist/module-graph.js.map +1 -1
  82. package/dist/nano.d.ts +125 -0
  83. package/dist/nano.d.ts.map +1 -0
  84. package/dist/nano.js +190 -0
  85. package/dist/nano.js.map +1 -0
  86. package/dist/plugins/css-modules.js +2 -2
  87. package/dist/plugins/css-modules.js.map +1 -1
  88. package/dist/plugins/kit.d.ts +12 -0
  89. package/dist/plugins/kit.d.ts.map +1 -1
  90. package/dist/plugins/kit.js +62 -12
  91. package/dist/plugins/kit.js.map +1 -1
  92. package/dist/plugins/postcss.js +2 -2
  93. package/dist/plugins/postcss.js.map +1 -1
  94. package/dist/plugins/scss.js +2 -2
  95. package/dist/plugins/scss.js.map +1 -1
  96. package/dist/plugins/stylex.d.ts +70 -0
  97. package/dist/plugins/stylex.d.ts.map +1 -0
  98. package/dist/plugins/stylex.js +166 -0
  99. package/dist/plugins/stylex.js.map +1 -0
  100. package/dist/plugins/svg.js +2 -2
  101. package/dist/plugins/svg.js.map +1 -1
  102. package/dist/render-seam.d.ts +5 -0
  103. package/dist/render-seam.d.ts.map +1 -1
  104. package/dist/render-seam.js +10 -0
  105. package/dist/render-seam.js.map +1 -1
  106. package/dist/router.d.ts +11 -1
  107. package/dist/router.d.ts.map +1 -1
  108. package/dist/router.js +254 -47
  109. package/dist/router.js.map +1 -1
  110. package/dist/vite.d.ts.map +1 -1
  111. package/dist/vite.js +34 -16
  112. package/dist/vite.js.map +1 -1
  113. package/package.json +49 -2
  114. package/src/boundary.ts +407 -0
  115. package/src/build-plan.ts +741 -0
  116. package/src/build-vite.ts +6 -7
  117. package/src/build.ts +120 -730
  118. package/src/chunk-names.ts +3 -2
  119. package/src/dev-ssr-graph.ts +63 -28
  120. package/src/diagnostic.ts +14 -2
  121. package/src/fonts-google.ts +3 -1
  122. package/src/fs.ts +2 -1
  123. package/src/index.ts +107 -2553
  124. package/src/internal/codegen.ts +400 -0
  125. package/src/internal/fetcher-runtime.ts +36 -0
  126. package/src/internal/head-merge.ts +19 -1
  127. package/src/internal/identity-policy.ts +94 -0
  128. package/src/internal/parity.ts +603 -71
  129. package/src/internal/query-runtime.ts +31 -0
  130. package/src/internal/render-document.ts +1116 -0
  131. package/src/internal/runtime-contract.ts +54 -0
  132. package/src/internal/web-app.ts +1114 -0
  133. package/src/islands.ts +106 -40
  134. package/src/manifest.ts +50 -3
  135. package/src/module-graph.ts +23 -9
  136. package/src/nano.ts +246 -0
  137. package/src/plugins/css-modules.ts +2 -2
  138. package/src/plugins/kit.ts +65 -12
  139. package/src/plugins/postcss.ts +2 -2
  140. package/src/plugins/scss.ts +2 -2
  141. package/src/plugins/stylex.ts +298 -0
  142. package/src/plugins/svg.ts +2 -2
  143. package/src/render-seam.ts +6 -0
  144. package/src/router.ts +293 -51
  145. package/src/vite.ts +41 -15
package/src/index.ts CHANGED
@@ -8,67 +8,41 @@
8
8
  * of DOM types: it is pure server orchestration + string building.
9
9
  */
10
10
 
11
- import {
12
- type BackendMount,
13
- type BackendMountHandler,
14
- NIFRA_BACKEND_MOUNT,
15
- } from "@nifrajs/core/mount"
16
- import { type ServerOptions, server, type UrlParts, urlPartsOf } from "@nifrajs/core/server"
17
- import {
18
- DEFERRED_ERROR_CODE,
19
- DEFERRED_RUNTIME,
20
- type Deferred,
21
- defer,
22
- MAP_DEFERRED_SOURCE,
23
- ndjsonStream,
24
- prepareDeferred,
25
- } from "./deferred.ts"
26
- import { isDraftEnabled } from "./draft.ts"
27
- import { trustedHeadAttributes } from "./internal/head-attributes.ts"
28
- // Head resolution/merging. Defined in an internal module so `@nifrajs/web/client` can export the same
29
- // two functions to the generated client entry without dragging THIS module (and its server code) into
30
- // the browser graph - see internal/head-merge.ts. Re-exported here so the public API is unchanged.
31
- import { mergeHeads, resolveMeta } from "./internal/head-merge.ts"
32
- import { jsStringLiteral } from "./internal/js-string.ts"
33
- import { EXECUTABLE_SCRIPT_TYPES, INERT_SCRIPT_TYPES } from "./internal/script-types.ts"
34
- import { ISR_REVALIDATE_HEADER, ISR_REVALIDATE_TAGS_HEADER, serializeISRTags } from "./isr.ts"
35
- import { generateLlmsTxt } from "./llms-txt.ts"
36
- import type {
37
- LayoutEntry,
38
- Loader as LayoutLoader,
39
- LinkDescriptor,
40
- LoaderContext,
41
- Manifest,
42
- Meta,
43
- MetaArgs,
44
- MetaDescriptor,
45
- MetaInput,
46
- RouteEntry,
47
- RouteModule,
48
- ScriptDescriptor,
49
- UnsafeScriptDescriptor,
50
- } from "./manifest.ts"
51
- import type { RenderAdapter, RenderProps } from "./render-seam.ts"
52
- import {
53
- ACTION_GLOBAL,
54
- DATA_GLOBAL,
55
- LAYOUT_DATA_GLOBAL,
56
- ROOT_ATTRIBUTE,
57
- ROUTE_GLOBAL,
58
- } from "./render-seam.ts"
59
- import {
60
- createMatcher,
61
- DATA_HEADER,
62
- NAV_FROM_HEADER,
63
- PRERENDERED_GLOBAL,
64
- REDIRECT_HEADER,
65
- RETAIN_HEADER,
66
- REVALIDATE_HEADER,
67
- STATUS_HEADER,
68
- } from "./router.ts"
69
- import { searchOf, searchOfChain } from "./search.ts"
70
-
71
11
  // Draft / preview mode - a signed cookie that flips `ctx.draft` for loaders + bypasses ISR for editors.
12
+ export {
13
+ assertStaticBoundaryImports,
14
+ type Boundary,
15
+ type BoundaryDescriptor,
16
+ type BoundaryError,
17
+ type BoundaryMode,
18
+ type BoundaryRegistration,
19
+ type BoundaryRequestCtx,
20
+ type BoundaryState,
21
+ type BoundaryStates,
22
+ type BoundaryStatus,
23
+ boundaryDescriptors,
24
+ boundaryModeKey,
25
+ type DynamicBoundary,
26
+ type DynamicBoundaryBatch,
27
+ type InterceptBoundary,
28
+ MemoryStaticBoundaryCache,
29
+ type PendingBoundary,
30
+ resolveDynamicBoundaries,
31
+ resolveStaticBoundaries,
32
+ type StaticBoundary,
33
+ type StaticBoundaryCache,
34
+ type StaticBoundaryImportEdge,
35
+ type StaticBoundaryRoot,
36
+ type StaticCtx,
37
+ startDynamicBoundaries,
38
+ } from "./boundary.ts"
39
+ export {
40
+ assertRenderAdapterConformance,
41
+ RenderAdapterConformanceError,
42
+ type RenderAdapterConformanceFixture,
43
+ } from "./conformance.ts"
44
+ // Deferred loader data (`defer()` + the `Deferred<T>` type) - consumed by the adapter's `<Await>`.
45
+ export { type Deferred, defer } from "./deferred.ts"
72
46
  export {
73
47
  DRAFT_COOKIE,
74
48
  type DraftCookieControls,
@@ -88,6 +62,59 @@ export {
88
62
  fontFace,
89
63
  fontPreload,
90
64
  } from "./fonts.ts"
65
+ export {
66
+ type GenerateClientEntryOptions,
67
+ type GenerateRouteSearchTypesOptions,
68
+ type GenerateServerManifestOptions,
69
+ generateClientEntry,
70
+ generateRouteSearchTypes,
71
+ generateServerManifest,
72
+ } from "./internal/codegen.ts"
73
+ // Generated client entries intentionally import the browser router from the client subpath:
74
+ // `import { createClientRouter, createMatcher, mergeHeads, resolveMeta } from "@nifrajs/web/client"`.
75
+ export { mergeHeads, resolveMeta } from "./internal/head-merge.ts"
76
+ export {
77
+ canonical,
78
+ gone,
79
+ jsonLd,
80
+ notFound,
81
+ type OpenGraphInput,
82
+ openGraph,
83
+ type RedirectOptions,
84
+ type RenderAssemblyCache,
85
+ type RenderedPage,
86
+ type RenderPageInput,
87
+ type RenderPageOptions,
88
+ type RevalidateResult,
89
+ redirect,
90
+ renderPage,
91
+ renderPageResult,
92
+ revalidate,
93
+ type StatusPageOptions,
94
+ serializeData,
95
+ statusPage,
96
+ unsafeInlineScript,
97
+ } from "./internal/render-document.ts"
98
+ export {
99
+ DEFAULT_DEV_PORT,
100
+ PRE_HYDRATION_GUARD,
101
+ type ServerOnly,
102
+ } from "./internal/runtime-contract.ts"
103
+ /**
104
+ * The two file-name conventions that decide what never reaches a browser: a `*.server` module is
105
+ * EMPTIED in the client build, a `*.fn` module is REPLACED with client stubs.
106
+ *
107
+ * Exported because more than the bundlers need them. `nifra dev --bun` cannot transform (Bun's dev
108
+ * bundler takes no plugins) so it must REFUSE instead, and a refusal driven by its own hand-written
109
+ * glob drifts from the transform - which is how `.fn.mts` came to be stubbed by both build pipelines
110
+ * and waved through by the guard that exists to stop it leaking. Anything deciding "is this module
111
+ * server-only" should import the matcher rather than re-encode it.
112
+ */
113
+ export { SERVER_FN_MODULE, SERVER_ONLY_MODULE } from "./internal/server-boundary.ts"
114
+ export {
115
+ type CreateWebAppOptions,
116
+ createWebApp,
117
+ } from "./internal/web-app.ts"
91
118
  // ISR (incremental static regeneration): a pluggable cache store + the `withISR` stale-while-revalidate
92
119
  // wrapper for rendered SSR responses.
93
120
  export {
@@ -112,6 +139,13 @@ export {
112
139
  export {
113
140
  type Action,
114
141
  buildManifest,
142
+ type ClientAction,
143
+ type ClientActionArgs,
144
+ type ClientActionResult,
145
+ type ClientLoader,
146
+ type ClientLoaderArgs,
147
+ type ClientRequestBody,
148
+ type ClientRouteHooks,
115
149
  enumerateStaticRoutes,
116
150
  filePathToPattern,
117
151
  filePathToPatterns,
@@ -183,6 +217,19 @@ export {
183
217
  type QueryState,
184
218
  type QueryStatus,
185
219
  } from "./query.ts"
220
+ export {
221
+ ACTION_GLOBAL,
222
+ BOUNDARY_GLOBAL,
223
+ DATA_GLOBAL,
224
+ LAYOUT_DATA_GLOBAL,
225
+ type RenderAdapter,
226
+ type RenderProps,
227
+ ROOT_ATTRIBUTE,
228
+ ROUTE_GLOBAL,
229
+ type SsrModuleLoader,
230
+ setSsrModuleLoader,
231
+ ssrModuleLoader,
232
+ } from "./render-seam.ts"
186
233
  // Agnostic client-side router core (pure + DOM-free) - consumed by per-adapter Router bindings.
187
234
  // `DATA_HEADER` marks a navigation's data-only GET; `createWebApp` answers it with loader JSON.
188
235
  export {
@@ -206,2501 +253,8 @@ export {
206
253
  type Submission,
207
254
  type SubmitOptions,
208
255
  } from "./router.ts"
209
- // Deferred loader data (`defer()` + the `Deferred<T>` type) - consumed by the adapter's `<Await>`.
210
- export { type Deferred, defer, mergeHeads, resolveMeta }
211
-
212
- /** Phantom brand key for {@link ServerOnly}. A unique symbol so the brand can't be forged by a plain
213
- * object literal; `unique symbol` keys never appear in the emitted JS, so the brand is purely
214
- * type-level (zero runtime cost). The property is optional + `never`-typed, so a `ServerOnly<T>`
215
- * stays assignment-compatible with `T` - it documents intent without obstructing real use. */
216
- declare const SERVER_ONLY_BRAND: unique symbol
217
-
218
- /**
219
- * Type-level intent marker for a value that must only exist on the server - a secret, a DB handle, a
220
- * server-only client. `ServerOnly<T>` is structurally `T` (the brand is an optional phantom field, so
221
- * existing code keeps type-checking), but it advertises to readers + the compiler that the value is
222
- * not meant to cross to the browser. It is **purely type-level** and erases at build - it does NOT,
223
- * by itself, keep the value out of the client bundle.
224
- *
225
- * The enforcement is two runtime conventions:
226
- * - add the side-effect import `import "@nifrajs/web/server-only"` at the top of the module - the
227
- * client build ({@link buildClient}) fails loud, with the import chain, if it reaches a browser
228
- * chunk (the poison-import marker);
229
- * - or name the file `*.server.ts` - the `.server` convention empties it in the client build.
230
- *
231
- * Use this brand to express the intent in the types; pair it with one of those runtime markers so a
232
- * leak is caught at build time rather than shipping a secret to the client.
233
- *
234
- * @example
235
- * import "@nifrajs/web/server-only"
236
- * import type { ServerOnly } from "@nifrajs/web"
237
- * export const apiKey: ServerOnly<string> = process.env.SECRET_API_KEY!
238
- */
239
- export type ServerOnly<T> = T & { readonly [SERVER_ONLY_BRAND]?: never }
240
-
241
- export {
242
- assertRenderAdapterConformance,
243
- RenderAdapterConformanceError,
244
- type RenderAdapterConformanceFixture,
245
- } from "./conformance.ts"
246
- export {
247
- ACTION_GLOBAL,
248
- DATA_GLOBAL,
249
- LAYOUT_DATA_GLOBAL,
250
- type RenderAdapter,
251
- type RenderProps,
252
- ROOT_ATTRIBUTE,
253
- ROUTE_GLOBAL,
254
- type SsrModuleLoader,
255
- setSsrModuleLoader,
256
- ssrModuleLoader,
257
- } from "./render-seam.ts"
258
-
259
256
  // The search-derivation primitive: parse a URL query, validate it against a route's `searchSchema`
260
257
  // (fail-closed to defaults), or return the raw parsed query when there is none. Both the server (loader
261
258
  // ctx + `renderPage`) and a client adapter mount call this with the same URL + schema, so the two sides
262
259
  // produce the identical value by construction. An adapter's `useSearch` binding reads its result.
263
260
  export { type SearchOf, searchOf, searchOfChain, serializeSearch } from "./search.ts"
264
-
265
- /**
266
- * Pre-hydration form guard - a tiny inline script flushed in `<head>` (it runs in the window between
267
- * first paint and the island bundle taking over). It neutralizes the one real hydration footgun: a
268
- * JS-only form (a hand-wired `onSubmit` with no native fallback) submitting *natively* before its
269
- * handler is attached, which navigates the browser to a broken `?field=…` GET of the current page.
270
- *
271
- * It blocks ONLY that shape - an effective-GET form whose action targets the current document - and
272
- * only until hydration commits (`data-nifra-hydrated`, set by the client entry). Method-`post` forms
273
- * (progressive enhancement: the native POST hits the route `action`) and GET forms with a real action
274
- * (a search box → `/search`) pass through untouched. Opt out per-form with `data-native`. Static text
275
- * (no interpolation), so it can't carry injected markup. See the Hydration guide.
276
- */
277
- export const PRE_HYDRATION_GUARD =
278
- "(function(){addEventListener('submit',function(e){var f=e.target;" +
279
- "if(!f||f.tagName!=='FORM'||f.hasAttribute('data-native'))return;" +
280
- "if(document.documentElement.hasAttribute('data-nifra-hydrated'))return;" +
281
- "var m=(f.getAttribute('method')||'get').toLowerCase();if(m==='post')return;" +
282
- "var a=f.getAttribute('action');" +
283
- "if(!a||a===''||a==='#'||a===location.pathname||a===location.href)e.preventDefault()" +
284
- "},true)})()"
285
-
286
- /**
287
- * The single default port for the dev server (`@nifrajs/web/dev`, `@nifrajs/web/vite`) **and**
288
- * `nifra start`. Deliberately uncommon: `3000`/`5173`/`8080` collide with whatever else is running
289
- * (Next, Vite, a stray Node API). `4321` rarely is - and being the *same* constant across `nifra dev`
290
- * and `nifra start` means a project's URL doesn't change between commands. Override per-run with
291
- * `--port <n>` or the `PORT` env var. */
292
- export const DEFAULT_DEV_PORT = 4321
293
-
294
- // Shared, stateless - allocated once at module load, not per render/stream.
295
- const TEXT_ENCODER = new TextEncoder()
296
-
297
- type MaybePromise<T> = T | Promise<T>
298
-
299
- // XSS-safe `<script>` JSON escaping in a SINGLE pass: `<`/`>` would break out of the
300
- // script element; U+2028/U+2029 are valid JSON but historically break JS string literals. Built via
301
- // fromCharCode so no raw separator chars live in this source. One regex + one output string replaces
302
- // the prior four sequential `replaceAll` full-string passes.
303
- const LINE_SEP = String.fromCharCode(0x2028)
304
- const PARA_SEP = String.fromCharCode(0x2029)
305
- const SCRIPT_ESCAPE = new RegExp(`[<>${LINE_SEP}${PARA_SEP}]`, "g")
306
- const SCRIPT_ESCAPE_MAP: Readonly<Record<string, string>> = {
307
- "<": "\\u003c",
308
- ">": "\\u003e",
309
- [LINE_SEP]: "\\u2028",
310
- [PARA_SEP]: "\\u2029",
311
- }
312
- const NODE_RESPONSE_BODY = Symbol.for("nifra.response.body")
313
- const RESPONSE_RESULT = Symbol.for("nifra.response.result")
314
-
315
- export interface RenderedPage {
316
- readonly [RESPONSE_RESULT]: true
317
- toResponse(): Response
318
- toNodeBody?(): {
319
- readonly status: number
320
- readonly headers: Readonly<Record<string, string | readonly string[]>> | undefined
321
- readonly body: string | Uint8Array
322
- }
323
- }
324
-
325
- export interface RenderPageOptions {
326
- readonly adapter: RenderAdapter
327
- /** The layout chain to render - outermost layout → page (opaque; the adapter renders it). */
328
- readonly chain: readonly unknown[]
329
- /** The loader output for this request. */
330
- readonly data: unknown
331
- /** An action's data return (POST only) - surfaced to the page as `actionData` + serialized
332
- * for the client so post-POST hydration matches. Omit on GETs. */
333
- readonly actionData?: unknown
334
- /**
335
- * URL of the built client entry (loaded as a module script).
336
- *
337
- * Optional ONLY on a `hydrate: false` page, where there is no client takeover to feed and this value
338
- * reaches no output at all. The union below is what enforces that: omitting it on a hydrating page
339
- * stays a compile error rather than rendering `src=""`.
340
- */
341
- readonly clientEntry?: string
342
- /** Chunk URLs for the **matched** route (its layout chain + own chunk) to `modulepreload` in the
343
- * shell - so the route code downloads in parallel with the entry instead of after it
344
- * (`buildClient`'s per-route map). Empty/omitted ⇒ only the entry is preloaded (unchanged). */
345
- readonly preload?: readonly string[]
346
- /** Stylesheet URLs for the **matched** route (its layout chain + own CSS, from `buildClient`'s
347
- * `BuildManifest.css`) - injected as `<link rel="stylesheet">` in `<head>` so styles arrive with the
348
- * first paint (no FOUC). Rendered even on non-hydrated pages. Empty/omitted ⇒ none (unchanged). */
349
- readonly styles?: readonly string[]
350
- /** SSG: the prerendered-path set, serialized to `window.__NIFRA_PRERENDERED__` so the client fetches
351
- * a static `_data.json` on soft-nav into a prerendered route. Empty/omitted ⇒ not injected. */
352
- readonly prerenderedPaths?: readonly string[]
353
- /** ISR: route freshness in seconds, emitted as the `x-nifra-isr-revalidate` header for a `withISR`
354
- * wrapper to read. Omit ⇒ no header (the wrapper's default TTL applies). */
355
- readonly revalidate?: number
356
- /** ISR invalidation tags emitted as a bounded `x-nifra-isr-tags` header. */
357
- readonly revalidateTags?: readonly string[]
358
- /** Matched route id; written to `window.__NIFRA_ROUTE__` so the client hydrates this chain. */
359
- readonly routeId?: string
360
- /** The matched route's decoded path params - surfaced to the page as `params` (via {@link RenderProps})
361
- * so an adapter's `useParams` is SSR-correct. Omit ⇒ `{}` (a route with no dynamic segments, or an
362
- * error/404 render). */
363
- readonly params?: Readonly<Record<string, string>>
364
- /** The request's `pathname + search` - surfaced as `path` (via {@link RenderProps}) so an adapter's
365
- * `useLocation`/`useSearchParams` render the right URL server-side and hydrate without drift. Omit ⇒
366
- * `""`. */
367
- readonly path?: string
368
- /** The route's validated search (`searchOf(mod.searchSchema, url.search)`, the same value handed to
369
- * the loader as `ctx.search`), surfaced as `search` (via {@link RenderProps}) so an adapter's
370
- * `useSearch` is SSR-correct. Omit ⇒ `{}` (a render with no search context). */
371
- readonly search?: Record<string, unknown>
372
- /** Per-layout loader data, forwarded to the adapter as `RenderProps.layoutData`. Aligned with the
373
- * chain's layout prefix; omitted when no layout in the chain has a loader. */
374
- readonly layoutData?: readonly unknown[]
375
- /** HTTP status for the response (default 200; e.g. 404 for a not-found page). */
376
- readonly status?: number
377
- /** Extra response headers - e.g. the `cache-control` a terminal status page wants. `content-type`
378
- * is ignored (the document is always HTML) and the ISR freshness header is applied after these,
379
- * so neither can be overridden from here. */
380
- readonly headers?: HeadersLike
381
- /** Document title (fallback when `head.title` is unset). */
382
- readonly title?: string
383
- /** Resolved route head - `title` overrides `title` above; `meta`/`link` render as managed
384
- * (`data-nifra`) tags the client updates on navigation.
385
- *
386
- * **Head contract (the layout chain contributes).** `createWebApp` resolves this via
387
- * {@link mergeHeads}: a route's head is its **layout chain's** `meta`/`head` exports merged with the
388
- * page's. A `_layout.tsx` may `export const meta` (or `export function meta(args)`) - its tags land
389
- * on every page below it (the home for `hreflang`, `preconnect`, a section-default `<title>`). The
390
- * merge is **nearest-wins for scalars** (the page's `title` overrides an inner layout's, which
391
- * overrides an outer one; an undefined page title keeps the layout's) and **concatenated for the
392
- * `meta`/`link` arrays** (outermost layout first, page last). `<meta>`/`<link>` attributes pass a
393
- * shared tag-specific allowlist (including inert `data-*` metadata) and values are escaped. */
394
- readonly head?: Meta
395
- /** Id of the container wrapping the app markup (default `"root"`). A non-default id also gets
396
- * {@link ROOT_ATTRIBUTE}, which is how the generated client entry finds the container to hydrate -
397
- * the entry is built once and cannot know what a given render chose. */
398
- readonly rootId?: string
399
- /** When `false`, emit a complete but **non-hydrated** document - no client entry script, data
400
- * globals, or modulepreloads. Used for server-rendered `_error` pages: a terminal state that needs no
401
- * client takeover, and it sidesteps an SSR/hydrate mismatch (the server rendered the boundary, not
402
- * the page the client manifest maps this route id to). Default `true`. */
403
- readonly hydrate?: boolean
404
- /** Island client bundles (`@nifrajs/web/islands`) to load as `<script type="module">` in the document
405
- * tail - emitted **regardless of `hydrate`**, so a static (`hydrate: false`) page can still mount
406
- * no-framework islands. URLs are attribute-escaped. Empty/omitted ⇒ none (unchanged output). */
407
- readonly islandScripts?: readonly string[]
408
- /** CSP nonce applied to every framework-owned executable script in this document. */
409
- readonly nonce?: string
410
- /**
411
- * Advanced: a per-route slot the renderer fills with the request-invariant document pieces (shell
412
- * prefix/suffix, tail statics) on the first render and reuses afterwards, skipping their re-assembly.
413
- *
414
- * Only pass a cache when every shell-shaping input is IDENTICAL across the requests sharing it:
415
- * same `head` content (a static meta chain - never a `meta(data)` function), `title`, `styles`,
416
- * `preload`, `islandScripts`, `clientEntry`, `rootId`, `hydrate`, and `prerenderedPaths`. Per-request
417
- * values (`data`, `params`, `search`, `actionData`, `layoutData`, deferred state) are always assembled
418
- * fresh and safe. A per-request `nonce` disables the cache automatically. `createWebApp` wires this
419
- * per route, gated on the route + layout metas being static.
420
- */
421
- readonly assemblyCache?: RenderAssemblyCache
422
- }
423
-
424
- /** The mutable per-route slot {@link RenderPageOptions.assemblyCache} fills. Opaque - create as `{}`. */
425
- export interface RenderAssemblyCache {
426
- /** Shell up to (not including) the deferred-runtime insertion point. */
427
- shellPre?: string
428
- /** Shell from after the deferred-runtime insertion point through the open `#root` container. */
429
- shellPost?: string
430
- /** Tail opener: the inline script open tag + the route-id global (before the action global). */
431
- tailPre?: string
432
- /** Tail mid: the prerendered-paths global (between the action and layout-data globals). */
433
- tailMid?: string
434
- /** Tail data prefix: the `window.<data global>=` assignment head. */
435
- tailData?: string
436
- /** Tail from after the serialized data through `</html>`. */
437
- tailPost?: string
438
- }
439
-
440
- /**
441
- * `renderPage` input. A hydrating page (the default) must supply `clientEntry`, because the document
442
- * loads it as a module script; a `hydrate: false` page may omit it, because nothing in the emitted
443
- * document references it. Expressed as a union so the compiler enforces the pairing rather than the
444
- * renderer discovering an empty `src` at runtime.
445
- */
446
- export type RenderPageInput = RenderPageOptions &
447
- ({ readonly hydrate?: true; readonly clientEntry: string } | { readonly hydrate: false })
448
-
449
- /**
450
- * Server: render a full HTML document for a page - the adapter's hydration head + the SSR
451
- * markup (**streamed**) + the serialized loader data + the client module - as a `Response`.
452
- * The shell (`<head>` + the open container) flushes first, the adapter's app stream follows,
453
- * then the tail (data globals + client entry). Pure Web Standards, so it returns straight from
454
- * a nifra route handler and streams on any fetch runtime (Bun/Node/Deno/Workers).
455
- */
456
- export function renderPage(options: RenderPageInput): MaybePromise<Response> {
457
- const page = renderPageResult(options)
458
- return page instanceof Promise ? page.then((p) => p.toResponse()) : page.toResponse()
459
- }
460
-
461
- export function renderPageResult(options: RenderPageInput): MaybePromise<RenderedPage> {
462
- const {
463
- adapter,
464
- chain,
465
- data,
466
- actionData,
467
- clientEntry,
468
- preload = [],
469
- styles = [],
470
- prerenderedPaths = [],
471
- revalidate,
472
- revalidateTags = [],
473
- routeId,
474
- status = 200,
475
- title = "nifra",
476
- head,
477
- rootId = "root",
478
- hydrate = true,
479
- islandScripts = [],
480
- nonce,
481
- headers: extraHeaders,
482
- } = options
483
- if (nonce !== undefined && nonce.trim() === "") {
484
- throw new TypeError("[nifra/web] renderPage nonce must be non-empty when provided")
485
- }
486
- const nonceAttr = nonce === undefined ? "" : ` nonce="${escapeAttr(nonce)}"`
487
- const route = routeId === undefined ? "" : `window.${ROUTE_GLOBAL}=${serializeData(routeId)};`
488
- // The SSG prerendered-path set (when an app declares it) - the client reads it to fetch a static
489
- // `_data.json` on soft-nav into a prerendered route instead of hitting the worker. Empty ⇒ omitted.
490
- const prerendered =
491
- prerenderedPaths.length === 0
492
- ? ""
493
- : `window.${PRERENDERED_GLOBAL}=${serializeData(prerenderedPaths)};`
494
- // Split deferred values: the component sees markers (id + promise) to `<Await>`; the serialized
495
- // data carries `{__nifra_deferred: id}` placeholders (promises don't serialize). `actionData` may
496
- // also `defer()` - split it too, continuing the id space so a single registry settles both. The
497
- // inline registry runtime is emitted only when something defers, so non-deferred output is unchanged.
498
- const { forComponent, forClient, deferred } = prepareDeferred(data)
499
- // Each layout's data is split in turn, each continuing the id space, so a `defer()` in a layout
500
- // settles through the SAME registry as the page's rather than colliding on ids.
501
- const layoutSplits: Array<ReturnType<typeof prepareDeferred>> = []
502
- if (options.layoutData !== undefined) {
503
- let offset = deferred.length
504
- for (const entry of options.layoutData) {
505
- const split = prepareDeferred(entry, offset)
506
- offset += split.deferred.length
507
- layoutSplits.push(split)
508
- }
509
- }
510
- const layoutDeferred = layoutSplits.flatMap((split) => split.deferred)
511
- const actionSplit =
512
- actionData === undefined
513
- ? undefined
514
- : prepareDeferred(actionData, deferred.length + layoutDeferred.length)
515
- // On the common page-only path (no layout loader, no action) reuse `deferred` directly instead of
516
- // allocating a fresh spread array every request.
517
- const allDeferred =
518
- layoutDeferred.length === 0 && actionSplit === undefined
519
- ? deferred
520
- : [...deferred, ...layoutDeferred, ...(actionSplit ? actionSplit.deferred : [])]
521
- // Omitted entirely when no layout has a loader - a page-only app emits exactly what it did before.
522
- const layoutTail =
523
- options.layoutData === undefined
524
- ? ""
525
- : `window.${LAYOUT_DATA_GLOBAL}=${serializeData(layoutSplits.map((split) => split.forClient))};`
526
-
527
- // Only emit the action global when an action actually ran, so plain GET output is unchanged.
528
- const action =
529
- actionSplit === undefined
530
- ? ""
531
- : `window.${ACTION_GLOBAL}=${serializeData(actionSplit.forClient)};`
532
- const deferredRuntime =
533
- allDeferred.length > 0 ? `<script${nonceAttr}>${DEFERRED_RUNTIME}</script>` : ""
534
- // The regex only injects the CSP nonce into the (constant) hydration head; with no nonce it's a
535
- // no-op that still scans the whole script every request. Skip it on the common no-nonce path.
536
- // The request-invariant document pieces. With a caller-supplied per-route cache (and no per-request
537
- // nonce, which would bake into them) they're built once and reused; the per-request seams - the
538
- // deferred runtime in the shell, the action/layout-data globals and the serialized loader data in
539
- // the tail - are always assembled fresh. Byte-identical to building the whole document inline.
540
- const slot: RenderAssemblyCache =
541
- nonce === undefined && options.assemblyCache !== undefined ? options.assemblyCache : {}
542
- if (slot.shellPre === undefined) {
543
- // Matched-route chunk preloads, concatenated directly. De-duped against the entry, which is
544
- // preloaded separately below.
545
- let preloadLinks = ""
546
- for (const url of preload) {
547
- if (url !== clientEntry)
548
- preloadLinks += `<link rel="modulepreload" href="${escapeAttr(url)}">`
549
- }
550
- // The matched route's stylesheets - `<link rel="stylesheet">` in `<head>` so CSS arrives with the
551
- // first paint (no FOUC). Render-blocking by design, and emitted regardless of `hydrate` (a static
552
- // or `_error` page still wants its styles). In dev (Vite) CSS is injected client-side instead.
553
- let styleLinks = ""
554
- for (const url of styles) styleLinks += `<link rel="stylesheet" href="${escapeAttr(url)}">`
555
- // Island bundles are referenced only by a `<script type="module">` at the END of `<body>`, so the
556
- // browser doesn't discover them until the whole page is parsed. `modulepreload` them in `<head>`
557
- // so the fetch starts immediately, in parallel with parsing - regardless of `hydrate`.
558
- let islandPreloads = ""
559
- for (const src of islandScripts)
560
- islandPreloads += `<link rel="modulepreload" href="${escapeAttr(src)}">`
561
- // Runs in the first-paint→hydration window to swallow a JS-only form's broken native submit. Only
562
- // on a hydrating page (a static/_error page has no client handlers, so no footgun).
563
- const hydrationGuard = hydrate ? `<script${nonceAttr}>${PRE_HYDRATION_GUARD}</script>` : ""
564
- // `<html>` attributes. `lang` defaults to `"en"`; `dir` is omitted entirely when unset, which IS
565
- // HTML's `ltr` default. Both attribute-escaped. `client.ts`'s `applyHead` mirrors this exact
566
- // defaulting on soft-nav, so a hard load and a client navigation produce the same `<html>`.
567
- const htmlAttrs = ` lang="${escapeAttr(head?.lang ?? "en")}"${head?.dir === undefined ? "" : ` dir="${escapeAttr(head.dir)}"`}`
568
- // Marks the container for the client entry when the id is not the one the entry falls back to.
569
- const rootMarker = rootId === "root" ? "" : ` ${ROOT_ATTRIBUTE}`
570
- // A non-hydrated page omits the adapter's hydration bootstrap entirely (Solid's `_$HY` registry
571
- // script, etc.) - there is no client takeover to feed, so it's dead bytes on a static document.
572
- // The nonce rewrite only runs when a nonce is set; with none it was a whole-string no-op scan.
573
- const rawHydrationHead = hydrate ? adapter.hydrationHead(nonce) : ""
574
- const hydrationHead =
575
- nonce === undefined
576
- ? rawHydrationHead
577
- : rawHydrationHead.replace(/<script(?![^>]*\bnonce=)(?=[\s>])/g, `<script${nonceAttr}`)
578
- // Shell up to the deferred-runtime seam: on a hydrating page that seam sits after the entry +
579
- // route-chunk preloads; a non-hydrating page has no runtime insertion at all.
580
- const entryPreloads = hydrate
581
- ? `<link rel="modulepreload" href="${escapeAttr(clientEntry ?? "")}">${preloadLinks}`
582
- : ""
583
- 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}`
584
- slot.shellPost = `${islandPreloads}${hydrationHead}</head><body><div id="${escapeAttr(rootId)}"${rootMarker}>`
585
- // Island bundles load regardless of `hydrate` - a static page (hydrate:false) ships no framework
586
- // client but can still mount no-framework islands (`@nifrajs/web/islands`).
587
- let islandTags = ""
588
- for (const src of islandScripts)
589
- islandTags += `<script type="module" src="${escapeAttr(src)}"${nonceAttr}></script>`
590
- if (hydrate) {
591
- slot.tailPre = `<script${nonceAttr}>${route}`
592
- slot.tailMid = prerendered
593
- slot.tailData = `window.${DATA_GLOBAL}=`
594
- slot.tailPost = `</script><script type="module" src="${escapeAttr(clientEntry ?? "")}"${nonceAttr}></script>${islandTags}</body></html>`
595
- } else {
596
- slot.tailPre = ""
597
- slot.tailMid = ""
598
- slot.tailData = ""
599
- slot.tailPost = `${islandTags}</body></html>`
600
- }
601
- }
602
- // The deferred runtime rides only on a hydrating page (a static page has no client takeover), and
603
- // only when something actually deferred - matching the pre-cache emission exactly.
604
- const runtimeSeam = hydrate && allDeferred.length > 0 ? deferredRuntime : ""
605
- const shellHtml = `${slot.shellPre}${runtimeSeam}${slot.shellPost}`
606
- // Closes the hydration container; deferred resolve scripts go AFTER it (outside `#root`) so they
607
- // aren't part of the adapter's hydrated tree (an inline script inside it breaks hydration).
608
- const closeRootHtml = "</div>"
609
- // Tail - the loader-data globals + the client module. Module scripts defer (run after parse), so
610
- // the data global + every streamed deferred resolution are set before the entry hydrates.
611
- const tailHtml = hydrate
612
- ? `${slot.tailPre}${action}${slot.tailMid}${layoutTail}${slot.tailData}${serializeData(forClient)}${slot.tailPost}`
613
- : (slot.tailPost as string)
614
- const headers: Record<string, string> = { "content-type": "text/html; charset=utf-8" }
615
- // Caller-supplied headers (a terminal status page's `cache-control`, say). Applied before the
616
- // framework's own below, so `content-type` and the ISR channel stay authoritative - a caller must
617
- // not be able to mislabel the document or forge the freshness header by passing them here.
618
- if (extraHeaders !== undefined) {
619
- for (const [name, value] of new Headers(extraHeaders)) {
620
- if (name !== "content-type") headers[name] = value
621
- }
622
- }
623
- // ISR: advertise the route's freshness so a `withISR` wrapper can set this page's cache TTL. A
624
- // dedicated header (not the action-revalidation `x-nifra-revalidate`) so the TTL channel never aliases
625
- // the client's path-list channel.
626
- if (revalidate !== undefined) headers[ISR_REVALIDATE_HEADER] = String(revalidate)
627
- const serializedTags = serializeISRTags(revalidateTags)
628
- if (serializedTags !== undefined) headers[ISR_REVALIDATE_TAGS_HEADER] = serializedTags
629
- const renderProps: RenderProps = {
630
- data: forComponent,
631
- actionData: actionSplit?.forComponent,
632
- // `params`/`path` thread the matched route + URL to the adapter's `useParams`/`useLocation` so they
633
- // render SSR-correct. Spread only when supplied (exactOptionalPropertyTypes) - an adapter with no
634
- // router bindings simply never reads them.
635
- ...(options.params !== undefined ? { params: options.params } : {}),
636
- ...(options.path !== undefined ? { path: options.path } : {}),
637
- // Same rule for `search`: the validated query the adapter's `useSearch` reads, spread only when the
638
- // caller supplied it (a non-router render never has it).
639
- ...(options.search !== undefined ? { search: options.search } : {}),
640
- // Spread only when present, so a page-only render produces exactly the props it did before.
641
- ...(options.layoutData !== undefined
642
- ? { layoutData: layoutSplits.map((split) => split.forComponent) }
643
- : {}),
644
- }
645
-
646
- // Fast path: nothing `defer()`s and the adapter can render synchronously to a string → buffer the
647
- // whole document in one pass. Progressive streaming only benefits pages with deferred boundaries
648
- // (those take the streaming path below); for a plain page the streaming pipeline + the framework's
649
- // streaming renderer are pure overhead vs a single sync render + concat. A buffered string body also
650
- // gets an automatic Content-Length. A render throw surfaces here exactly as the streaming path's
651
- // shell-readiness `await` does, so the `_error` boundary still maps it to a status.
652
- if (allDeferred.length === 0 && adapter.renderToString !== undefined) {
653
- const out = adapter.renderToString(chain, renderProps)
654
- return typeof out === "string"
655
- ? new BufferedRenderedPage(shellHtml + out + closeRootHtml + tailHtml, status, headers)
656
- : out.then(
657
- (bodyHtml) =>
658
- new BufferedRenderedPage(
659
- shellHtml + bodyHtml + closeRootHtml + tailHtml,
660
- status,
661
- headers,
662
- ),
663
- )
664
- }
665
-
666
- return renderStreamedPage(
667
- adapter,
668
- chain,
669
- renderProps,
670
- shellHtml,
671
- closeRootHtml,
672
- allDeferred,
673
- tailHtml,
674
- status,
675
- headers,
676
- nonceAttr,
677
- ).then((response) => new ResponseRenderedPage(response))
678
- }
679
-
680
- async function renderStreamedPage(
681
- adapter: RenderAdapter,
682
- chain: readonly unknown[],
683
- renderProps: RenderProps,
684
- shellHtml: string,
685
- closeRootHtml: string,
686
- allDeferred: ReadonlyArray<{ readonly id: number; readonly promise: Promise<unknown> }>,
687
- tailHtml: string,
688
- status: number,
689
- headers: Record<string, string>,
690
- nonceAttr: string,
691
- ): Promise<Response> {
692
- // Streaming path - required for `defer()` (progressive `<Await>` resolution) and used by any adapter
693
- // that doesn't implement `renderToString`. Awaiting `renderToStream` resolves on shell-readiness
694
- // (React: on-shell-ready; Solid: synchronously), so a shell-render throw surfaces before any byte is
695
- // sent. A *mid*-stream failure errors the body instead.
696
- const enc = TEXT_ENCODER
697
- const shell = enc.encode(shellHtml)
698
- const closeRoot = enc.encode(closeRootHtml)
699
- const tail = enc.encode(tailHtml)
700
- const appStream = await adapter.renderToStream(chain, renderProps)
701
- const body = streamDocument(shell, appStream, closeRoot, allDeferred, tail, enc, nonceAttr)
702
- return new Response(body, { status, headers })
703
- }
704
-
705
- class BufferedRenderedPage implements RenderedPage {
706
- readonly [RESPONSE_RESULT] = true
707
- private readonly body: string
708
- private readonly status: number
709
- private readonly headers: Readonly<Record<string, string>>
710
-
711
- constructor(body: string, status: number, headers: Readonly<Record<string, string>>) {
712
- this.body = body
713
- this.status = status
714
- this.headers = headers
715
- }
716
-
717
- toResponse(): Response {
718
- return htmlResponse(this.body, { status: this.status, headers: this.headers })
719
- }
720
-
721
- toNodeBody(): {
722
- readonly status: number
723
- readonly headers: Readonly<Record<string, string | readonly string[]>>
724
- readonly body: string
725
- } {
726
- return { status: this.status, headers: this.headers, body: this.body }
727
- }
728
- }
729
-
730
- class ResponseRenderedPage implements RenderedPage {
731
- readonly [RESPONSE_RESULT] = true
732
- private readonly response: Response
733
-
734
- constructor(response: Response) {
735
- this.response = response
736
- }
737
-
738
- toResponse(): Response {
739
- return this.response
740
- }
741
- }
742
-
743
- function htmlResponse(body: string, init: ResponseInit): Response {
744
- const response = new Response(body, init)
745
- // @nifrajs/node can write buffered HTML straight to ServerResponse with `end(body)`, avoiding a Web
746
- // Response stream drain on Node. Non-enumerable + Symbol.for keeps this invisible to Web runtimes and
747
- // cross-package without adding a runtime dependency from @nifrajs/node to @nifrajs/web.
748
- Object.defineProperty(response, NODE_RESPONSE_BODY, { value: body })
749
- return response
750
- }
751
-
752
- /**
753
- * Assemble the document stream: `shell` → the app `stream` (forwarded chunk-by-chunk, so a streaming
754
- * renderer's progressive flushing is preserved) → `closeRoot` → one `__nifraResolve`/`__nifraReject`
755
- * script per deferred value (emitted once its promise settles - by now the app stream has awaited
756
- * the same Suspense boundaries - and placed OUTSIDE `#root`) → `tail`. A mid-stream app error errors
757
- * the result (the body breaks) rather than silently truncating a 200.
758
- */
759
- function streamDocument(
760
- shell: Uint8Array,
761
- stream: ReadableStream<Uint8Array>,
762
- closeRoot: Uint8Array,
763
- deferred: ReadonlyArray<{ readonly id: number; readonly promise: Promise<unknown> }>,
764
- tail: Uint8Array,
765
- enc: TextEncoder,
766
- nonceAttr: string,
767
- ): ReadableStream<Uint8Array> {
768
- return new ReadableStream({
769
- async start(controller) {
770
- const reader = stream.getReader()
771
- try {
772
- controller.enqueue(shell)
773
- for (;;) {
774
- const { done, value } = await reader.read()
775
- if (done) break
776
- controller.enqueue(value)
777
- }
778
- controller.enqueue(closeRoot)
779
- // Stream each resolution as ITS OWN promise settles - NOT in array order. A slow
780
- // defer() must not block a faster one; each script self-addresses by id, so order is irrelevant.
781
- await Promise.all(
782
- deferred.map(async (d) => {
783
- try {
784
- const value = serializeData(await d.promise)
785
- controller.enqueue(
786
- enc.encode(`<script${nonceAttr}>window.__nifraResolve(${d.id},${value})</script>`),
787
- )
788
- } catch (err) {
789
- // A rejected deferred streams __nifraReject (the client `<Await>` surfaces it) - it must
790
- // not break the whole body. Redact: stream a stable opaque code, never the raw error
791
- // text; log the real reason server-side.
792
- console.error("[nifra/web] deferred value rejected:", err)
793
- controller.enqueue(
794
- enc.encode(
795
- `<script${nonceAttr}>window.__nifraReject(${d.id},${serializeData(DEFERRED_ERROR_CODE)})</script>`,
796
- ),
797
- )
798
- }
799
- }),
800
- )
801
- controller.enqueue(tail)
802
- controller.close()
803
- } catch (err) {
804
- controller.error(err)
805
- } finally {
806
- reader.releaseLock()
807
- }
808
- },
809
- })
810
- }
811
-
812
- /** Options for {@link redirect}. */
813
- export interface RedirectOptions {
814
- /** HTTP status (default 303 See Other; pass 307/308 to preserve the method). */
815
- readonly status?: number
816
- /** Allow an off-origin / absolute destination. Off by default: only a same-origin path (a single
817
- * leading `/`) is permitted, so an action can't be turned into an open redirect by passing
818
- * attacker-controlled input straight through. Set `true` for a deliberate external redirect. */
819
- readonly external?: boolean
820
- }
821
-
822
- /** A same-origin destination is an absolute path: one leading `/`, but NOT `//` (protocol-relative →
823
- * another origin). Everything else (absolute URL with a scheme, `//host`, `javascript:`, a bare
824
- * relative `foo`) is treated as off-origin and requires `external: true`. */
825
- function isSameOriginPath(location: string): boolean {
826
- return location.startsWith("/") && !location.startsWith("//")
827
- }
828
-
829
- /**
830
- * Build a redirect `Response` - return it from a route `action` for the Post/Redirect/Get
831
- * pattern (POST mutates, 303 sends the browser to a fresh GET, so a reload doesn't re-submit).
832
- * Defaults to 303 (See Other); pass `{ status: 307 }` or `{ status: 308 }` to preserve the method.
833
- *
834
- * **Secure by default:** `location` must be a same-origin path (begins with `/`, not `//`). An
835
- * off-origin/absolute destination throws unless you pass `{ external: true }` - this closes the
836
- * open-redirect footgun of `return redirect(formData.get("next"))` on the no-JS (native-form) path,
837
- * which returns the action's `Response` verbatim.
838
- *
839
- * @param options redirect status and whether an off-origin destination is intentional.
840
- */
841
- export function redirect(location: string, options: RedirectOptions = {}): Response {
842
- if (options.external !== true && !isSameOriginPath(location)) {
843
- throw new Error(
844
- `[nifra/web] redirect(${JSON.stringify(location)}) is not a same-origin path. Use a path beginning with "/" (not "//"), or redirect(location, { external: true }) for a deliberate off-origin redirect. This guards against open redirects from unvalidated input.`,
845
- )
846
- }
847
- // Reject CR/LF in the Location explicitly - defense-in-depth (response splitting / header
848
- // injection). Spec-correct runtimes' Headers setter throws on CR/LF, but `external: true` lets
849
- // unvalidated input reach this sink, so we don't rely on the runtime. Same posture as
850
- // serializeCookie / the SSE frame formatter, which strip CRLF at their sinks.
851
- if (/[\r\n]/.test(location)) {
852
- throw new Error(
853
- `[nifra/web] redirect location contains a CR/LF character - refusing to emit a header-injecting redirect.`,
854
- )
855
- }
856
- return new Response(null, { status: options.status ?? 303, headers: { location } })
857
- }
858
-
859
- /**
860
- * Brand marking a `Response` as a **terminal-status signal** rather than a response to serve verbatim.
861
- *
862
- * A loader that throws a bare `Response` has always been passed straight through - that is how
863
- * `throw redirect(...)` works, and apps rely on it. So "render the `_404` boundary at 404" cannot be
864
- * expressed by throwing a plain `Response`: the framework would have no way to tell it apart from a
865
- * hand-rolled body the app wants served exactly as written. The brand is that distinction, and
866
- * checking it *before* the pass-through is what keeps every existing throw working unchanged.
867
- *
868
- * `Symbol.for` matches `RESPONSE_RESULT` above: a registry symbol survives two copies of this module,
869
- * which a `unique symbol` would not - and a duplicate-install turning a 404 into a raw 404 body would
870
- * be a maddening bug to trace.
871
- */
872
- /** Derived from the `Headers` constructor rather than the DOM lib's `HeadersInit`: `@nifrajs/web`
873
- * is consumed from DOM-free programs (the root tsconfig runs `types: ["bun"]`), and naming the DOM
874
- * type here would break their build. Same workaround as `SSEInit.headers` in core. */
875
- type HeadersLike = ConstructorParameters<typeof Headers>[0]
876
-
877
- /**
878
- * The signatures a **duplicate module instance** produces during SSR, across engines.
879
- *
880
- * Two copies of React (or of `@nifrajs/core`) at the SAME version still fail, because module identity
881
- * is path-based: hooks read a dispatcher off the copy that rendered, and the component imported the
882
- * other one. The error that surfaces names a React internal, so it reads as a React bug and the actual
883
- * cause - two directories - is a long inference away. Naming the cause at the point of failure is the
884
- * difference between that and a five-second read.
885
- */
886
- const DUPLICATE_INSTANCE_SIGNATURES: readonly RegExp[] = [
887
- /resolveDispatcher\(\)/,
888
- /Invalid hook call/,
889
- /Cannot read propert(?:y|ies) of null \(reading '(?:use[A-Z]\w*)'\)/,
890
- /null is not an object \(evaluating '.*\.use[A-Z]\w*'\)/,
891
- ]
892
-
893
- /**
894
- * Append the likely cause to an SSR error that carries a duplicate-instance signature.
895
- *
896
- * Deliberately does NOT claim the resolved paths: `@nifrajs/web` is framework-agnostic and does not
897
- * depend on React, so it cannot resolve the copies without guessing. It names the condition and the
898
- * command that reports the paths, which is the actionable part. Returns the error untouched when the
899
- * signature does not match, so an ordinary render error reads exactly as before.
900
- */
901
- function withDuplicateInstanceHint(err: unknown): unknown {
902
- if (!(err instanceof Error)) return err
903
- if (!DUPLICATE_INSTANCE_SIGNATURES.some((rx) => rx.test(err.message))) return err
904
- const augmented = new Error(
905
- `${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.`,
906
- { cause: err },
907
- )
908
- augmented.name = err.name
909
- // `stack` is optional under exactOptionalPropertyTypes; assigning `undefined` would replace a real
910
- // stack with nothing on engines that always populate it.
911
- if (err.stack !== undefined) augmented.stack = err.stack
912
- return augmented
913
- }
914
-
915
- /**
916
- * An action's `Response` passes straight through - except a redirect on a client-submit data
917
- * request: fetch would follow the 3xx into HTML the client can't use, so the redirect rides the
918
- * X-Nifra-Redirect header on a 204 and the client navigates. One conversion shared by the
919
- * returned- and thrown-Response paths, so `return redirect()` and `throw redirect()` agree.
920
- */
921
- function actionResponse(response: Response, isDataRequest: boolean): Response {
922
- if (isDataRequest && response.status >= 300 && response.status < 400) {
923
- const location = response.headers.get("location") ?? "/"
924
- return new Response(null, { status: 204, headers: { [REDIRECT_HEADER]: location } })
925
- }
926
- return response
927
- }
928
-
929
- /** A loaded layout module. `loader`/`gate` are the layout-loader surface; `meta` predates it. */
930
- type LoadedLayoutModules = ReadonlyArray<{
931
- default: unknown
932
- meta?: MetaInput
933
- loader?: LayoutLoader
934
- action?: unknown
935
- gate?: boolean
936
- // A layout may declare its own `searchSchema`; the route's effective search merges the layout chain's
937
- // schemas with the page's (page-wins). Present on the raw module already - typed here so it is readable.
938
- searchSchema?: RouteModule["searchSchema"]
939
- }>
940
-
941
- /**
942
- * Narrow the route's params to the ones a layout owns.
943
- *
944
- * A layout wraps a URL prefix, so anything deeper belongs to a route beneath it. Handing it the full
945
- * set would let a layout read a param it does not own - which reads fine until the layout is reused
946
- * under a route that has no such param and the value silently becomes `undefined`.
947
- */
948
- function scopeParams(
949
- params: Record<string, string>,
950
- owned: readonly string[] | undefined,
951
- ): Record<string, string> {
952
- if (owned === undefined) return params // hand-built manifest with no scope info: unchanged behaviour
953
- if (owned.length === 0) return EMPTY_LAYOUT_PARAMS
954
- const scoped: Record<string, string> = {}
955
- for (const name of owned) {
956
- const value = params[name]
957
- if (value !== undefined) scoped[name] = value
958
- }
959
- return scoped
960
- }
961
-
962
- const EMPTY_LAYOUT_PARAMS: Record<string, string> = Object.freeze({})
963
-
964
- const EMPTY_RETAIN: ReadonlySet<number> = new Set<number>()
965
-
966
- /**
967
- * Marks an error as coming from a LAYOUT loader, carrying that layout's id.
968
- *
969
- * The boundary that catches it must be at or above the failing layout's own segment. The route's
970
- * innermost `_error` may live BELOW the layout that failed, and rendering there would wrap the
971
- * boundary in a layout whose data never arrived - so the page would render inside a component that
972
- * threw. A registry symbol, matching the other cross-module brands here.
973
- */
974
- const LAYOUT_ERROR_ID = Symbol.for("nifra.web.layout-error-id")
975
-
976
- const tagLayoutError = (err: unknown, layoutId: string): unknown => {
977
- if (typeof err === "object" && err !== null && !(LAYOUT_ERROR_ID in err)) {
978
- Object.defineProperty(err, LAYOUT_ERROR_ID, { value: layoutId, enumerable: false })
979
- }
980
- return err
981
- }
982
-
983
- const layoutErrorId = (err: unknown): string | undefined =>
984
- typeof err === "object" && err !== null
985
- ? ((err as Record<symbol, unknown>)[LAYOUT_ERROR_ID] as string | undefined)
986
- : undefined
987
-
988
- const STATUS_SIGNAL = Symbol.for("nifra.web.status-signal")
989
-
990
- /** Reason phrases for the plain-text fallback, used only when the app authored no `_<status>` and no
991
- * `_404` page. Deliberately not exhaustive - anything unlisted falls back to "Error", which is more
992
- * useful than shipping a table of every RFC status for a body almost nobody will see. */
993
- const STATUS_TEXT: Readonly<Record<number, string>> = {
994
- 400: "Bad Request",
995
- 401: "Unauthorized",
996
- 402: "Payment Required",
997
- 403: "Forbidden",
998
- 404: "Not Found",
999
- 410: "Gone",
1000
- 451: "Unavailable For Legal Reasons",
1001
- 500: "Internal Server Error",
1002
- }
1003
-
1004
- interface StatusSignal extends Response {
1005
- readonly [STATUS_SIGNAL]: { readonly status: number; readonly headers?: HeadersLike }
1006
- }
1007
-
1008
- function isStatusSignal(value: unknown): value is StatusSignal {
1009
- return value instanceof Response && STATUS_SIGNAL in value
1010
- }
1011
-
1012
- function statusSignal(status: number, options: StatusPageOptions): never {
1013
- if (!Number.isInteger(status) || status < 400 || status > 599) {
1014
- throw new Error(
1015
- `[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.`,
1016
- )
1017
- }
1018
- const response = new Response(null, { status })
1019
- // Non-enumerable so the brand never lands in a structured clone or a JSON log of the response.
1020
- Object.defineProperty(response, STATUS_SIGNAL, {
1021
- value: { status, ...(options.headers !== undefined ? { headers: options.headers } : {}) },
1022
- enumerable: false,
1023
- })
1024
- throw response
1025
- }
1026
-
1027
- /** Options shared by {@link notFound}, {@link gone}, and {@link statusPage}. */
1028
- export interface StatusPageOptions {
1029
- /**
1030
- * Extra headers for the rendered response - `cache-control` above all.
1031
- *
1032
- * The defaults differ by status for a reason: a 404 may be a race with publication, so it wants a
1033
- * short TTL, while a 410 is a promise that the URL is permanently gone and can be cached hard.
1034
- * Getting this wrong is the difference between a crawler dropping a dead URL and re-fetching it
1035
- * for weeks.
1036
- */
1037
- readonly headers?: HeadersLike
1038
- }
1039
-
1040
- /**
1041
- * Render the nearest `_404` page at status **404**. `throw` it from a loader when the record does not
1042
- * exist.
1043
- *
1044
- * This is the fix for the soft 404: a matched route whose loader finds nothing has otherwise no way to
1045
- * answer 404, so the path of least resistance is to return empty data and render "not found" inside a
1046
- * **200**. That looks correct in a browser and is invisible in review, which is why it ships and stays
1047
- * shipped - while search engines penalise it and keep the dead URL indexed.
1048
- *
1049
- * Returns `never`: these throw, so a loader narrows without a redundant `return`, and the type states
1050
- * the thing the "loaders `throw` redirect, actions `return` it" rule already trips people on.
1051
- */
1052
- export function notFound(options: StatusPageOptions = {}): never {
1053
- return statusSignal(404, options)
1054
- }
1055
-
1056
- /**
1057
- * Render a terminal page at status **410 Gone**. `throw` it from a loader for a record that existed and
1058
- * was deliberately removed - a withdrawn listing, a deleted post.
1059
- *
1060
- * 410 is not a pedantic 404: it tells a crawler to **drop** the URL rather than re-fetch it for weeks
1061
- * on the assumption the 404 was transient. Uses `_410.tsx` if the app has one, otherwise `_404`.
1062
- */
1063
- export function gone(options: StatusPageOptions = {}): never {
1064
- return statusSignal(410, options)
1065
- }
1066
-
1067
- /**
1068
- * Render a terminal page at any 4xx/5xx status - the escape hatch behind {@link notFound} and
1069
- * {@link gone} (402, 451, …). Uses `_<status>.tsx` if present, otherwise `_404`.
1070
- */
1071
- export function statusPage(status: number, options: StatusPageOptions = {}): never {
1072
- return statusSignal(status, options)
1073
- }
1074
-
1075
- /** The wrapper `revalidate()` returns: the action's `data` plus the paths it changed. A plain tagged
1076
- * shape (not a class) so `@nifrajs/client`'s `ActionData` can unwrap it structurally without importing
1077
- * from `@nifrajs/web`. `createWebApp` strips the wrapper - the client receives `data` as the body and
1078
- * the paths via the `X-Nifra-Revalidate` header. */
1079
- export interface RevalidateResult<T> {
1080
- readonly __nifraRevalidate: readonly string[]
1081
- readonly data: T
1082
- }
1083
-
1084
- /**
1085
- * Return this from an action to declare which routes the mutation changed (alongside the action's
1086
- * `data`). `createWebApp` sets the `X-Nifra-Revalidate` response header; after the submit the client
1087
- * marks those cached routes stale - refetching the active one and any mounted fetcher showing them -
1088
- * so a mutation can refresh views beyond the one that was submitted. `data` is still surfaced to the
1089
- * component as `actionData` (the wrapper is transparent to `ActionData<typeof action>`).
1090
- */
1091
- export function revalidate<T>(paths: readonly string[], data: T): RevalidateResult<T> {
1092
- return { __nifraRevalidate: paths, data }
1093
- }
1094
-
1095
- /**
1096
- * Serialize loader data for embedding inside an inline `<script>`. `JSON.stringify` alone
1097
- * is NOT safe there: a string containing `</script>` or `<!--` would break out of the
1098
- * script element (an XSS vector). Escape `<`/`>` to `\uXXXX`, plus the U+2028/U+2029
1099
- * separators.
1100
- */
1101
- export function serializeData(data: unknown): string {
1102
- const serialized = JSON.stringify(data ?? null)
1103
- // Most loader payloads contain no script-sensitive characters. Guard with chained `indexOf`
1104
- // rather than a regex `.test`: each probe is a native memchr-style scan, measured ~7x faster than
1105
- // the regex scan on V8 for a multi-KB payload (and the engine rejects the two >0xFF separator
1106
- // probes in O(1) when the string is internally one-byte, which serialized JSON almost always is).
1107
- // The same four characters are probed as the SCRIPT_ESCAPE class, so any payload the regex would
1108
- // escape still takes the escape path - this is only a cheaper detector, never a security
1109
- // relaxation.
1110
- const needsEscape =
1111
- serialized.indexOf("<") !== -1 ||
1112
- serialized.indexOf(">") !== -1 ||
1113
- serialized.indexOf(LINE_SEP) !== -1 ||
1114
- serialized.indexOf(PARA_SEP) !== -1
1115
- return needsEscape
1116
- ? serialized.replace(SCRIPT_ESCAPE, (ch) => SCRIPT_ESCAPE_MAP[ch] ?? ch)
1117
- : serialized
1118
- }
1119
-
1120
- function escapeHtml(value: string): string {
1121
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
1122
- }
1123
-
1124
- /**
1125
- * Escape a `<script>` element's text content so it cannot break out of the element. Per the HTML spec,
1126
- * a script's text may contain any character EXCEPT the sequences that the parser treats as element
1127
- * boundaries: `</` (which would begin the end tag - `</script>` is the obvious XSS vector, but ANY `</`
1128
- * starts script-data-end-tag parsing), and the comment/CDATA edges `<!--` / `]]>`. We escape the `<`
1129
- * (and the `>` of `]]>`) to its JS unicode escape: inside a JS/JSON string literal `<` is the
1130
- * identical character, so a JSON-LD payload is byte-equivalent after parsing - but the raw `<`/`>` the
1131
- * HTML tokenizer scans for is gone. This is the JSON-LD-in-HTML rule (content is JSON, never raw HTML),
1132
- * mirroring {@link serializeData}'s posture for the data-global script. Idempotent on already-safe text.
1133
- */
1134
- function escapeScriptContent(content: string): string {
1135
- // Order matters: rewrite `]]>` first (its `>` becomes `>`), then every `<` (covers `</` and
1136
- // `<!--` in one pass). `<` → `<`; the lone `>` of `]]>` → `>`. A bare `>` elsewhere is
1137
- // harmless in script data, so only the `]]>` close is targeted for `>`.
1138
- return content.replaceAll("]]>", "]]\\u003e").replaceAll("<", "\\u003c")
1139
- }
1140
-
1141
- function escapeAttr(value: string): string {
1142
- return value
1143
- .replaceAll("&", "&amp;")
1144
- .replaceAll('"', "&quot;")
1145
- .replaceAll("<", "&lt;")
1146
- .replaceAll(">", "&gt;")
1147
- }
1148
-
1149
- /** Serialize attributes that passed the shared SSR/client head trust policy. */
1150
- function tagAttrs(tag: "meta" | "link", attrs: Readonly<object>): string | null {
1151
- const trusted = trustedHeadAttributes(tag, attrs)
1152
- if (trusted === null) return null
1153
- let out = ""
1154
- for (const [name, value] of trusted) {
1155
- if (out !== "") out += " "
1156
- out += value === true ? name : `${name}="${escapeAttr(value)}"`
1157
- }
1158
- return out
1159
- }
1160
-
1161
- // Memoize the serialized head-tag string by the resolved `Meta` object's identity. A STATIC route
1162
- // `meta` is returned by-reference from resolveMeta, so the same object recurs every request → cache
1163
- // hit, and the invariant string is serialized once per route, not per request. A FUNCTION `meta`
1164
- // builds a fresh object each request (new identity) → miss → recompute, exactly as needed (its
1165
- // content can vary). WeakMap so a route module that's GC'd takes its entry with it.
1166
- const headTagsCache = new WeakMap<Meta, string>()
1167
-
1168
- function assertExecutableScriptType(type: string): void {
1169
- if (!EXECUTABLE_SCRIPT_TYPES.has(type)) {
1170
- throw new TypeError(
1171
- `[nifra/web] executable inline scripts accept ${[...EXECUTABLE_SCRIPT_TYPES].map((t) => JSON.stringify(t)).join(" or ")}; received ${JSON.stringify(type)}`,
1172
- )
1173
- }
1174
- }
1175
-
1176
- /** Render a route's `meta`/`link`/`script` as managed (`data-nifra`) head tags. Title is set
1177
- * separately. XSS-safe by construction: every attribute flows through the shared tag-specific trust
1178
- * policy then value escaping, and each `script[].content` through `escapeScriptContent`
1179
- * (breakout-escaped) - so loader-derived strings (LLM-authored `og:*`, user content) can't inject markup
1180
- * or close the tag early. String concatenation (no intermediate `.map()` arrays + spread) - parity with
1181
- * the already concat-based preloadLinks/styleLinks/islandPreloads loops; byte-identical output. Result
1182
- * is memoized per resolved-`Meta` identity (static meta → serialized once per route). */
1183
- function headTags(head: Meta | undefined): string {
1184
- if (head === undefined) return ""
1185
- const cached = headTagsCache.get(head)
1186
- if (cached !== undefined) return cached
1187
- let out = ""
1188
- if (head.meta !== undefined)
1189
- for (const m of head.meta) {
1190
- const attrs = tagAttrs("meta", m)
1191
- if (attrs !== null) out += `<meta${attrs === "" ? "" : ` ${attrs}`} data-nifra>`
1192
- }
1193
- if (head.link !== undefined)
1194
- for (const l of head.link) {
1195
- const attrs = tagAttrs("link", l)
1196
- if (attrs !== null) out += `<link${attrs === "" ? "" : ` ${attrs}`} data-nifra>`
1197
- }
1198
- // `<script>` slot - JSON-LD + other inert head scripts. `type` is attribute-escaped; `content` is
1199
- // breakout-escaped (`escapeScriptContent`) so a `</script>` (or `<!--`/`]]>`) payload can't close the
1200
- // element early. Managed (`data-nifra`) so a soft-nav's `applyHead` cleanly replaces it.
1201
- if (head.script !== undefined)
1202
- for (const s of head.script) {
1203
- const type = s.type ?? "application/ld+json"
1204
- if (!INERT_SCRIPT_TYPES.has(type)) {
1205
- throw new TypeError(
1206
- `[nifra/web] head.script only accepts inert JSON script types; received ${JSON.stringify(type)}. Use unsafeInlineScript() with a CSP nonce for executable code.`,
1207
- )
1208
- }
1209
- out += `<script type="${type}" data-nifra>${escapeScriptContent(s.content)}</script>`
1210
- }
1211
- if (head.unsafeScript !== undefined)
1212
- for (const s of head.unsafeScript) {
1213
- if (s.unsafe !== true || s.nonce.trim() === "") {
1214
- throw new TypeError("[nifra/web] executable inline scripts require a non-empty CSP nonce")
1215
- }
1216
- // `type` is validated, not escaped, for the same reason as the inert slot above: an unknown
1217
- // value here is a bug, and escaping one would emit a nonsense script type rather than say so.
1218
- // It was interpolated raw while the `nonce` beside it was escaped, so a descriptor built by hand
1219
- // - `unsafeScript` is a public field, the helper is only a convenience - could close the
1220
- // attribute and inject markup. Measured: `type: '"><img src=x onerror=alert(1)>'` reached the
1221
- // document. An injection in the slot whose whole purpose is to make script emission trustworthy.
1222
- assertExecutableScriptType(s.type)
1223
- out += `<script type="${s.type}" nonce="${escapeAttr(s.nonce)}" data-nifra>${escapeScriptContent(s.content)}</script>`
1224
- }
1225
- headTagsCache.set(head, out)
1226
- return out
1227
- }
1228
-
1229
- /**
1230
- * A `<link rel="canonical">` descriptor for a route's `meta.link`. The canonical URL tells search
1231
- * engines which URL is authoritative for a page (deduping query-string / tracking variants).
1232
- *
1233
- * ```ts
1234
- * export const meta = (a) => ({ link: [canonical(`https://site.com/posts/${a.params.slug}`)] })
1235
- * ```
1236
- */
1237
- export function canonical(href: string): LinkDescriptor {
1238
- return { rel: "canonical", href }
1239
- }
1240
-
1241
- /** Inputs for {@link openGraph} - the common Open Graph properties. All optional; only the provided
1242
- * ones become tags. `type` defaults to `"website"`. */
1243
- export interface OpenGraphInput {
1244
- readonly title?: string
1245
- readonly description?: string
1246
- /** Absolute URL of the share image (`og:image`). */
1247
- readonly image?: string
1248
- /** Canonical URL of the page (`og:url`). */
1249
- readonly url?: string
1250
- /** Object type (`og:type`) - `"website"`, `"article"`, … Default `"website"`. */
1251
- readonly type?: string
1252
- }
1253
-
1254
- /**
1255
- * Build the Open Graph `<meta property="og:*">` entries for a route's `meta.meta`. Returns only the
1256
- * properties you supplied (plus `og:type`, defaulting to `"website"`), so it composes with other meta.
1257
- *
1258
- * ```ts
1259
- * export const meta = { meta: [...openGraph({ title: "Nifra", image: "https://site.com/og.png" })] }
1260
- * ```
1261
- */
1262
- export function openGraph(input: OpenGraphInput): MetaDescriptor[] {
1263
- const tags: MetaDescriptor[] = []
1264
- const add = (property: string, content: string | undefined): void => {
1265
- if (content !== undefined) tags.push({ property, content })
1266
- }
1267
- add("og:title", input.title)
1268
- add("og:description", input.description)
1269
- add("og:image", input.image)
1270
- add("og:url", input.url)
1271
- // `og:type` always present (the spec's required property) - default "website" when unset.
1272
- tags.push({ property: "og:type", content: input.type ?? "website" })
1273
- return tags
1274
- }
1275
-
1276
- /**
1277
- * Build a JSON-LD `<script type="application/ld+json">` entry for a route's `meta.script` from a plain
1278
- * object. `JSON.stringify` produces the body; the head renderer breakout-escapes it (see
1279
- * `escapeScriptContent`), so a string field containing `</script>` is embedded safely.
1280
- *
1281
- * ```ts
1282
- * export const meta = {
1283
- * script: [jsonLd({ "@context": "https://schema.org", "@type": "Article", headline: "Hi" })],
1284
- * }
1285
- * ```
1286
- */
1287
- export function jsonLd(data: Record<string, unknown>): ScriptDescriptor {
1288
- return { type: "application/ld+json", content: JSON.stringify(data) }
1289
- }
1290
-
1291
- /**
1292
- * Deliberately unsafe escape hatch for executable inline code. The required nonce keeps the result
1293
- * compatible with a strict CSP and makes the security-sensitive choice visible at the call site.
1294
- */
1295
- export function unsafeInlineScript(
1296
- content: string,
1297
- options: { readonly nonce: string; readonly type?: "module" | "text/javascript" },
1298
- ): UnsafeScriptDescriptor {
1299
- if (options.nonce.trim() === "") {
1300
- throw new TypeError("[nifra/web] unsafeInlineScript requires a non-empty CSP nonce")
1301
- }
1302
- const type = options.type ?? "module"
1303
- // Checked here as well as at emit: the type union is compile-time only, and this helper is the one
1304
- // place a caller is told what it may pass. Failing at the call site names the argument; failing at
1305
- // render names a document.
1306
- assertExecutableScriptType(type)
1307
- return {
1308
- unsafe: true,
1309
- type,
1310
- nonce: options.nonce,
1311
- content,
1312
- }
1313
- }
1314
-
1315
- export interface CreateWebAppOptions<Env = unknown> {
1316
- readonly adapter: RenderAdapter
1317
- readonly manifest: Manifest
1318
- /** URL of the built client entry (module script) injected into every page. */
1319
- readonly clientEntry: string
1320
- /** Default document title for all pages. */
1321
- readonly title?: string
1322
- /**
1323
- * Options for the underlying `server()` - `requestTimeoutMs`, `admission`, `gracefulSignals`, and
1324
- * the rest of {@link ServerOptions}.
1325
- *
1326
- * Needed because the `Server` is constructed in here, so a caller has no other way to reach its
1327
- * constructor: a page app could set no request timeout and no capacity gate, which are exactly the
1328
- * two knobs a production readiness check looks for. An SSR app wants them MORE than a backend does -
1329
- * a render is slow and allocation-heavy, so a burst that a JSON API would absorb is the one that
1330
- * exhausts the pod.
1331
- *
1332
- * Applies to the whole app, {@link mounts} and the {@link api} auto-mount included: the capacity gate
1333
- * sits at the fetch entry, ahead of the request hooks those are dispatched from.
1334
- */
1335
- readonly server?: ServerOptions
1336
- /**
1337
- * Runs against the app BEFORE any page route is registered - the seam for `securityHeaders()`,
1338
- * `requestId()`, `logger()`, a rate limit, or anything else applied with `use`.
1339
- *
1340
- * ```ts
1341
- * createWebApp({
1342
- * …,
1343
- * use: (app) => {
1344
- * app.use(securityHeaders())
1345
- * app.use(requestId())
1346
- * },
1347
- * })
1348
- * ```
1349
- *
1350
- * A callback rather than an array because `use` is overloaded - `Middleware`, `IdentityPlugin`,
1351
- * `ContextPlugin` - and only the real call site instantiates the right overload. The return value
1352
- * is ignored: this is for cross-cutting concerns, not for declaring routes (declare those on the
1353
- * returned app, where they get their types).
1354
- *
1355
- * **Why the timing matters.** `beforeHandle`, `afterHandle`, `around`, `derive`/`decorate`, and
1356
- * `onError` are snapshotted into each route AS IT IS DECLARED, and `createWebApp` declares every
1357
- * page (plus the `/*` catch-all) before it returns - so a caller's `app.use(…)` afterwards binds
1358
- * them to nothing, silently. `requestId()` is exactly that case: it is a `derive`, so applied late
1359
- * it leaves every page without `c.requestId`. Route assurance evidence is order-scoped the same
1360
- * way, so a late `securityHeaders()` leaves the pages unable to PROVE the header to `nifra assure`
1361
- * even though it does still set it.
1362
- *
1363
- * `onRequest`/`onResponse` (and the response header/body hooks) are app-global arrays read at
1364
- * request time, so those alone DO work when added late. Using this seam for everything avoids
1365
- * having to remember which is which.
1366
- *
1367
- * Runs ahead of the {@link mounts} / {@link api} request hooks, so an `onRequest` middleware guards
1368
- * a mounted auth handler too.
1369
- *
1370
- * A `ContextPlugin` applied here takes runtime effect but cannot widen the declared return type of
1371
- * this function, so `c.requestId` is not typed on routes you declare afterwards. Named plugins are
1372
- * idempotent, so `app.use(requestId())` on the returned app recovers the TYPE without applying the
1373
- * plugin a second time.
1374
- */
1375
- readonly use?: (app: ReturnType<typeof server<Env>>) => void
1376
- /** Injected into each loader's `ctx.api` - typically an `inProcessClient(app)` (typed
1377
- * per-route via `@nifrajs/client`'s `createRoutes`). Opaque to the core.
1378
- *
1379
- * **Auto-mount.** Every `inProcessClient(backend)` exposes the symbol-keyed platform-aware backend
1380
- * mount interface from `@nifrajs/core/mount`; `createWebApp` also serves that backend over HTTP at
1381
- * {@link apiPrefix} (default `/api`): a request whose pathname starts with the prefix is dispatched
1382
- * before page routing with the same `env`/`waitUntil` platform context, and the backend's `Response`
1383
- * is returned untouched. The mount runs in `nifra dev` too. Pass `apiPrefix: ""` to disable it. */
1384
- readonly api?: unknown
1385
- /** HTTP path prefix the {@link api} backend is auto-mounted at (default `"/api"`). A request whose
1386
- * pathname is exactly the prefix or starts with `prefix + "/"` is dispatched to the backend before
1387
- * page routing; the backend therefore defines its routes at the **full** path (`server().post("/api/
1388
- * sync", …)`), matching the in-process `inProcessClient` call sites. Set to `""` to disable the
1389
- * auto-mount entirely (the app serves pages only and `api` stays a loader-only `ctx.api`). Mounting
1390
- * is also a no-op when `api` does not expose the symbol mount. */
1391
- readonly apiPrefix?: string
1392
- /**
1393
- * Strip {@link apiPrefix} from the pathname before dispatching to `api` (default `false`).
1394
- *
1395
- * The default suits a backend that declares FULL paths (`server().post("/api/sync", …)`), which is
1396
- * right when it is only ever mounted here. Set this when the backend declares its routes WITHOUT the
1397
- * prefix because it also runs standalone behind its own shell, so its paths cannot carry a prefix that
1398
- * only exists when it is mounted. Without it every request 404s inside the backend, and the workaround
1399
- * is a `Proxy` that rewrites each URL.
1400
- */
1401
- readonly apiStrip?: boolean
1402
- /**
1403
- * Sub-apps mounted ahead of page routing - an auth handler, a webhook receiver, a stack's routes.
1404
- *
1405
- * Structural on purpose: anything with `{ path, app: { fetch } }` fits, so a library that exposes its
1406
- * routes as such a list mounts as `mounts: theirRoutes` without `@nifrajs/web` taking a dependency on
1407
- * it. `better-auth` is the motivating case - it is not a `backend` route, so `/api/auth/*` used to 404
1408
- * silently.
1409
- *
1410
- * Tried longest-path-first and BEFORE the `api` mount, so a mount at `/api/auth` wins over a backend
1411
- * at `/api` no matter which was declared first. `stripPrefix` is the per-mount form of {@link apiStrip}:
1412
- * leave it off to pass the full path through.
1413
- */
1414
- readonly mounts?: ReadonlyArray<{
1415
- readonly path: string
1416
- readonly app: { fetch(request: Request): Response | Promise<Response> }
1417
- readonly stripPrefix?: boolean
1418
- }>
1419
- /** Secret for **draft / preview mode** (see `enableDraft`). When set, a request carrying a valid
1420
- * signed `__nifra_draft` cookie gets `ctx.draft === true` in loaders/actions (else always `false`).
1421
- * Pair with `withISR({ draftSecret })` so editors bypass the cache. Omit to disable draft mode. */
1422
- readonly draftSecret?: string
1423
- /** Per-route chunk URLs (`buildClient`'s `BuildManifest.routes`) - `routeId → [layout chunks…, own
1424
- * chunk]`. When present, each page `modulepreload`s its matched route's chunks alongside the entry,
1425
- * so the route code downloads in parallel (no entry→route-chunk waterfall). Omit ⇒ entry-only. */
1426
- readonly routePreload?: Readonly<Record<string, readonly string[]>>
1427
- /** The app's bundled stylesheet URLs (`buildClient`'s `BuildManifest.css`) - the aggregate, injected
1428
- * as `<link rel="stylesheet">` in a page's `<head>`. Used as the fallback for any route absent from
1429
- * {@link routeStyles}. Omit ⇒ no links (dev, where Vite injects CSS, or a CSS-free app). */
1430
- readonly styles?: readonly string[]
1431
- /** Per-route stylesheet URLs (`buildClient`'s `BuildManifest.routeStyles`) - `routeId → [chain CSS]`.
1432
- * When a matched route has an entry here, only those (its layout chain + own CSS) are linked instead
1433
- * of the aggregate `styles`, so a page ships only the CSS it uses. An empty array ⇒ no `<link>` (the
1434
- * page imports no CSS). Routes absent here fall back to `styles`. Omit ⇒ always use `styles`. */
1435
- readonly routeStyles?: Readonly<Record<string, readonly string[]>>
1436
- /** SSG: the prerendered-path set (e.g. `enumerateStaticRoutes(routes).paths` or the build's
1437
- * `prerendered.json`). Injected as `window.__NIFRA_PRERENDERED__` on every page so a client soft-nav
1438
- * into a prerendered route fetches its static `_data.json` instead of hitting the worker. */
1439
- readonly prerenderedPaths?: readonly string[]
1440
- /** Publish the project's `AGENTS.md` inside `/llms.txt` and `/llms-full.txt`. **Off by default**:
1441
- * those endpoints are public and unauthenticated, while `AGENTS.md` is a repo file written for the
1442
- * team - unreleased feature names, internal hostnames, and "don't touch X yet" notes live there
1443
- * routinely. Turn it on only for a repo whose guidelines you would publish as a page. */
1444
- readonly publishLocalGuidelines?: boolean
1445
- /** SSG: per dynamic route pattern, its `getStaticPaths` `fallback` (from `enumerateStaticRoutes` or
1446
- * the build's `prerendered.json`). A route mapped to `"404"` rejects any path NOT in
1447
- * `prerenderedPaths` with the 404 page - the unlisted path simply doesn't exist. `"ssr"` (the
1448
- * default for unmapped routes) renders unlisted paths on-demand. */
1449
- readonly staticFallbacks?: Readonly<Record<string, "ssr" | "404">>
1450
- /** Observe every loader/action failure - for error-reporting plugins (Sentry-style). Called for
1451
- * real throws (not control-flow `Response`s like `redirect`), **before** the nearest `_error`
1452
- * boundary renders / a soft-nav 500 / a rethrow - so it sees errors that the boundary would
1453
- * otherwise hide. Observation only; its own throws are swallowed so a faulty reporter can't break
1454
- * rendering. (`beforeLoader` is intentionally omitted - the core HTTP hooks already cover
1455
- * pre-request work.) */
1456
- readonly onLoaderError?: (
1457
- error: unknown,
1458
- ctx: {
1459
- readonly request: Request
1460
- readonly params: Readonly<Record<string, string>>
1461
- readonly route: string
1462
- },
1463
- ) => void
1464
- }
1465
-
1466
- /** The handler context fields createWebApp uses - a structural subset of nifra's `Context`. */
1467
- interface RouteContext {
1468
- readonly params: Record<string, string>
1469
- readonly req: Request
1470
- /** Platform bindings (Workers env), forwarded to each route's loader/action as `args.env`. */
1471
- readonly env: unknown
1472
- }
1473
-
1474
- /**
1475
- * Re-issue `request` with `prefix` removed from its pathname.
1476
- *
1477
- * Needed because two conventions exist and both are reasonable. `createWebApp`'s auto-mount assumes a
1478
- * backend that declares FULL paths (`server().post("/api/sync")`), which is right when the backend is
1479
- * only ever mounted here. A backend that also runs standalone declares paths WITHOUT the prefix and
1480
- * lets its own shell supply it - and mounting one of those here used to require the caller to wrap it
1481
- * in a `Proxy` that rewrote every URL. Two apps wrote that same wrapper independently, which is the
1482
- * signal that it belonged in the framework.
1483
- *
1484
- * The `Request` is rebuilt rather than mutated (`url` is read-only), preserving method, headers, body,
1485
- * and duplex streaming - the body is passed through unread, so a large or streamed upload is untouched.
1486
- */
1487
- function stripMountPrefix(request: Request, prefix: string): Request {
1488
- const url = new URL(request.url)
1489
- const rest = url.pathname.slice(prefix.length)
1490
- url.pathname = rest === "" ? "/" : rest
1491
- // `url.href`, not the `URL`: this type set only declares the string and Request overloads.
1492
- return new Request(url.href, request)
1493
- }
1494
-
1495
- /**
1496
- * Resolve the explicit symbol-keyed backend mount interface. The symbol seam forwards platform
1497
- * context without making web depend on client.
1498
- */
1499
- function backendMountOf(api: unknown): BackendMountHandler | undefined {
1500
- if ((typeof api !== "object" && typeof api !== "function") || api === null) return undefined
1501
- const explicit = (api as Partial<BackendMount>)[NIFRA_BACKEND_MOUNT]
1502
- if (typeof explicit !== "function") return undefined
1503
- return (request, platform) => explicit.call(api, request, platform)
1504
- }
1505
-
1506
- // `createWebApp` reaches the same Request object through the mount hook and the page route. Cache the
1507
- // allocation-light core split once so API mounting, path hydration, search parsing, and SSG fallback
1508
- // checks do not each rescan the absolute URL. WeakMap keeps this bounded to requests that are alive.
1509
- const REQUEST_URL_PARTS = new WeakMap<Request, UrlParts>()
1510
- const urlPartsFor = (request: Request): UrlParts => {
1511
- const cached = REQUEST_URL_PARTS.get(request)
1512
- if (cached !== undefined) return cached
1513
- const parts = urlPartsOf(request.url)
1514
- REQUEST_URL_PARTS.set(request, parts)
1515
- return parts
1516
- }
1517
-
1518
- /**
1519
- * Build a nifra app from a route manifest: every route SSRs its layout chain via `renderPage`,
1520
- * and a wildcard catch-all renders `_404` (or a plain 404). Reuses @nifrajs/core's router +
1521
- * lifecycle, so matching, params, and precedence are battle-tested. fs-free - feed it a
1522
- * manifest from `discoverRoutes` (`@nifrajs/web/fs`) at startup, so the served app stays portable.
1523
- *
1524
- * **Typed platform bindings.** Pass `Env` - `createWebApp<Env>({ … })` - to declare the app's Workers
1525
- * bindings ONCE. It seeds the returned `Server`'s context with `{ env: Env }` (exactly as the backend's
1526
- * `server<Env>()` does), so `app.fetch(req, { env })` / `toFetchHandler(app)` type-check the `env`
1527
- * argument against the declared shape - no per-binding cast at the edge entry. Per-route loaders/actions
1528
- * stay typed independently of this call: annotate them with `@nifrajs/client`'s `LoaderArgs<Api, Env>`
1529
- * (same `Env`) so `ctx.env.MY_KV` is typed there too. Omit the parameter and `Env` is `unknown` - the
1530
- * secure default; validate at the trust boundary before use.
1531
- */
1532
- export function createWebApp<Env = unknown>(
1533
- options: CreateWebAppOptions<Env>,
1534
- ): ReturnType<typeof server<Env>> {
1535
- const { adapter, manifest, clientEntry, title, api } = options
1536
- const titleOption = title === undefined ? {} : { title }
1537
- // Draft/preview: when a `draftSecret` is configured, each request's signed `__nifra_draft` cookie is
1538
- // verified once and surfaced to loaders/actions as `ctx.draft`. No secret ⇒ always `false` (sync, free).
1539
- const draftFlag = (req: Request): Promise<boolean> =>
1540
- options.draftSecret === undefined
1541
- ? Promise.resolve(false)
1542
- : isDraftEnabled(req, options.draftSecret)
1543
- // Per-route preload chunks (spread into renderPage; omitted when unmapped, for exactOptionalPropertyTypes).
1544
- const preloadOf = (id: string): { preload?: readonly string[] } => {
1545
- const chunks = options.routePreload?.[id]
1546
- return chunks ? { preload: chunks } : {}
1547
- }
1548
- // The matched route's stylesheet links (spread into renderPage). Per-route when the build mapped it
1549
- // (`routeStyles[id]` - only the chain's CSS; an empty array ⇒ no `<link>`), else the aggregate
1550
- // `styles`. Omitted entirely when CSS-free (for exactOptionalPropertyTypes).
1551
- const stylesOf = (id: string): { styles?: readonly string[] } => {
1552
- const perRoute = options.routeStyles?.[id]
1553
- if (perRoute !== undefined) return { styles: perRoute }
1554
- return options.styles && options.styles.length > 0 ? { styles: options.styles } : {}
1555
- }
1556
- // Seed the context with the declared `Env` so `app.fetch(req, { env })` / `toFetchHandler(app)` type
1557
- // the platform bindings (see the `createWebApp` doc). The runtime `env` still arrives per-request via
1558
- // `app.fetch(req, { env })`; this is a compile-time-only seed (`server<Env>()` casts, doesn't store).
1559
- const app = server<Env>(options.server)
1560
- // Before the mount hooks and before every page route, so the order-scoped hooks (`derive`,
1561
- // `beforeHandle`, assurance evidence) actually bind to them - see the `use` option. A caller
1562
- // cannot do this after the fact: by the time this function returns, the routes are declared.
1563
- options.use?.(app)
1564
- // Auto-mount the in-process backend over HTTP at `apiPrefix` (default `/api`), BEFORE page routing.
1565
- // `onRequest` runs on the raw request ahead of the router, so this wins over the page wildcard `/*`
1566
- // for every method (POST/GET/PUT/…) - not just the GET page routes - and a backend 404 (`/api/none`)
1567
- // surfaces as the backend's own response, never the page 404. We dispatch the SAME `Request` object
1568
- // (its body unread) so streamed/large bodies pass through untouched; the backend defines its routes
1569
- // at the full prefixed path (`server().post("/api/sync", …)`), matching the `inProcessClient` call
1570
- // sites. `apiPrefix: ""` opts out; a non-mountable `api` (no symbol mount) is left pages-only. The hook
1571
- // is registered ONLY when both hold, so a pages-only app keeps core's synchronous no-hook fast path.
1572
- const apiPrefix = options.apiPrefix ?? "/api"
1573
- const apiStrip = options.apiStrip === true
1574
- const mountedApi = backendMountOf(api)
1575
- // Longest path first, so a more specific mount (`/api/auth`) is tried before a broader one (`/api`)
1576
- // regardless of the order they were declared in.
1577
- const mounts = [...(options.mounts ?? [])].sort((a, b) => b.path.length - a.path.length)
1578
- const underPrefix = (pathname: string, prefix: string): boolean =>
1579
- pathname === prefix || pathname.startsWith(`${prefix}/`)
1580
-
1581
- if (mounts.length > 0 || (apiPrefix !== "" && mountedApi !== undefined)) {
1582
- app.onRequest((req, platform) => {
1583
- const { pathname } = urlPartsFor(req)
1584
- // Sub-app mounts win over the backend prefix: they are the more specific declaration, and an
1585
- // auth handler mounted at `/api/auth` must not be swallowed by the backend mounted at `/api`.
1586
- for (const mount of mounts) {
1587
- if (!underPrefix(pathname, mount.path)) continue
1588
- return mount.app.fetch(mount.stripPrefix === true ? stripMountPrefix(req, mount.path) : req)
1589
- }
1590
- // Exactly the prefix (`/api`) or a sub-path (`/api/…`) - NOT a sibling like `/apixyz` that merely
1591
- // shares the prefix as a string head. Dispatch the original `req` (body intact) to the backend.
1592
- if (mountedApi !== undefined && apiPrefix !== "" && underPrefix(pathname, apiPrefix)) {
1593
- return mountedApi(apiStrip ? stripMountPrefix(req, apiPrefix) : req, platform)
1594
- }
1595
- return undefined // not an API path → continue to page routing
1596
- })
1597
- }
1598
- // SSG `fallback: "404"`: the set of concrete paths that actually exist for those routes. An unlisted
1599
- // path under a `"404"` route is rejected (it isn't a static file, and the route declared it shouldn't
1600
- // SSR on demand). O(1) membership via a Set.
1601
- const prerenderedSet = new Set(options.prerenderedPaths ?? [])
1602
- const matchManifestRoute = createMatcher(
1603
- manifest.routes.map((route) => ({ routeId: route.id, pattern: route.pattern })),
1604
- )
1605
- const routeById = new Map(manifest.routes.map((route) => [route.id, route]))
1606
-
1607
- // Load a route's layout modules (outermost layout → innermost), keeping each module whole so the
1608
- // render path can take both its `default` (the component chain) AND its `meta` (the sitewide head it
1609
- // contributes). Loaded lazily - the data-only and 405 branches return before any layout is needed.
1610
- const loadLayoutModules = async (route: RouteEntry): Promise<LoadedLayoutModules> => {
1611
- const modules = await Promise.all(
1612
- // layoutIds only reference layouts present in the manifest (buildManifest invariant).
1613
- route.layoutIds.map((id) => (manifest.layouts[id] as LayoutEntry).load()),
1614
- )
1615
- // A layout is not a form target, so an `action` there is a mistake with no meaning to give it.
1616
- // A `loader`, by contrast, now runs (see `runLayoutChain`).
1617
- for (let i = 0; i < modules.length; i++) {
1618
- if ((modules[i] as { action?: unknown }).action === undefined) continue
1619
- const id = route.layoutIds[i] as string
1620
- throw new Error(
1621
- `[nifra/web] "${(manifest.layouts[id] as LayoutEntry).file}" exports an \`action\`, but layouts do not run one - only route files do. Move the mutation into the route that submits to it.`,
1622
- )
1623
- }
1624
- return modules
1625
- }
1626
-
1627
- /**
1628
- * Run a route's layout-chain loaders, honouring declared gates.
1629
- *
1630
- * Returns once every **gate** has resolved, with the non-gate loaders still in flight, so the caller
1631
- * can start the page loader at exactly the right moment: after anything that might reject the
1632
- * request, alongside anything that merely fetches.
1633
- *
1634
- * The ordering is the security-relevant part. Parallel loaders are NOT an authorization boundary -
1635
- * a page loader running concurrently with a guard has already queried by the time the guard says no.
1636
- * Remix documents that as a footgun; here it is a declaration instead. `export const gate = true`
1637
- * makes a layout blocking for everything beneath it, and nothing beneath a rejected gate runs.
1638
- *
1639
- * Each layout receives only the params it OWNS ({@link RouteEntry.layoutParams}), not the route's
1640
- * full set, so a layout at `orgs/[org]/` cannot read a param belonging to a route below it.
1641
- */
1642
- /**
1643
- * Layout indices a client navigation asked to keep, from {@link RETAIN_HEADER}.
1644
- *
1645
- * The CLIENT decides retainability: it knows each layout's scoped params (shipped in the bootstrap)
1646
- * and both the old and new match, so it can tell whether a layout's own prefix changed - without the
1647
- * server re-matching a path the client already matched.
1648
- *
1649
- * It is a HINT, not an instruction. The client is asking to keep data it already holds, which is
1650
- * harmless for data and unacceptable for a guard, so `runLayoutChain` refuses to skip a gate no
1651
- * matter what arrives here. Anything unparseable is ignored rather than rejected: the worst case of
1652
- * a bad hint is a loader that runs when it need not.
1653
- */
1654
- const retainedIndices = (header: string | null): ReadonlySet<number> => {
1655
- if (header === null || header === "") return EMPTY_RETAIN
1656
- const out = new Set<number>()
1657
- for (const part of header.split(",")) {
1658
- // Digits only. `Number("")` is 0 and `Number(" ")` is 0, so a stray comma would otherwise read
1659
- // as "retain index 0" and silently skip the outermost layout.
1660
- if (!/^\d+$/.test(part)) continue
1661
- out.add(Number(part))
1662
- }
1663
- return out
1664
- }
1665
-
1666
- /**
1667
- * Validate a data-navigation's retain request against the manifest and its declared source path.
1668
- * A client may ask to retain every slot it currently has; the server only honours indices whose
1669
- * layout identity and owned params are unchanged. Hard document GETs never retain anything.
1670
- */
1671
- const validatedRetainedIndices = (
1672
- req: Request,
1673
- route: RouteEntry,
1674
- params: Readonly<Record<string, string>>,
1675
- ): ReadonlySet<number> => {
1676
- if (req.headers.get(DATA_HEADER) === null) return EMPTY_RETAIN
1677
- const requested = retainedIndices(req.headers.get(RETAIN_HEADER))
1678
- const from = req.headers.get(NAV_FROM_HEADER)
1679
- if (requested.size === 0 || from === null) return EMPTY_RETAIN
1680
- let fromPath: string
1681
- try {
1682
- const current = new URL(req.url)
1683
- const source = new URL(from, current)
1684
- if (source.origin !== current.origin) return EMPTY_RETAIN
1685
- fromPath = source.pathname + source.search
1686
- } catch {
1687
- return EMPTY_RETAIN
1688
- }
1689
- const previousMatch = matchManifestRoute(fromPath)
1690
- if (previousMatch === null) return EMPTY_RETAIN
1691
- const previous = routeById.get(previousMatch.routeId)
1692
- if (previous === undefined) return EMPTY_RETAIN
1693
- const valid = new Set<number>()
1694
- for (const index of requested) {
1695
- if (route.layoutIds[index] !== previous.layoutIds[index]) continue
1696
- const owned = route.layoutParams?.[index] ?? []
1697
- const previouslyOwned = previous.layoutParams?.[index] ?? []
1698
- if (
1699
- owned.length !== previouslyOwned.length ||
1700
- owned.some((name, i) => name !== previouslyOwned[i]) ||
1701
- owned.some((name) => params[name] !== previousMatch.params[name])
1702
- ) {
1703
- continue
1704
- }
1705
- valid.add(index)
1706
- }
1707
- return valid
1708
- }
1709
-
1710
- // The validated (or raw-parsed) search a route's loader context receives; `searchOf` fails closed to
1711
- // the schema's defaults on hostile input, so this never throws on an attacker-picked query.
1712
- const loaderSearch = (searchSchema: RouteModule["searchSchema"], request: Request) =>
1713
- searchOf(searchSchema, urlPartsFor(request).search)
1714
-
1715
- // The route's EFFECTIVE search once its layout chain is loaded: the layout schemas merged with the
1716
- // page's (page-wins), the same chain the client mount builds for `useSearch`. Used for the page loader's
1717
- // `ctx.search` and the render's `RenderProps.search`, so both agree with the client and with each other.
1718
- const searchChainOf = (
1719
- layoutMods: LoadedLayoutModules,
1720
- mod: RouteModule,
1721
- request: Request,
1722
- ): Record<string, unknown> =>
1723
- searchOfChain(
1724
- [...layoutMods.map((m) => m.searchSchema), mod.searchSchema],
1725
- urlPartsFor(request).search,
1726
- )
1727
-
1728
- const runLayoutChain = async (
1729
- route: RouteEntry,
1730
- ctx: LoaderContext,
1731
- retain: ReadonlySet<number> = new Set(),
1732
- ): Promise<{
1733
- readonly modules: LoadedLayoutModules
1734
- readonly layoutData: readonly unknown[] | undefined
1735
- readonly retained: readonly number[]
1736
- readonly pending: Promise<unknown>
1737
- }> => {
1738
- const modules = await loadLayoutModules(route)
1739
- if (!modules.some((m) => m.loader !== undefined)) {
1740
- // Nothing to run: no array is produced, so a page-only app serializes nothing extra and its
1741
- // HTML is byte-identical to before this feature.
1742
- return { modules, layoutData: undefined, retained: [], pending: Promise.resolve() }
1743
- }
1744
- const results: unknown[] = new Array(modules.length).fill(null)
1745
- const retained: number[] = []
1746
- const pending: Array<Promise<void>> = []
1747
- for (let i = 0; i < modules.length; i++) {
1748
- const loader = modules[i]?.loader
1749
- if (loader === undefined) continue
1750
- // Unchanged scope: the client keeps what it has. A GATE is never skipped - it is a guard, and a
1751
- // guard that only runs when the URL prefix changed is not a guard.
1752
- if (retain.has(i) && modules[i]?.gate !== true) {
1753
- retained.push(i)
1754
- continue
1755
- }
1756
- const scoped: LoaderContext = {
1757
- ...ctx,
1758
- params: scopeParams(ctx.params, route.layoutParams?.[i]),
1759
- }
1760
- if (modules[i]?.gate === true) {
1761
- // Blocking: awaited here, so a throw propagates before anything deeper is started.
1762
- try {
1763
- results[i] = await loader(scoped)
1764
- } catch (err) {
1765
- throw tagLayoutError(err, route.layoutIds[i] as string)
1766
- }
1767
- continue
1768
- }
1769
- const layoutId = route.layoutIds[i] as string
1770
- const index = i
1771
- // The loader is invoked INSIDE the async function, not before it. `Promise.resolve(loader(x))`
1772
- // would let a synchronously-throwing loader escape past the rejection handler entirely - the
1773
- // exception happens while evaluating the argument, before any promise exists to reject.
1774
- pending.push(
1775
- (async () => {
1776
- try {
1777
- results[index] = await loader(scoped)
1778
- } catch (err) {
1779
- throw tagLayoutError(err, layoutId)
1780
- }
1781
- })(),
1782
- )
1783
- }
1784
- return { modules, layoutData: results, retained, pending: Promise.all(pending) }
1785
- }
1786
-
1787
- /** Run only blocking layout gates before a route action. Non-gate loaders fetch render data and
1788
- * therefore run after the mutation when a native POST needs a fresh document. */
1789
- const runLayoutGates = async (
1790
- route: RouteEntry,
1791
- ctx: LoaderContext,
1792
- ): Promise<LoadedLayoutModules> => {
1793
- const modules = await loadLayoutModules(route)
1794
- for (let i = 0; i < modules.length; i++) {
1795
- const mod = modules[i]
1796
- if (mod?.gate !== true || mod.loader === undefined) continue
1797
- try {
1798
- await mod.loader({
1799
- ...ctx,
1800
- params: scopeParams(ctx.params, route.layoutParams?.[i]),
1801
- })
1802
- } catch (err) {
1803
- throw tagLayoutError(err, route.layoutIds[i] as string)
1804
- }
1805
- }
1806
- return modules
1807
- }
1808
-
1809
- // Build a route's render chain + its merged `<head>` from the already-loaded layout modules + the
1810
- // page module. The chain is `[…layout components, page]`; the head merges each layout's `meta`
1811
- // export (outermost→innermost) with the page's (last), so a `head`/`meta` on `_layout.tsx`
1812
- // contributes sitewide tags. `metaArgs` (loader data + params) feed function-form `meta`s.
1813
- const resolveChainAndHead = (
1814
- layoutModules: LoadedLayoutModules,
1815
- page: RouteModule,
1816
- metaArgs: MetaArgs,
1817
- ): { chain: unknown[]; head: Meta } => {
1818
- const chain = [...layoutModules.map((m) => m.default), page.default]
1819
- const heads = [
1820
- ...layoutModules.map((m) => resolveMeta(m.meta, metaArgs)),
1821
- resolveMeta(page.meta, metaArgs),
1822
- ]
1823
- return { chain, head: mergeHeads(heads) }
1824
- }
1825
-
1826
- // Dir a special-file id lives in: `_error`→"" , `a/b/_error`→"a/b" (and likewise for `_layout`).
1827
- const dirOfId = (id: string, suffix: string): string =>
1828
- id === suffix ? "" : id.slice(0, id.length - suffix.length - 1)
1829
-
1830
- /**
1831
- * Choose the `_error` boundary for a failure, respecting where a LAYOUT loader failed.
1832
- *
1833
- * A route error uses the nearest boundary, as it always has. A layout error must not: the nearest
1834
- * boundary can sit BELOW the layout that threw, and rendering there would wrap the boundary in that
1835
- * very layout - the one whose loader just failed and whose data therefore never arrived.
1836
- */
1837
- const boundaryFor = (route: RouteEntry, err: unknown): string | undefined => {
1838
- const ids = route.errorIds ?? []
1839
- const failing = layoutErrorId(err)
1840
- if (failing === undefined) return ids.at(-1)
1841
- const layoutDir = dirOfId(failing, "_layout")
1842
- // Deepest boundary at or ABOVE the failing layout's directory.
1843
- for (let i = ids.length - 1; i >= 0; i--) {
1844
- const errDir = dirOfId(ids[i] as string, "_error")
1845
- if (errDir === "" || errDir === layoutDir || layoutDir.startsWith(`${errDir}/`)) return ids[i]
1846
- }
1847
- return undefined
1848
- }
1849
-
1850
- // The request's origin (scheme + host + port, NO trailing slash) - the one server fact `meta()` needs
1851
- // for absolute `canonical`/`og:url`/`og:image` but can't otherwise see (it also runs on the client).
1852
- // `URL.origin` is exactly that shape; it matches the browser's `location.origin` for the same URL, so
1853
- // a soft-nav's `applyHead` resolves an identical `<head>` (no hydration drift). A malformed `req.url`
1854
- // (shouldn't happen on a real request) degrades to `""` - the documented unknown-origin default -
1855
- // rather than throwing during render.
1856
- const originOf = (req: Request): string => {
1857
- try {
1858
- return new URL(req.url).origin
1859
- } catch {
1860
- return ""
1861
- }
1862
- }
1863
-
1864
- // The request's `pathname + search` - threaded into `renderPage` so an adapter's `useLocation`/
1865
- // `useSearchParams` render the current URL server-side and hydrate against the client's initial state
1866
- // (which the client entry seeds from `location.pathname + location.search`). No hash: it never reaches
1867
- // the server. A malformed `req.url` degrades to "/" rather than throwing during render.
1868
- const pathOf = (req: Request): string => {
1869
- try {
1870
- const parts = urlPartsFor(req)
1871
- return parts.pathname + parts.search
1872
- } catch {
1873
- return "/"
1874
- }
1875
- }
1876
-
1877
- /**
1878
- * Render the **nearest `_error` boundary** when a route's loader throws (the agnostic, server-side
1879
- * half of error UI - works on every adapter, no client takeover). The boundary renders in place of
1880
- * the page, wrapped by the layouts **at or above** its segment (deeper layouts are dropped). It's
1881
- * served **non-hydrated** at status 500: a terminal page, and rendering a boundary (not the page the
1882
- * client maps this route to) would otherwise hydrate-mismatch. The component receives `{ name,
1883
- * message }` - never the stack (no internals leak into HTML).
1884
- */
1885
- const renderError = async (
1886
- route: RouteEntry,
1887
- errorId: string,
1888
- err: unknown,
1889
- ): Promise<Response | RenderedPage> => {
1890
- const errDir = dirOfId(errorId, "_error")
1891
- const keptLayoutIds = route.layoutIds.filter((id) => {
1892
- const ld = dirOfId(id, "_layout")
1893
- return ld === "" || ld === errDir || errDir.startsWith(`${ld}/`)
1894
- })
1895
- const layouts = await Promise.all(
1896
- keptLayoutIds.map((id) =>
1897
- (manifest.layouts[id] as LayoutEntry).load().then((m) => m.default),
1898
- ),
1899
- )
1900
- const { default: errComp } = await (manifest.errors?.[errorId] as LayoutEntry).load()
1901
- const e = err instanceof Error ? err : new Error(String(err))
1902
- return renderPageResult({
1903
- adapter,
1904
- chain: [...layouts, errComp],
1905
- data: { name: e.name, message: e.message },
1906
- clientEntry,
1907
- routeId: errorId,
1908
- status: 500,
1909
- hydrate: false,
1910
- ...titleOption,
1911
- })
1912
- }
1913
-
1914
- // The 404 response - the `_404` page (status 404) or a plain-text fallback. Shared by the wildcard
1915
- // catch-all (unmatched paths) and the `fallback: "404"` enforcement (unlisted paths under a route
1916
- // that opted out of on-demand SSR).
1917
- const renderNotFound = (path?: string): Promise<Response | RenderedPage> =>
1918
- renderTerminalStatus(404, path)
1919
-
1920
- /**
1921
- * Render a terminal-status page: the `_<status>` page if the app authored one, else `_404`, else
1922
- * plain text. Shared by the wildcard catch-all, `fallback: "404"` enforcement, and a loader's
1923
- * `notFound()` / `gone()` / `statusPage()`, so all of them resolve the page and set the status
1924
- * through one path rather than forking.
1925
- *
1926
- * Hydrates, following the `_404` precedent rather than `_error`'s non-hydrated 500: these are
1927
- * ordinary pages the client router can own, and a 404 arrived at by clicking a link should behave
1928
- * like any other route.
1929
- */
1930
- const renderTerminalStatus = async (
1931
- status: number,
1932
- path?: string,
1933
- extraHeaders?: HeadersLike,
1934
- ): Promise<Response | RenderedPage> => {
1935
- const page = manifest.statusPages?.[String(status)] ?? manifest.notFound
1936
- if (page === undefined) {
1937
- const headers = new Headers(extraHeaders)
1938
- headers.set("content-type", "text/plain; charset=utf-8")
1939
- return new Response(STATUS_TEXT[status] ?? "Error", { status, headers })
1940
- }
1941
- // The routeId decides which preload/style bundle and which client component this maps to, so it
1942
- // must name the page actually rendered - `_410` when `_410.tsx` exists, `_404` when it fell back.
1943
- const routeId = manifest.statusPages?.[String(status)] !== undefined ? `_${status}` : "_404"
1944
- const loaded = (await page.load()) as {
1945
- readonly default: unknown
1946
- readonly searchSchema?: RouteModule["searchSchema"]
1947
- }
1948
- const component = loaded.default
1949
- return renderPageResult({
1950
- adapter,
1951
- chain: [component],
1952
- data: null,
1953
- clientEntry,
1954
- routeId,
1955
- // The page hydrates, so besides `path` its SSR `search` must equal the client mount's derivation for
1956
- // this routeId (`searchOf(searchSchema, url.search)`), or a status page reading `useSearch` drifts.
1957
- // Only when `path` is present (a real URL); a schema-less status page then gets the raw parsed query.
1958
- ...(path !== undefined
1959
- ? {
1960
- search: searchOf(
1961
- loaded.searchSchema,
1962
- path.includes("?") ? path.slice(path.indexOf("?")) : "",
1963
- ),
1964
- }
1965
- : {}),
1966
- // The page hydrates, so its SSR `path` must equal the client's initial
1967
- // `location.pathname+search` (an unmatched path yields no params → `{}`), or a `useLocation`
1968
- // on it would drift.
1969
- ...(path !== undefined ? { path } : {}),
1970
- status,
1971
- ...(extraHeaders !== undefined ? { headers: extraHeaders } : {}),
1972
- ...preloadOf(routeId),
1973
- ...stylesOf(routeId),
1974
- prerenderedPaths: options.prerenderedPaths ?? [],
1975
- ...titleOption,
1976
- })
1977
- }
1978
-
1979
- /**
1980
- * Answer a loader's terminal-status signal, in whichever form the caller asked for.
1981
- *
1982
- * A hard navigation wants the document, so it gets the rendered boundary. A client-side navigation
1983
- * fetched DATA, not a document, so it gets an empty body plus the status on `X-Nifra-Status`, and
1984
- * the client router renders the same boundary from its own manifest. Sending the HTML back to a
1985
- * soft-nav would be answering a different question than the one asked - and skipping the header
1986
- * entirely is what leaves a crawler seeing a correct 404 while a user who clicked a link sees a
1987
- * blank page.
1988
- */
1989
- const renderStatusSignal = (
1990
- req: Request,
1991
- signal: StatusSignal,
1992
- ): Promise<Response | RenderedPage> | Response => {
1993
- const { status, headers } = signal[STATUS_SIGNAL]
1994
- if (req.headers.get(DATA_HEADER) !== null) {
1995
- const responseHeaders = new Headers(headers)
1996
- responseHeaders.set(STATUS_HEADER, String(status))
1997
- return new Response(null, { status, headers: responseHeaders })
1998
- }
1999
- return renderTerminalStatus(status, pathOf(req), headers)
2000
- }
2001
-
2002
- for (const route of manifest.routes) {
2003
- // A dynamic route whose `getStaticPaths` declared `fallback: "404"` - only its prerendered paths
2004
- // exist; anything else 404s (computed once per route, not per request).
2005
- const is404Fallback = options.staticFallbacks?.[route.pattern] === "404"
2006
- // Per-route document-assembly cache (see RenderAssemblyCache): filled on the first GET render and
2007
- // reused while the route + layout MODULE IDENTITIES are unchanged. Attached only when every meta
2008
- // in the chain is static - a `meta(data)` function makes the head per-request, so those routes
2009
- // always assemble fresh. A module reload (dev HMR) yields new module objects, dropping the slot.
2010
- let assemblySlot: RenderAssemblyCache | undefined
2011
- let assemblySlotMod: unknown
2012
- let assemblySlotLayouts: LoadedLayoutModules | undefined
2013
- const assemblyCacheFor = (
2014
- mod: RouteModule,
2015
- lms: LoadedLayoutModules,
2016
- ): { assemblyCache: RenderAssemblyCache } | Record<string, never> => {
2017
- if (typeof mod.meta === "function") return {}
2018
- for (const m of lms) if (typeof m.meta === "function") return {}
2019
- const layoutsUnchanged =
2020
- assemblySlotLayouts !== undefined &&
2021
- assemblySlotLayouts.length === lms.length &&
2022
- assemblySlotLayouts.every((m, i) => m === lms[i])
2023
- if (assemblySlotMod !== mod || !layoutsUnchanged) {
2024
- assemblySlot = {}
2025
- assemblySlotMod = mod
2026
- assemblySlotLayouts = lms
2027
- }
2028
- return { assemblyCache: assemblySlot as RenderAssemblyCache }
2029
- }
2030
- app.register("GET", route.pattern, undefined, async (c: RouteContext) => {
2031
- // Enforce `fallback: "404"` before any work: an unlisted path under this route doesn't exist.
2032
- // Covers hard navigation directly; a client soft-nav's data fetch gets the 404, throws, and the
2033
- // history layer falls back to a full-page navigation (which lands here again, as a document).
2034
- if (is404Fallback && !prerenderedSet.has(urlPartsFor(c.req).pathname)) {
2035
- return renderNotFound(pathOf(c.req))
2036
- }
2037
- const mod = await route.load()
2038
- const draft = await draftFlag(c.req)
2039
- let data: unknown
2040
- let layoutData: readonly unknown[] | undefined
2041
- let layoutModules: LoadedLayoutModules | undefined
2042
- let layoutRetained: readonly number[] = []
2043
- try {
2044
- const ctx = {
2045
- params: c.params,
2046
- request: c.req,
2047
- req: c.req,
2048
- api,
2049
- env: c.env,
2050
- draft,
2051
- search: loaderSearch(mod.searchSchema, c.req),
2052
- }
2053
- // Layout loaders run for BOTH the document and the data-only request. A gate that only ran on
2054
- // the document path would be bypassed by adding the data header, which is exactly the request
2055
- // a client navigation makes - a guard has to hold on the path an attacker can pick.
2056
- //
2057
- // `runLayoutChain` returns once every GATE has resolved, with the non-gate loaders still in
2058
- // flight. So the page loader starts as late as correctness requires and as early as speed
2059
- // allows, and both are awaited together below.
2060
- const run = await runLayoutChain(
2061
- route,
2062
- ctx,
2063
- validatedRetainedIndices(c.req, route, c.params),
2064
- )
2065
- layoutModules = run.modules
2066
- layoutRetained = run.retained
2067
- // The page loader gets the EFFECTIVE search (layout chain + page, page-wins), now that the layout
2068
- // modules are loaded - so `ctx.search` includes a layout's shared keys (`?org`), matching `useSearch`.
2069
- const [pageData] = await Promise.all([
2070
- mod.loader
2071
- ? mod.loader({ ...ctx, search: searchChainOf(run.modules, mod, c.req) })
2072
- : null,
2073
- run.pending, // a non-gate layout loader that rejects must still surface, not go unhandled
2074
- ])
2075
- data = pageData
2076
- layoutData = run.layoutData
2077
- } catch (err) {
2078
- // A terminal-status signal (`notFound()` / `gone()` / `statusPage(n)`) renders a boundary at
2079
- // that status. Checked BEFORE the pass-through below: a signal IS a `Response`, so the order
2080
- // is what keeps a hand-rolled `throw new Response(...)` served verbatim, as it always was.
2081
- if (isStatusSignal(err)) return renderStatusSignal(c.req, err)
2082
- // A thrown `Response` is a control-flow signal (a guard's `redirect(...)`, an explicit error
2083
- // response) - let it propagate to core, which returns it as-is. Real errors render the nearest
2084
- // `_error` boundary, if any; with none, rethrow (unchanged 500 behavior).
2085
- if (err instanceof Response) throw err
2086
- // Let reporting plugins observe the data-layer failure before it's rendered/rethrown/500'd.
2087
- if (options.onLoaderError !== undefined) {
2088
- try {
2089
- options.onLoaderError(err, { request: c.req, params: c.params, route: route.pattern })
2090
- } catch {
2091
- // A faulty reporter must never break error rendering.
2092
- }
2093
- }
2094
- const errorId = boundaryFor(route, err)
2095
- if (errorId === undefined) throw err
2096
- // A soft-nav data fetch can't render a boundary - 500 so the client falls back to a full-page
2097
- // navigation, which lands here as a document and renders the `_error` page.
2098
- if (c.req.headers.get(DATA_HEADER) !== null) {
2099
- return new Response("Internal Server Error", {
2100
- status: 500,
2101
- headers: { "content-type": "text/plain; charset=utf-8" },
2102
- })
2103
- }
2104
- return renderError(route, errorId, withDuplicateInstanceHint(err))
2105
- }
2106
- // A loader may RETURN its control-flow signal instead of throwing it - `return redirect(...)`
2107
- // reads naturally and must not silently serialize the `Response` as loader data. Mirror the
2108
- // catch above exactly: a status signal renders its boundary, any other `Response` (a
2109
- // redirect, a hand-rolled response) passes through to core verbatim - so return and throw
2110
- // are interchangeable.
2111
- if (isStatusSignal(data)) return renderStatusSignal(c.req, data)
2112
- if (data instanceof Response) return data
2113
- // Client-side navigation asks (via the X-Nifra-Data header) for just the loader data - no full
2114
- // document, no layout chain. A route with deferred data streams NDJSON (critical data first,
2115
- // then each deferred value as it settles); otherwise one JSON (the fast path). Same loader,
2116
- // same auth - only the transport differs.
2117
- if (c.req.headers.get(DATA_HEADER) !== null) {
2118
- const pageSplit = prepareDeferred(data)
2119
- const layoutSplits: Array<ReturnType<typeof prepareDeferred>> = []
2120
- let offset = pageSplit.deferred.length
2121
- for (const entry of layoutData ?? []) {
2122
- const split = prepareDeferred(entry, offset)
2123
- layoutSplits.push(split)
2124
- offset += split.deferred.length
2125
- }
2126
- const deferred = [...pageSplit.deferred, ...layoutSplits.flatMap((split) => split.deferred)]
2127
- const payload =
2128
- layoutData === undefined
2129
- ? pageSplit.forClient
2130
- : {
2131
- v: 1 as const,
2132
- data: pageSplit.forClient,
2133
- layoutData: layoutSplits.map((split) => split.forClient),
2134
- retained: layoutRetained,
2135
- }
2136
- // Bare value when there is no layout data - the pre-envelope shape, so a client running older
2137
- // code against a newer server keeps working.
2138
- if (deferred.length === 0) {
2139
- return Response.json(payload ?? null)
2140
- }
2141
- return new Response(ndjsonStream(payload, deferred), {
2142
- headers: { "content-type": "application/x-ndjson; charset=utf-8" },
2143
- })
2144
- }
2145
- const chainLayoutModules = layoutModules ?? (await loadLayoutModules(route))
2146
- const { chain, head } = resolveChainAndHead(chainLayoutModules, mod, {
2147
- data,
2148
- params: c.params,
2149
- origin: originOf(c.req),
2150
- })
2151
- const hydrateRoute = mod.hydrate !== false
2152
- try {
2153
- // `await` so a shell-render throw (renderToStream rejects before any byte) is caught here and
2154
- // can render the `_error` page - not just a loader throw. Mid-stream (post-shell) throws can't
2155
- // be recovered to a full page; the per-adapter client boundary catches client render errors.
2156
- return await renderPageResult({
2157
- adapter,
2158
- chain,
2159
- data,
2160
- head,
2161
- clientEntry,
2162
- routeId: route.id,
2163
- params: c.params,
2164
- path: pathOf(c.req),
2165
- // The effective (layout chain + page) search, matching the page loader's `ctx.search` above and
2166
- // the client mount - so `useSearch` renders SSR-correct and hydrates with no drift. `layoutModules`
2167
- // is loaded by now (the loader try succeeded to reach here).
2168
- search: searchChainOf(layoutModules ?? [], mod, c.req),
2169
- hydrate: hydrateRoute,
2170
- ...(layoutData !== undefined ? { layoutData } : {}),
2171
- ...preloadOf(route.id),
2172
- ...stylesOf(route.id),
2173
- prerenderedPaths: options.prerenderedPaths ?? [],
2174
- ...(mod.revalidate !== undefined ? { revalidate: mod.revalidate } : {}),
2175
- ...(mod.revalidateTags !== undefined ? { revalidateTags: mod.revalidateTags } : {}),
2176
- ...(mod.islandScripts !== undefined ? { islandScripts: mod.islandScripts } : {}),
2177
- ...titleOption,
2178
- ...assemblyCacheFor(mod, chainLayoutModules),
2179
- })
2180
- } catch (err) {
2181
- // Same precedence as the loader catch above - a `meta()` may signal too.
2182
- if (isStatusSignal(err)) return renderStatusSignal(c.req, err)
2183
- if (err instanceof Response) throw err
2184
- // Let reporting plugins observe the data-layer failure before it's rendered/rethrown/500'd.
2185
- if (options.onLoaderError !== undefined) {
2186
- try {
2187
- options.onLoaderError(err, { request: c.req, params: c.params, route: route.pattern })
2188
- } catch {
2189
- // A faulty reporter must never break error rendering.
2190
- }
2191
- }
2192
- const errorId = boundaryFor(route, err)
2193
- if (errorId === undefined) throw err
2194
- return renderError(route, errorId, withDuplicateInstanceHint(err))
2195
- }
2196
- })
2197
-
2198
- // POST runs the route's `action` (mutation). A `Response` return (e.g. a `redirect(...)`)
2199
- // passes straight through; a data return re-renders the page (the loader re-runs for fresh
2200
- // data) with `actionData`. Routes without an action reject POST with 405 - not a stray 404.
2201
- app.register("POST", route.pattern, undefined, async (c: RouteContext) => {
2202
- const mod = await route.load()
2203
- const draft = await draftFlag(c.req)
2204
- if (mod.action === undefined) {
2205
- return new Response("Method Not Allowed", {
2206
- status: 405,
2207
- headers: { allow: "GET", "content-type": "text/plain; charset=utf-8" },
2208
- })
2209
- }
2210
- const actionContext = {
2211
- params: c.params,
2212
- request: c.req,
2213
- req: c.req,
2214
- api,
2215
- env: c.env,
2216
- draft,
2217
- search: loaderSearch(mod.searchSchema, c.req),
2218
- }
2219
- const isDataRequest = c.req.headers.get(DATA_HEADER) !== null
2220
- let layoutModules: LoadedLayoutModules
2221
- let result: unknown
2222
- try {
2223
- // A gate is an authorization boundary for everything beneath its layout, mutations included.
2224
- // Run only gates before the action; ordinary layout data loaders run after a native mutation.
2225
- layoutModules = await runLayoutGates(route, actionContext)
2226
- result = await mod.action(actionContext)
2227
- } catch (err) {
2228
- // A THROWN Response is the same control-flow signal as a returned one (`throw redirect()`
2229
- // in a gate or an action) - route it through the same conversion as the returned-Response
2230
- // branch below, so throw and return are interchangeable on the mutation path too.
2231
- if (err instanceof Response) return actionResponse(err, isDataRequest)
2232
- throw err
2233
- }
2234
- // An action may wrap its data in `revalidate(paths, data)` to declare which routes it changed.
2235
- // Unwrap to the inner data; the paths ride the `X-Nifra-Revalidate` header on the data-mode
2236
- // responses (the client acts on them - a full-page POST re-runs loaders inline, so no header).
2237
- const isRevalidate =
2238
- result !== null && typeof result === "object" && "__nifraRevalidate" in result
2239
- const actionResult = isRevalidate ? (result as RevalidateResult<unknown>).data : result
2240
- const revalidateHeader: Record<string, string> = isRevalidate
2241
- ? { [REVALIDATE_HEADER]: (result as RevalidateResult<unknown>).__nifraRevalidate.join(",") }
2242
- : {}
2243
- if (actionResult instanceof Response) return actionResponse(actionResult, isDataRequest)
2244
- // Client submit wants just the action's data (it revalidates the loader itself); a native
2245
- // form POST re-renders the full page (loader re-runs) with the action data.
2246
- if (isDataRequest) {
2247
- // An action may `defer()` slow parts of its result - stream them (critical data first, then
2248
- // each deferred as it settles) exactly like a loader; a non-deferred action returns one JSON.
2249
- const { forClient, deferred } = prepareDeferred(actionResult)
2250
- if (deferred.length === 0)
2251
- return Response.json(actionResult ?? null, { headers: revalidateHeader })
2252
- return new Response(ndjsonStream(forClient, deferred), {
2253
- headers: { "content-type": "application/x-ndjson; charset=utf-8", ...revalidateHeader },
2254
- })
2255
- }
2256
- // Derived once and shared: the loader's `ctx.search` and the render's `RenderProps.search` are the
2257
- // SAME effective (layout chain + page) value, and the client mount rebuilds it identically. The
2258
- // layout modules are already loaded (the action ran through their gates above).
2259
- const search = searchChainOf(layoutModules, mod, c.req)
2260
- const data = mod.loader
2261
- ? await mod.loader({
2262
- params: c.params,
2263
- request: c.req,
2264
- req: c.req,
2265
- api,
2266
- env: c.env,
2267
- draft,
2268
- search,
2269
- })
2270
- : null
2271
- const { chain, head } = resolveChainAndHead(layoutModules, mod, {
2272
- data,
2273
- params: c.params,
2274
- origin: originOf(c.req),
2275
- })
2276
- const hydrateRoute = mod.hydrate !== false
2277
- // A full-page POST streams the action's `defer()`'d parts mid-document behind `<Await>` too -
2278
- // `renderPage` splits `actionData` like loader data (works with JS off; hydrates after).
2279
- return renderPageResult({
2280
- adapter,
2281
- chain,
2282
- data,
2283
- actionData: actionResult,
2284
- head,
2285
- clientEntry,
2286
- routeId: route.id,
2287
- params: c.params,
2288
- path: pathOf(c.req),
2289
- search,
2290
- hydrate: hydrateRoute,
2291
- ...preloadOf(route.id),
2292
- ...stylesOf(route.id),
2293
- prerenderedPaths: options.prerenderedPaths ?? [],
2294
- ...titleOption,
2295
- })
2296
- })
2297
- }
2298
-
2299
- // Register llms.txt & llms-full.txt
2300
- const llmsOptions = { includeLocalGuidelines: options.publishLocalGuidelines === true }
2301
- app.register("GET", "/llms.txt", undefined, async () => {
2302
- const text = await generateLlmsTxt(false, manifest.routes, api, llmsOptions)
2303
- return new Response(text, {
2304
- headers: { "content-type": "text/plain; charset=utf-8" },
2305
- })
2306
- })
2307
-
2308
- app.register("GET", "/llms-full.txt", undefined, async () => {
2309
- const text = await generateLlmsTxt(true, manifest.routes, api, llmsOptions)
2310
- return new Response(text, {
2311
- headers: { "content-type": "text/plain; charset=utf-8" },
2312
- })
2313
- })
2314
-
2315
- // Wildcard catch-all: unmatched paths render `_404` (404), or a plain text 404 if absent.
2316
- app.register("GET", "/*", undefined, (c: RouteContext) => renderNotFound(pathOf(c.req)))
2317
-
2318
- return app
2319
- }
2320
-
2321
- export interface GenerateClientEntryOptions {
2322
- /**
2323
- * Module specifier for the adapter's client runtime, e.g. `"@nifrajs/web-solid/client"`.
2324
- *
2325
- * **Contract:** the module MUST export `mountRouter({ router, routes, container })`. The generated
2326
- * bootstrap imports the specifier and calls it - so a self-executing entry that mounts on import
2327
- * builds cleanly and then does nothing, which is the trap this contract exists to name. The type is
2328
- * a bare `string` because a specifier is resolved by the bundler, not the type system, so the
2329
- * requirement is enforced by the bootstrap instead: it throws immediately, naming this module and
2330
- * the missing export, rather than failing later as `mountRouter is not a function`.
2331
- */
2332
- readonly clientModule: string
2333
- /** Turn a route/layout source file (relative to the routes dir) into an import specifier. */
2334
- readonly resolve: (file: string) => string
2335
- }
2336
-
2337
- /**
2338
- * Codegen: emit a client-entry module (as source) that lazily imports each route's layout chain
2339
- * (so `Bun.build` with `splitting` code-splits one chunk per route), builds a `patterns` list,
2340
- * then creates the agnostic router store (with a `loadModule` hook), installs history + form
2341
- * interception, loads the initial route's chunk, and hydrates the adapter's stateful Router. The
2342
- * initial route is derived from the URL (falling back to the server-injected route id, e.g.
2343
- * `_404`), so after hydration the Router owns navigation and swaps routes without full reloads.
2344
- * Bun has no `import.meta.glob`, so file-based routing needs this. Write the result to a file and
2345
- * bundle it with `buildClient` / `Bun.build` (+ the adapter's transform).
2346
- */
2347
- export function generateClientEntry(
2348
- manifest: Manifest,
2349
- options: GenerateClientEntryOptions,
2350
- ): string {
2351
- const { clientModule, resolve } = options
2352
-
2353
- const loaderRows: string[] = []
2354
- const patternRows: string[] = []
2355
- const statusRoutes: Record<number, string> = {}
2356
- // Routes whose loader appends a nearest `_error` module (LAST) - the client wraps the page in the
2357
- // adapter's `errorBoundary(fallback)` for these, so a client render error shows the `_error` UI.
2358
- const errorRouteIds: string[] = []
2359
- // Lazy loader returns the raw modules (for both the component chain + the page's `meta` export).
2360
- const lazyLoader = (files: readonly string[]): string => {
2361
- const imports = files.map((f) => `import(${jsStringLiteral(resolve(f))})`).join(", ")
2362
- return `() => Promise.all([${imports}])`
2363
- }
2364
- for (const route of manifest.routes) {
2365
- // layoutIds only reference layouts present in the manifest (buildManifest invariant).
2366
- const files = [
2367
- ...route.layoutIds.map((id) => (manifest.layouts[id] as LayoutEntry).file),
2368
- route.file,
2369
- ]
2370
- // Append the nearest `_error` file LAST, so loadModule can pull it off the tail and wrap the page.
2371
- const nearestErrorId = route.errorIds?.at(-1)
2372
- const errorFile =
2373
- nearestErrorId === undefined ? undefined : manifest.errors?.[nearestErrorId]?.file
2374
- if (errorFile !== undefined) {
2375
- files.push(errorFile)
2376
- errorRouteIds.push(route.id)
2377
- }
2378
- loaderRows.push(` ${JSON.stringify(route.id)}: ${lazyLoader(files)},`)
2379
- patternRows.push(
2380
- ` { routeId: ${JSON.stringify(route.id)}, pattern: ${JSON.stringify(route.pattern)} },`,
2381
- )
2382
- }
2383
- if (manifest.notFound !== undefined) {
2384
- loaderRows.push(` "_404": ${lazyLoader([manifest.notFound.file])},`)
2385
- statusRoutes[404] = "_404"
2386
- }
2387
- for (const [status, entry] of Object.entries(manifest.statusPages ?? {})) {
2388
- const routeId = `_${status}`
2389
- loaderRows.push(` ${JSON.stringify(routeId)}: ${lazyLoader([entry.file])},`)
2390
- statusRoutes[Number(status)] = routeId
2391
- }
2392
-
2393
- return `${[
2394
- // `/client`, never the root: the root's graph carries the server (renderPage, the static-file
2395
- // server), and Vite's dev server evaluates what it is given instead of tree-shaking it.
2396
- 'import { createClientRouter, createMatcher, mergeHeads, resolveMeta } from "@nifrajs/web/client"',
2397
- 'import { applyHead, installForms, installHistory, signalHydrated } from "@nifrajs/web/client"',
2398
- // Namespace import: `errorBoundary` is optional (an adapter may not export it). A namespace member
2399
- // access yields `undefined` if absent - unlike a named import, which would be a link error.
2400
- `import * as __adapter from ${JSON.stringify(clientModule)}`,
2401
- "const { mountRouter } = __adapter",
2402
- // The assurance hook is optional: ordinary client entries pay only for the namespace lookup, while
2403
- // hydration runners get a runtime identity from the exact adapter module that mounted the page. The
2404
- // registry is token-only and lives on a Symbol.for key so it cannot collide with app data.
2405
- "const __hydrationHook = __adapter.hydrationAssuranceHook",
2406
- 'if (__hydrationHook && typeof __hydrationHook.runtimeIdentity === "function") {',
2407
- ' const __runtimeKey = Symbol.for("nifra.hydration.runtime")',
2408
- " const __runtimeState = globalThis[__runtimeKey]",
2409
- " const __identities = __runtimeState && Array.isArray(__runtimeState.identities) ? __runtimeState.identities : []",
2410
- " globalThis[__runtimeKey] = { framework: __hydrationHook.framework, identities: [...__identities, __hydrationHook.runtimeIdentity()] }",
2411
- "}",
2412
- // The `clientModule` contract is a string specifier, so nothing type-checks that the module it
2413
- // names actually exports `mountRouter`. Without this the miss surfaces as
2414
- // "mountRouter is not a function" from inside a bundled chunk, at first paint, naming neither the
2415
- // module nor the requirement - a self-executing entry passes every build and fails only here.
2416
- `if (typeof mountRouter !== "function") throw new Error(${JSON.stringify(
2417
- `[nifra/web] clientModule ${JSON.stringify(clientModule)} does not export \`mountRouter\`. ` +
2418
- "A client module must export `mountRouter({ router, routes, container })` - it is called by " +
2419
- "the generated bootstrap, so a self-executing entry will not work. Use your adapter's " +
2420
- '`/client` entry (e.g. "@nifrajs/web-react/client"), or re-export mountRouter from it.',
2421
- )})`,
2422
- "const errorBoundary = __adapter.errorBoundary",
2423
- // A hot update that the framework cannot actually apply must end in a reload, not in nothing.
2424
- //
2425
- // Bun's dev server applies React Fast Refresh to JSX modules. For React that patches the component
2426
- // and preserves state. For Preact it does not - the module still LOOKS Fast-Refresh-able, so the
2427
- // update is accepted and then swallowed: `bun:beforeUpdate`/`bun:afterUpdate` both fire, the server
2428
- // logs a rebuild, and the page silently keeps rendering the old code. An edit that appears to do
2429
- // nothing is the worst failure mode in a dev loop - worse than a reload, because there is no signal
2430
- // to act on. An adapter that knows its framework is in that position says so, and the entry turns
2431
- // the swallowed update into an honest full reload.
2432
- 'if (import.meta.hot && __adapter.hotUpdateNeedsReload) import.meta.hot.on("bun:afterUpdate", () => location.reload())',
2433
- `const errorRouteIds = new Set(${JSON.stringify(errorRouteIds)})`,
2434
- // Each route is a lazy loader: dynamic imports → Bun.build (splitting) emits one chunk per
2435
- // route, shared layouts/deps deduped into shared chunks, so a route's code loads only when
2436
- // visited. loadModule caches the [layouts…, page] component chain + the chain's meta list per id.
2437
- "const loaders = {",
2438
- ...loaderRows,
2439
- "}",
2440
- "const chains = {}",
2441
- "const metas = {}",
2442
- // routeId → the page module's `searchSchema` export (or undefined). Populated lazily with
2443
- // chains/metas so the mount can derive this route's typed `search` from the URL, matching the SSR.
2444
- "const searchSchemas = {}",
2445
- // routeId → the page's client-only search keys (`searchClientKeys`, or `[]`). The router reads this
2446
- // by reference to decide when a same-route search change can skip the loader fetch (re-render only).
2447
- "const searchClientKeys = {}",
2448
- "const loadModule = async (id) => {",
2449
- " if (chains[id]) return",
2450
- " const mods = await loaders[id]()",
2451
- // For an error route the `_error` module is appended LAST: wrap the page (now second-to-last) in
2452
- // the adapter's boundary so a client render error renders the `_error` UI. DOM-transparent, so the
2453
- // hydrated tree matches the SSR markup (which has no boundary). Falls back to the plain chain when
2454
- // the adapter has no `errorBoundary`.
2455
- // `metas[id]` is the chain's `meta` exports in head order (outermost layout → … → page), so a
2456
- // soft-nav merges the layout chain's head with the page's - matching the SSR `<head>` (sitewide
2457
- // layout tags persist across client navigation, no flash of page-only head). `_error` carries no
2458
- // head (a terminal boundary), so it's excluded from the meta list for error routes.
2459
- " if (errorBoundary && errorRouteIds.has(id)) {",
2460
- " const fallback = mods[mods.length - 1].default",
2461
- " const page = mods[mods.length - 2].default",
2462
- " const layouts = mods.slice(0, mods.length - 2).map((m) => m.default)",
2463
- " chains[id] = [...layouts, errorBoundary(fallback), page]",
2464
- " metas[id] = mods.slice(0, mods.length - 1).map((m) => m.meta)",
2465
- // The search-schema CHAIN is the layout modules + page (all but the appended `_error`), so a layout's
2466
- // `searchSchema` merges with the page's. Client keys come from the page (second-to-last).
2467
- " searchSchemas[id] = mods.slice(0, mods.length - 1).map((m) => m.searchSchema)",
2468
- " searchClientKeys[id] = mods[mods.length - 2].searchClientKeys ?? []",
2469
- " } else {",
2470
- " chains[id] = mods.map((m) => m.default)",
2471
- " metas[id] = mods.map((m) => m.meta)",
2472
- // The chain is every module (layouts + page); client keys come from the page (the last module).
2473
- " searchSchemas[id] = mods.map((m) => m.searchSchema)",
2474
- " searchClientKeys[id] = mods[mods.length - 1].searchClientKeys ?? []",
2475
- " }",
2476
- "}",
2477
- "const patterns = [",
2478
- ...patternRows,
2479
- "]",
2480
- // Derive the initial route from the URL (correct on refresh/deep-link); fall back to the
2481
- // server-injected route id for non-pattern routes (e.g. _404, which matches nothing).
2482
- "const matched = createMatcher(patterns)(location.pathname)",
2483
- // Map any `{__nifra_deferred: id}` placeholder in the SSR data to the registry's promise, so the
2484
- // component receives real promises to `<Await>` (a no-op when a page has no deferred data).
2485
- MAP_DEFERRED_SOURCE,
2486
- "const initial = {",
2487
- ` routeId: matched ? matched.routeId : (window.${ROUTE_GLOBAL} ?? ""),`,
2488
- " params: matched ? matched.params : {},",
2489
- // pathname + search (NOT just pathname): the SSR render threads `pathname+search` into
2490
- // `useLocation`/`useSearchParams`, so the hydrating initial state must carry the query too or a
2491
- // page reading the search string would hydrate-mismatch. The #hash is client-only (never SSR'd).
2492
- " path: location.pathname + location.search,",
2493
- ` data: mapDeferred(window.${DATA_GLOBAL}),`,
2494
- // Undefined on a page-only app, which is exactly what the router treats as "no layout data".
2495
- ` layoutData: window.${LAYOUT_DATA_GLOBAL} && window.${LAYOUT_DATA_GLOBAL}.map(mapDeferred),`,
2496
- // actionData (only set after a form POST) is in the initial state so the binding hydrates
2497
- // consistently with the server-rendered markup; mapped through `mapDeferred` too so a deferred
2498
- // action's placeholders become registry markers (a no-op when the action didn't defer).
2499
- ` actionData: mapDeferred(window.${ACTION_GLOBAL}),`,
2500
- " pending: false,",
2501
- "}",
2502
- `const statusRoutes = ${JSON.stringify(statusRoutes)}`,
2503
- "const router = createClientRouter({ patterns, initial, loadModule, statusRoutes, searchClientKeys })",
2504
- "installHistory(router)",
2505
- "installForms(router)",
2506
- // The container is found in the DOM, not baked in. `rootId` is a per-render option and this entry
2507
- // is a per-build artifact, so a hardcoded id is a guess: `renderPage({ rootId: "app" })` produced a
2508
- // perfect document that hydrated NOTHING, with no diagnostic, because the missing `#root` was
2509
- // swallowed by an `if (root)`. `renderPage` marks a custom container with `ROOT_ATTRIBUTE`; the
2510
- // default `#root` it leaves unmarked, which is what the fallback is for.
2511
- `const root = document.querySelector("body > div[${ROOT_ATTRIBUTE}]") ?? document.getElementById("root")`,
2512
- // Loud, because there is no recoverable case: this entry ships only in a document `renderPage`
2513
- // opened a container in, so reaching here means the document is not the one it was built for.
2514
- `if (!root) throw new Error(${JSON.stringify(
2515
- "[nifra/web] no hydration container found. The generated bootstrap mounts into the element " +
2516
- `renderPage opened the app in - the one marked \`${ROOT_ATTRIBUTE}\` when a custom \`rootId\` ` +
2517
- "is set, `#root` otherwise - and this document has neither. If you emit the document yourself, " +
2518
- 'keep `<div id="root">` around the SSR markup.',
2519
- )})`,
2520
- // Load the initial route's chunk, then hydrate the Router (chain is cached). The initial head
2521
- // is server-rendered; subsequent navigations update it from the matched route's meta + data.
2522
- "loadModule(initial.routeId).then(() => {",
2523
- " mountRouter({ router, routes: chains, searchSchemas, container: root })",
2524
- // Next frame: the adapter has committed its initial hydration, so handlers are attached. Flip the
2525
- // document to interactive (`data-nifra-hydrated` + `nifra:hydrated`) for apps to gate pre-hydration UI.
2526
- " requestAnimationFrame(signalHydrated)",
2527
- " router.subscribe(() => {",
2528
- " const s = router.snapshot()",
2529
- // Merge the matched route's chain meta (layouts→page) into one head - same contract as SSR.
2530
- " if (!s.pending) {",
2531
- // `origin: location.origin` matches the SSR `originOf(req)` (both are `URL.origin` for the same
2532
- // page URL), so a soft-nav re-resolves the SAME absolute canonical/og:url - no head drift.
2533
- " const args = { data: s.data, params: s.params, origin: location.origin }",
2534
- " applyHead(mergeHeads((metas[s.routeId] ?? [undefined]).map((m) => resolveMeta(m, args))))",
2535
- " }",
2536
- " })",
2537
- "})",
2538
- ].join("\n")}\n`
2539
- }
2540
-
2541
- export interface GenerateRouteSearchTypesOptions {
2542
- /** Turn a route source file into a module specifier for a `typeof import(...)` type - the same contract
2543
- * as `generateClientEntry`'s `resolve`, but WITHOUT a file extension (a `.d.ts` imports a module, not a
2544
- * path). Relative to wherever the emitted `.d.ts` is written. */
2545
- readonly resolve: (file: string) => string
2546
- /** The module whose `RouteSearch` interface is augmented (default `"@nifrajs/web"`). Every adapter's
2547
- * `NavigateTarget` reads `@nifrajs/web`'s `RouteSearch`, so the default types `navigate` on all of them. */
2548
- readonly module?: string
2549
- }
2550
-
2551
- /**
2552
- * Codegen: emit a `.d.ts` that types cross-route `navigate({ to, search })` against each route's
2553
- * `searchSchema`. It augments the {@link RouteSearch} map with `"<pattern>": SearchOf<typeof import(...)>`
2554
- * for every **static** route (one with no `:param`/`*` segment - a concrete `to` a caller can pass; a
2555
- * dynamic route's concrete path can't match its pattern key, so those keep the loose object form). Written
2556
- * by `nifra sync-routes` next to the route tree and included in the app's `tsconfig`; because it is
2557
- * regenerated from the route files, a `navigate` whose `search` no longer matches the route's schema
2558
- * becomes a `tsc` error - the same drift guarantee as nifra's typed client, no hand-maintained map.
2559
- */
2560
- export function generateRouteSearchTypes(
2561
- manifest: Manifest,
2562
- options: GenerateRouteSearchTypesOptions,
2563
- ): string {
2564
- const { resolve, module = "@nifrajs/web" } = options
2565
- // Static routes only (no `:param` / `*` catch-all): their pattern IS a concrete `to`. Sorted for stable
2566
- // output; a dynamic route falls through to the loose `{ to: string; search?: Record<...> }` form.
2567
- const entries = manifest.routes
2568
- .filter((route) => !/[:*]/.test(route.pattern))
2569
- .map((route) => [route.pattern, resolve(route.file)] as const)
2570
- .sort((a, b) => (a[0] < b[0] ? -1 : 1))
2571
- .map(
2572
- ([pattern, spec]) =>
2573
- ` ${JSON.stringify(pattern)}: SearchOf<typeof import(${JSON.stringify(spec)})>`,
2574
- )
2575
- return `${[
2576
- "// GENERATED by @nifrajs/web generateRouteSearchTypes - typed cross-route navigate({ to, search }).",
2577
- "// Regenerated from the route files; a stale navigate search shape becomes a tsc error. Do not edit.",
2578
- 'import type { SearchOf } from "@nifrajs/web"',
2579
- `declare module ${JSON.stringify(module)} {`,
2580
- " interface RouteSearch {",
2581
- ...entries,
2582
- " }",
2583
- "}",
2584
- "export {}",
2585
- ].join("\n")}\n`
2586
- }
2587
-
2588
- export interface GenerateServerManifestOptions {
2589
- /** Turn a route/layout source file (relative to the routes dir) into an import specifier -
2590
- * same contract as `generateClientEntry`'s `resolve`. */
2591
- readonly resolve: (file: string) => string
2592
- /** The content-hashed client entry URL (from `buildClient`'s manifest), **baked** into the emitted
2593
- * module - a disk-less worker can't read `manifest.json` at runtime. */
2594
- readonly clientEntry: string
2595
- /** The app's aggregate stylesheet URLs (`buildClient`'s `BuildManifest.css`) - baked as
2596
- * `export const styles` so the server entry can hand them to `createWebApp` (→ `<link rel="stylesheet">`
2597
- * in `<head>`). Without this the built SSR page ships no CSS link and renders unstyled. */
2598
- readonly styles?: readonly string[] | undefined
2599
- /** Per-route stylesheet URLs (`buildClient`'s `BuildManifest.routeStyles`) - baked as
2600
- * `export const routeStyles` so a page links only the CSS its route chain uses. */
2601
- readonly routeStyles?: Readonly<Record<string, readonly string[]>> | undefined
2602
- /** Emit **lazy** per-route loaders (`() => import("./routes/x")`, a static specifier) instead of
2603
- * eager `import * as`, so a bundler with code-splitting emits one chunk per route - loaded on the
2604
- * first request to it, not all at boot (smaller cold-start parse). Default `false` (eager). Both
2605
- * modes are fs-free with statically-analyzable specifiers; only the *when* differs. */
2606
- readonly lazy?: boolean
2607
- }
2608
-
2609
- /**
2610
- * Codegen: emit a **server manifest** module (as source) for disk-less edge runtimes (Cloudflare
2611
- * Workers, …) - and, with a `target`, any portable server bundle. `discoverRoutes` scans `node:fs`
2612
- * and dynamic-imports each route by a *runtime* path - neither exists on workerd. This instead emits
2613
- * **statically-analyzable** imports of every route/layout/`_error`/terminal status page (so the bundler includes them) and
2614
- * rebuilds the manifest with `buildManifest` - the SAME pure logic `discoverRoutes` feeds, so patterns
2615
- * + layout chains are identical. Eager (`import * as`) by default; `lazy` emits `() => import(...)` so
2616
- * a code-splitting bundler chunks per route. The emitted module exports `manifest` (consumed by
2617
- * `createWebApp`, unchanged) + `clientEntry` (baked). Write it to a file and bundle it into the worker
2618
- * entry (see `buildServer` in `@nifrajs/web/build`).
2619
- */
2620
- // Route source files are emitted as EXTENSIONLESS import specifiers. An explicit `.tsx`/`.ts` in an
2621
- // import is a hard error under a plain `tsc` (TS5097) unless `allowImportingTsExtensions` is set - which
2622
- // only the nifra template tsconfig does - so the generated manifest failed a bare `tsc` with one error
2623
- // per route. Every bundler and `moduleResolution` still resolves the extensionless form to the source
2624
- // file, so dropping the extension costs nothing at build time and makes the output portable. Only a
2625
- // known TS/JS source extension is stripped; the map KEY keeps its extension (it is the route identifier
2626
- // `buildManifest` matches, not an import path).
2627
- const SOURCE_EXTENSION = /\.(?:[mc]?tsx?|[mc]?jsx?)$/
2628
- function moduleSpecifier(resolved: string): string {
2629
- return resolved.replace(SOURCE_EXTENSION, "")
2630
- }
2631
-
2632
- export function generateServerManifest(
2633
- manifest: Manifest,
2634
- options: GenerateServerManifestOptions,
2635
- ): string {
2636
- const { resolve, clientEntry, styles, routeStyles, lazy = false } = options
2637
- // Every unique source file in the manifest (routes + layouts + error/status pages), sorted for stable output.
2638
- const files = [
2639
- ...new Set([
2640
- ...manifest.routes.map((r) => r.file),
2641
- ...Object.values(manifest.layouts).map((l) => l.file),
2642
- ...Object.values(manifest.errors ?? {}).map((e) => e.file),
2643
- ...(manifest.notFound ? [manifest.notFound.file] : []),
2644
- ...Object.values(manifest.statusPages ?? {}).map((page) => page.file),
2645
- ]),
2646
- ].sort()
2647
- const header = [
2648
- "// GENERATED by @nifrajs/web generateServerManifest - route manifest for the disk-less edge",
2649
- "// (no filesystem; route imports are static specifiers the bundler resolves). buildManifest is",
2650
- "// the same pure logic discoverRoutes feeds, so patterns + layout chains match exactly.",
2651
- 'import { buildManifest, type RouteModule } from "@nifrajs/web"',
2652
- ]
2653
- const clientEntryLine = `export const clientEntry = ${JSON.stringify(clientEntry)}`
2654
- // Baked stylesheet URLs so the server entry can pass them to createWebApp → <link rel="stylesheet">.
2655
- // Always emitted (default empty) so consumers can `import { styles, routeStyles }` unconditionally.
2656
- const stylesLine = `export const styles = ${JSON.stringify(styles ?? [])}`
2657
- const routeStylesLine = `export const routeStyles = ${JSON.stringify(routeStyles ?? {})}`
2658
- if (lazy) {
2659
- // Lazy: `() => import("./routes/x")` per route (static specifier → one chunk per route under a
2660
- // code-splitting bundler, loaded on first request). The map keys are the route-relative paths
2661
- // `buildManifest` expects; the importer it builds calls the per-file loader.
2662
- const loaders = files.map(
2663
- (file) =>
2664
- ` ${jsStringLiteral(file)}: () => import(${jsStringLiteral(moduleSpecifier(resolve(file)))}),`,
2665
- )
2666
- return `${[
2667
- ...header,
2668
- "const loaders: Record<string, () => Promise<RouteModule>> = {",
2669
- ...loaders,
2670
- "}",
2671
- clientEntryLine,
2672
- stylesLine,
2673
- routeStylesLine,
2674
- "export const manifest = buildManifest(Object.keys(loaders), (file) => () => loaders[file]())",
2675
- ].join("\n")}\n`
2676
- }
2677
- // Eager: `import * as` per route (all bundled into the entry, parsed at boot). Index-based
2678
- // identifiers are collision-proof regardless of filename.
2679
- const imports = files.map(
2680
- (file, i) => `import * as m${i} from ${JSON.stringify(moduleSpecifier(resolve(file)))}`,
2681
- )
2682
- const entries = files.map((file, i) => ` ${JSON.stringify(file)}: m${i},`)
2683
- return `${[
2684
- ...header,
2685
- ...imports,
2686
- "const modules: Record<string, RouteModule> = {",
2687
- ...entries,
2688
- "}",
2689
- clientEntryLine,
2690
- stylesLine,
2691
- routeStylesLine,
2692
- "export const manifest = buildManifest(Object.keys(modules), (file) => () => Promise.resolve(modules[file]))",
2693
- ].join("\n")}\n`
2694
- }
2695
-
2696
- /**
2697
- * The two file-name conventions that decide what never reaches a browser: a `*.server` module is
2698
- * EMPTIED in the client build, a `*.fn` module is REPLACED with client stubs.
2699
- *
2700
- * Exported because more than the bundlers need them. `nifra dev --bun` cannot transform (Bun's dev
2701
- * bundler takes no plugins) so it must REFUSE instead, and a refusal driven by its own hand-written
2702
- * glob drifts from the transform - which is how `.fn.mts` came to be stubbed by both build pipelines
2703
- * and waved through by the guard that exists to stop it leaking. Anything deciding "is this module
2704
- * server-only" should import the matcher rather than re-encode it.
2705
- */
2706
- export { SERVER_FN_MODULE, SERVER_ONLY_MODULE } from "./internal/server-boundary.ts"