@warlock.js/web 5.2.0 → 5.2.2

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 (201) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/esm/build/contribution.d.mts +1 -1
  3. package/esm/build/contribution.mjs +1 -1
  4. package/esm/build/contribution.mjs.map +1 -1
  5. package/esm/build/discover-pages.mjs +1 -1
  6. package/esm/build/discover-pages.mjs.map +1 -1
  7. package/esm/build/generate-client-registry.mjs +1 -1
  8. package/esm/build/generate-client-registry.mjs.map +1 -1
  9. package/esm/build/generate-pages-barrel.mjs +1 -1
  10. package/esm/build/generate-pages-barrel.mjs.map +1 -1
  11. package/esm/build/page-default-export.mjs +1 -1
  12. package/esm/build/page-default-export.mjs.map +1 -1
  13. package/esm/build/page-routes-manifest.mjs +1 -1
  14. package/esm/build/page-routes-manifest.mjs.map +1 -1
  15. package/esm/build/public-files.mjs +1 -1
  16. package/esm/build/public-files.mjs.map +1 -1
  17. package/esm/build/read-route-exports.mjs +1 -1
  18. package/esm/build/read-route-exports.mjs.map +1 -1
  19. package/esm/client/build-hydrated-tree.mjs +1 -1
  20. package/esm/client/build-hydrated-tree.mjs.map +1 -1
  21. package/esm/client/hydrate-page.mjs +1 -1
  22. package/esm/client/hydrate-page.mjs.map +1 -1
  23. package/esm/client/navigation/current-route.d.mts +1 -1
  24. package/esm/client/navigation/current-route.mjs +1 -1
  25. package/esm/client/navigation/current-route.mjs.map +1 -1
  26. package/esm/client/navigation/fetch-page-data.mjs +1 -1
  27. package/esm/client/navigation/fetch-page-data.mjs.map +1 -1
  28. package/esm/client/navigation/navigation-root.mjs +1 -1
  29. package/esm/client/navigation/navigation-root.mjs.map +1 -1
  30. package/esm/client/navigation/prefetch.mjs +1 -1
  31. package/esm/client/navigation/prefetch.mjs.map +1 -1
  32. package/esm/client/navigation/refresh.d.mts +1 -1
  33. package/esm/client/navigation/refresh.mjs +1 -1
  34. package/esm/client/navigation/refresh.mjs.map +1 -1
  35. package/esm/client/navigation/scroll-to-fragment.mjs +1 -1
  36. package/esm/client/navigation/scroll-to-fragment.mjs.map +1 -1
  37. package/esm/client/navigation/verbs.d.mts +1 -1
  38. package/esm/client/navigation/verbs.mjs +1 -1
  39. package/esm/client/navigation/verbs.mjs.map +1 -1
  40. package/esm/client/runtime/manifest.d.mts +1 -1
  41. package/esm/client/runtime/manifest.mjs +1 -1
  42. package/esm/client/runtime/manifest.mjs.map +1 -1
  43. package/esm/client/runtime/matcher.d.mts +1 -1
  44. package/esm/client/runtime/matcher.mjs +1 -1
  45. package/esm/client/runtime/matcher.mjs.map +1 -1
  46. package/esm/client/runtime/types.d.mts +1 -1
  47. package/esm/components/default-app.mjs +1 -1
  48. package/esm/components/default-app.mjs.map +1 -1
  49. package/esm/components/document-context.d.mts +1 -1
  50. package/esm/components/document-context.mjs +1 -1
  51. package/esm/components/document-context.mjs.map +1 -1
  52. package/esm/components/head.d.mts +1 -1
  53. package/esm/components/head.mjs +1 -1
  54. package/esm/components/head.mjs.map +1 -1
  55. package/esm/components/link.d.mts +1 -1
  56. package/esm/components/link.mjs +1 -1
  57. package/esm/components/link.mjs.map +1 -1
  58. package/esm/components/scripts.d.mts +1 -1
  59. package/esm/components/scripts.mjs +1 -1
  60. package/esm/components/scripts.mjs.map +1 -1
  61. package/esm/context.d.mts +1 -1
  62. package/esm/hydration/index.mjs +1 -1
  63. package/esm/hydration/index.mjs.map +1 -1
  64. package/esm/hydration-payload.mjs +1 -1
  65. package/esm/hydration-payload.mjs.map +1 -1
  66. package/esm/index.d.mts +1 -1
  67. package/esm/loaders.d.mts +1 -1
  68. package/esm/metadata.d.mts +1 -1
  69. package/esm/metadata.mjs +1 -1
  70. package/esm/metadata.mjs.map +1 -1
  71. package/esm/props.d.mts +1 -1
  72. package/esm/route.d.mts +1 -1
  73. package/esm/routing/compose-route-path.d.mts +1 -1
  74. package/esm/routing/compose-route-path.mjs +1 -1
  75. package/esm/routing/compose-route-path.mjs.map +1 -1
  76. package/esm/routing/data-request.mjs +1 -1
  77. package/esm/routing/data-request.mjs.map +1 -1
  78. package/esm/routing/filesystem-route.mjs +1 -1
  79. package/esm/routing/filesystem-route.mjs.map +1 -1
  80. package/esm/routing/layout-policy.mjs +1 -1
  81. package/esm/routing/layout-policy.mjs.map +1 -1
  82. package/esm/routing/navigator.mjs +1 -1
  83. package/esm/routing/navigator.mjs.map +1 -1
  84. package/esm/routing/query-string.d.mts +1 -1
  85. package/esm/routing/query-string.mjs +1 -1
  86. package/esm/routing/query-string.mjs.map +1 -1
  87. package/esm/routing/route-identity.mjs +1 -1
  88. package/esm/routing/route-identity.mjs.map +1 -1
  89. package/esm/routing/route-table.d.mts +1 -1
  90. package/esm/routing/route-table.mjs +1 -1
  91. package/esm/routing/route-table.mjs.map +1 -1
  92. package/esm/routing/router-events.d.mts +1 -1
  93. package/esm/routing/router-events.mjs +1 -1
  94. package/esm/routing/router-events.mjs.map +1 -1
  95. package/esm/routing/url-fragment.mjs +1 -1
  96. package/esm/routing/url-fragment.mjs.map +1 -1
  97. package/esm/runtime/register-modules.d.mts +1 -1
  98. package/esm/runtime/register-modules.mjs +1 -1
  99. package/esm/runtime/register-modules.mjs.map +1 -1
  100. package/esm/server/build-hydration-payload.mjs +1 -1
  101. package/esm/server/build-hydration-payload.mjs.map +1 -1
  102. package/esm/server/client-asset-url-prefix.d.mts +1 -1
  103. package/esm/server/client-asset-url-prefix.mjs +1 -1
  104. package/esm/server/client-asset-url-prefix.mjs.map +1 -1
  105. package/esm/server/create-page-module-loader.d.mts +1 -1
  106. package/esm/server/create-page-module-loader.mjs +1 -1
  107. package/esm/server/create-page-module-loader.mjs.map +1 -1
  108. package/esm/server/create-page-route-handler.d.mts +1 -1
  109. package/esm/server/create-page-route-handler.mjs +1 -1
  110. package/esm/server/create-page-route-handler.mjs.map +1 -1
  111. package/esm/server/dev-server.mjs +1 -1
  112. package/esm/server/dev-server.mjs.map +1 -1
  113. package/esm/server/error-page.d.mts +1 -1
  114. package/esm/server/error-page.mjs +1 -1
  115. package/esm/server/error-page.mjs.map +1 -1
  116. package/esm/server/execute-page-request.d.mts +1 -1
  117. package/esm/server/execute-page-request.mjs +1 -1
  118. package/esm/server/execute-page-request.mjs.map +1 -1
  119. package/esm/server/execute-page-request.types.d.mts +1 -1
  120. package/esm/server/hydration-client-url.d.mts +1 -1
  121. package/esm/server/hydration-client-url.mjs +1 -1
  122. package/esm/server/hydration-client-url.mjs.map +1 -1
  123. package/esm/server/install-page-routes-from-manifest.d.mts +1 -1
  124. package/esm/server/install-page-routes-from-manifest.mjs +1 -1
  125. package/esm/server/install-page-routes-from-manifest.mjs.map +1 -1
  126. package/esm/server/install-page-routes.d.mts +1 -1
  127. package/esm/server/install-page-routes.mjs +1 -1
  128. package/esm/server/install-page-routes.mjs.map +1 -1
  129. package/esm/server/install-production-page-routes.mjs +1 -1
  130. package/esm/server/install-production-page-routes.mjs.map +1 -1
  131. package/esm/server/match-page-route.mjs +1 -1
  132. package/esm/server/match-page-route.mjs.map +1 -1
  133. package/esm/server/not-found-page.d.mts +1 -1
  134. package/esm/server/not-found-page.mjs +1 -1
  135. package/esm/server/not-found-page.mjs.map +1 -1
  136. package/esm/server/page-context.d.mts +1 -1
  137. package/esm/server/page-context.mjs +1 -1
  138. package/esm/server/page-context.mjs.map +1 -1
  139. package/esm/server/page-file-change.mjs +1 -1
  140. package/esm/server/page-file-change.mjs.map +1 -1
  141. package/esm/server/page-manifest.d.mts +1 -1
  142. package/esm/server/page-manifest.mjs +1 -1
  143. package/esm/server/page-manifest.mjs.map +1 -1
  144. package/esm/server/page-render-bundle.mjs +1 -1
  145. package/esm/server/page-render-bundle.mjs.map +1 -1
  146. package/esm/server/page-route-reload.mjs +1 -1
  147. package/esm/server/page-route-reload.mjs.map +1 -1
  148. package/esm/server/register-production-public-files.mjs +1 -1
  149. package/esm/server/register-production-public-files.mjs.map +1 -1
  150. package/esm/server/render-page.d.mts +1 -1
  151. package/esm/server/render-page.mjs +1 -1
  152. package/esm/server/render-page.mjs.map +1 -1
  153. package/esm/server/resolve-page-metadata.mjs +1 -1
  154. package/esm/server/resolve-page-metadata.mjs.map +1 -1
  155. package/esm/server/resolve-validation-data.mjs +1 -1
  156. package/esm/server/resolve-validation-data.mjs.map +1 -1
  157. package/esm/server/settle-page-response.d.mts +1 -1
  158. package/esm/server/settle-page-response.mjs +1 -1
  159. package/esm/server/settle-page-response.mjs.map +1 -1
  160. package/esm/server/stylesheet-urls.d.mts +1 -1
  161. package/esm/server/stylesheet-urls.mjs +1 -1
  162. package/esm/server/stylesheet-urls.mjs.map +1 -1
  163. package/esm/server/unregistered-pages.mjs +1 -1
  164. package/esm/server/unregistered-pages.mjs.map +1 -1
  165. package/esm/server/web-connector-factory.d.mts +1 -1
  166. package/esm/server/web-connector-factory.mjs +1 -1
  167. package/esm/server/web-connector-factory.mjs.map +1 -1
  168. package/esm/server/web-connector.d.mts +1 -1
  169. package/esm/server/web-connector.mjs +1 -1
  170. package/esm/server/web-connector.mjs.map +1 -1
  171. package/esm/shared.d.mts +1 -1
  172. package/esm/shared.mjs +1 -1
  173. package/esm/shared.mjs.map +1 -1
  174. package/esm/validation.d.mts +1 -1
  175. package/esm/vite/app-convention-aliases.mjs +1 -1
  176. package/esm/vite/app-convention-aliases.mjs.map +1 -1
  177. package/esm/vite/build-client.d.mts +1 -1
  178. package/esm/vite/build-client.mjs +1 -1
  179. package/esm/vite/build-client.mjs.map +1 -1
  180. package/esm/vite/gate-a-resolve.d.mts +1 -1
  181. package/esm/vite/gate-a-resolve.mjs +1 -1
  182. package/esm/vite/gate-a-resolve.mjs.map +1 -1
  183. package/esm/vite/gate-b-secrets.d.mts +1 -1
  184. package/esm/vite/gate-b-secrets.mjs +1 -1
  185. package/esm/vite/gate-b-secrets.mjs.map +1 -1
  186. package/esm/vite/gate-c-verify.d.mts +1 -1
  187. package/esm/vite/gate-c-verify.mjs +1 -1
  188. package/esm/vite/gate-c-verify.mjs.map +1 -1
  189. package/esm/vite/hydration-entries.d.mts +1 -1
  190. package/esm/vite/hydration-entries.mjs +1 -1
  191. package/esm/vite/hydration-entries.mjs.map +1 -1
  192. package/esm/vite/index.d.mts +1 -1
  193. package/esm/vite/index.mjs +1 -1
  194. package/esm/vite/index.mjs.map +1 -1
  195. package/esm/vite/page-registry-plugin.d.mts +1 -1
  196. package/esm/vite/page-registry-plugin.mjs +1 -1
  197. package/esm/vite/page-registry-plugin.mjs.map +1 -1
  198. package/esm/vite/projection.d.mts +1 -1
  199. package/esm/vite/projection.mjs +1 -1
  200. package/esm/vite/projection.mjs.map +1 -1
  201. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"render-page.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/render-page.ts"],"sourcesContent":["import { createElement, type ComponentType, type ReactNode } from \"react\";\nimport { Response, type Request } from \"@warlock.js/core\";\nimport DefaultApp from \"../components/default-app\";\nimport {\n DocumentContext,\n escapePayload,\n PAYLOAD_SCRIPT_ID,\n type DocumentContextValue,\n} from \"../components/document-context\";\nimport type { SharedContext } from \"../index\";\nimport { buildHydrationPayload } from \"./build-hydration-payload\";\nimport {\n hydrationErrorPageProps,\n resolveErrorPageMetadata,\n type ErrorPageModule,\n type ErrorPageModuleLoader,\n} from \"./error-page\";\nimport { ERROR_PAGE_METADATA } from \"./resolve-page-metadata\";\nimport {\n registerModules,\n type RegisterableModuleNamespace,\n} from \"../runtime/register-modules\";\nimport { markNonHydrating } from \"./page-render-bundle\";\nimport type { ServerErrorPageProps } from \"../props\";\nimport {\n buildErrorRecord,\n designateBoundary,\n executePageRequest,\n type BufferedCookie,\n type ExecutePageRequestOptions,\n type PageDataBundle,\n type PageErrorRecord,\n type PageLevelName,\n type PageResponseCommit,\n type PageRouteEntry,\n type PageRouteMatch,\n type PageTripleModule,\n} from \"./execute-page-request\";\n\nexport { escapePayload, PAYLOAD_SCRIPT_ID };\nexport type { BufferedCookie };\n\n/** Widens `PageDataBundle` with the stage 7 commit record — see `execute-page-request.ts`. */\ntype Bundle = PageDataBundle & { commit?: PageResponseCommit };\n\n/** Reads the stage 7 commit into the lowercased header map `RenderedPage` carries. */\nfunction committedHeaders(bundle: PageDataBundle): Record<string, string> {\n const headers: Record<string, string> = {};\n\n for (const header of (bundle as Bundle).commit?.headers ?? []) {\n headers[header.key.toLowerCase()] = header.value;\n }\n\n return headers;\n}\n\n/** Reads the stage 7 commit into the cookie list `RenderedPage` carries. */\nfunction committedCookies(bundle: PageDataBundle): BufferedCookie[] {\n return (bundle as Bundle).commit?.cookies ?? [];\n}\n\n/**\n * Pipeline stages 9–10: RENDER the page tree from the\n * data bundle stages 1–8 produced, then return finalized { html, status,\n * headers }. Stage 10 happens at the CALL SITE in two halves —\n * 10a the caller applies status + headers (the single live-response write,\n * after render, before anything flushes), 10b it flushes\n * the document. Nothing in this module writes the live response. It never\n * re-runs any earlier stage — `renderPage` calls `executePageRequest` and\n * everything here consumes its bundle as-is.\n *\n * `renderPage` is deliberately double-duty (dx-differentiators.md §3): it is\n * the production orchestrator AND the test helper. Because a loader IS a\n * controller, `renderPage(\"products.details\", { params: { id: \"42\" } })`\n * returns `{ html, status, headers, data }` in one call — asserting a page's\n * data and its response headers is a unit test, no browser, no server boot.\n */\n\n// ---------------------------------------------------------------------------\n// The routes seam (same pattern as connectPageContext: boot wiring, once)\n// ---------------------------------------------------------------------------\n\nexport type PageRoutesRegistry = {\n routes: readonly PageRouteEntry[];\n /** Same contract as ExecutePageRequestOptions[\"createHttp\"]. */\n createHttp: ExecutePageRequestOptions[\"createHttp\"];\n};\n\nlet pageRoutesRegistry: PageRoutesRegistry | undefined;\n\n/**\n * Boot-time wiring so `renderPage(name, options)` can resolve a route NAME\n * without each call site carrying the manifest. Returns the previous registry\n * so tests can restore it. A per-call `routes`/`createHttp` override wins.\n */\nexport function connectPageRoutes(\n registry: PageRoutesRegistry | undefined,\n): PageRoutesRegistry | undefined {\n const previous = pageRoutesRegistry;\n pageRoutesRegistry = registry;\n return previous;\n}\n\n// ---------------------------------------------------------------------------\n// renderPage surface\n// ---------------------------------------------------------------------------\n\nexport type RenderPageOptions = {\n params?: Record<string, string>;\n query?: Record<string, string>;\n /**\n * Impersonation for tests: assigned to `request.user` right after the\n * request pair is constructed — `user` is a plain public property on core's\n * Request (core/src/http/request.ts:92) and this is exactly the write auth\n * middleware would have performed.\n */\n as?: unknown;\n /** Per-call overrides of the connected registry (tests, mostly). */\n routes?: readonly PageRouteEntry[];\n createHttp?: ExecutePageRequestOptions[\"createHttp\"];\n /** Loaded only after the ordinary boundary chain has been exhausted. */\n loadErrorPage?: ErrorPageModuleLoader;\n};\n\n/**\n * `renderPageRequest` takes the URL itself, so `params`/`query` (the\n * name-based sugar buildUrl consumes) have no meaning here — everything else\n * is the same seam.\n */\nexport type RenderPageRequestOptions = Omit<\n RenderPageOptions,\n \"params\" | \"query\"\n>;\n\nexport type RenderedPage = {\n /** The full document (\"\" when the pipeline short-circuited before render). */\n html: string;\n status: number;\n /** Committed response headers, lowercased key → value. */\n headers: Record<string, string>;\n /** Committed response cookies, in commit order — stage 7's `bundle.commit.cookies`. */\n cookies: BufferedCookie[];\n /**\n * The PAGE loader's data — `data.product.name` reads as the dx story\n * writes it. `unknown`: the pipeline never checks a loader's return shape.\n */\n data: unknown;\n /**\n * The full stages-1–8 bundle, for assertions beyond the page's own data.\n * Undefined ONLY on `renderPageRequest`'s no-match path: no route matched,\n * so no pipeline ran and there is no bundle — the 404 answer stands alone.\n * `renderPage` always carries one (its no-match throws instead).\n */\n bundle: PageDataBundle | undefined;\n};\n\nexport type RenderPageFailureOptions = {\n name: string;\n path: string;\n request: Request;\n response: Response;\n thrown: unknown;\n loadErrorPage?: ErrorPageModuleLoader;\n};\n\nfunction requireRegistry(\n options: Pick<RenderPageOptions, \"routes\" | \"createHttp\">,\n): PageRoutesRegistry {\n const routes = options.routes ?? pageRoutesRegistry?.routes;\n const createHttp = options.createHttp ?? pageRoutesRegistry?.createHttp;\n\n if (!routes || !createHttp) {\n throw new Error(\n \"renderPage()/renderPageRequest() has no route registry connected \" +\n \"(web/src/server/render-page.ts). Both resolve against the page \" +\n \"manifest, which the server bootstrap owns. Fix: \" +\n \"call connectPageRoutes({ routes, createHttp }) at boot (tests: in \" +\n \"beforeAll), or pass { routes, createHttp } to this call.\",\n );\n }\n\n return { routes, createHttp };\n}\n\nfunction buildUrl(\n entry: PageRouteEntry,\n params: Record<string, string>,\n query: Record<string, string>,\n): string {\n const path = entry.path\n .split(\"/\")\n .map((segment) => {\n if (!segment.startsWith(\":\")) return segment;\n\n const name = segment.slice(1);\n const value = params[name];\n\n if (value === undefined) {\n throw new Error(\n `renderPage(\"${entry.name}\"): route path \"${entry.path}\" needs ` +\n `param \"${name}\" and the call did not provide it ` +\n \"(web/src/server/render-page.ts). Fix: pass it in \" +\n `\\`params: { ${name}: … }\\`.`,\n );\n }\n\n return encodeURIComponent(value);\n })\n .join(\"/\");\n\n const queryString = new URLSearchParams(query).toString();\n\n return queryString ? `${path}?${queryString}` : path;\n}\n\n// ---------------------------------------------------------------------------\n// Stage 9 — RENDER\n// ---------------------------------------------------------------------------\n\n/**\n * The framework-owned terminal boundary (P1 §4: designation falls back to\n * `app` even when no level exports one — \"the framework owns a root\n * boundary\"). Deliberately generic: the error itself is server knowledge and\n * never serialized into the document.\n */\nfunction FrameworkRootBoundary(): ReactNode {\n return createElement(\"main\", { role: \"alert\" }, \"Something went wrong.\");\n}\n\nfunction errorPageElement(\n module: ErrorPageModule,\n props: ServerErrorPageProps,\n): ReactNode {\n const ErrorPage = module.default as\n ((input: ServerErrorPageProps) => ReactNode) | undefined;\n if (!ErrorPage) {\n throw new Error(\n \"The application error.page.tsx module has no default export.\",\n );\n }\n return createElement(ErrorPage, props);\n}\n\ntype LevelProps = {\n data: unknown;\n shared: Readonly<SharedContext> | undefined;\n children?: ReactNode;\n};\n\n/** The ordinary page leaf alone receives the route match's params. */\ntype PageLevelProps = {\n data: unknown;\n shared: Readonly<SharedContext> | undefined;\n params: Readonly<Record<string, string>>;\n};\n\nconst DATA_KEYS: Record<PageLevelName, \"appData\" | \"layoutData\" | \"pageData\"> =\n {\n app: \"appData\",\n layout: \"layoutData\",\n page: \"pageData\",\n };\n\n/**\n * Compose the tree root→leaf: `<App><Layout><Page/></Layout></App>`, each\n * level receiving ITS OWN loader data and the same sealed `shared` — the\n * exact props the M1 contract declares (web/src/props.ts) and never\n * request/response (the component also renders on a machine where neither\n * exists, props.ts:19-22).\n *\n * A level with no default export contributes no DOM and passes children\n * through — that is `layout.tsx` omitting its default export to be a guard\n * with no DOM.\n */\nfunction buildPageElement(\n triple: Record<PageLevelName, PageTripleModule>,\n bundle: PageDataBundle,\n): ReactNode {\n return wrapRootward(triple, bundle, \"page\", buildLeaf(triple.page, bundle));\n}\n\n/**\n * The error path renders the DESIGNATED boundary in place of the level it\n * covers, still wrapped by every level rootward of it — a page-level throw\n * keeps its App and Layout chrome, whose data survived the settle rules\n * (P1 §4: fulfilled sibling data stays in the bundle).\n *\n * `record` is explicit rather than read from `bundle.error` — a render-time\n * throw (`finishRender`'s stage 9 escalation loop) designates a NEW boundary on the fly that the stage 1-8 bundle never saw.\n */\nfunction buildBoundaryElement(\n triple: Record<PageLevelName, PageTripleModule>,\n bundle: PageDataBundle,\n record: PageErrorRecord,\n): ReactNode {\n const { boundary, error } = record;\n const Boundary = triple[boundary.boundaryLevel].ErrorBoundary as\n ((props: { error: unknown }) => ReactNode) | undefined;\n\n const element = Boundary\n ? createElement(Boundary, { error })\n : createElement(FrameworkRootBoundary, {});\n\n const wrapped = wrapRootward(triple, bundle, boundary.boundaryLevel, element);\n\n // \"App\" has no level rootward of it, so `wrapRootward` returns `wrapped`\n // unwrapped when the boundary covers the app level itself — but the\n // pipeline always emits a complete document, so the\n // framework default supplies the shell here even though the app's own\n // (broken) root is what's being bypassed.\n return boundary.boundaryLevel === \"app\"\n ? createElement(DefaultApp, { children: wrapped })\n : wrapped;\n}\n\nfunction buildLeaf(\n module: PageTripleModule,\n bundle: PageDataBundle,\n): ReactNode {\n const Component = module.default as\n ((props: PageLevelProps) => ReactNode) | undefined;\n\n if (!Component) return null;\n\n return createElement(Component as ComponentType<PageLevelProps>, {\n data: bundle.pageData,\n shared: bundle.shared,\n params: bundle.route.params,\n });\n}\n\nfunction wrapRootward(\n triple: Record<PageLevelName, PageTripleModule>,\n bundle: PageDataBundle,\n from: PageLevelName,\n leaf: ReactNode,\n): ReactNode {\n const wrappers: PageLevelName[] =\n from === \"page\" ? [\"layout\", \"app\"] : from === \"layout\" ? [\"app\"] : [];\n\n let element = leaf;\n\n for (const level of wrappers) {\n const Component = triple[level].default as\n ((props: LevelProps) => ReactNode) | undefined;\n\n if (!Component) {\n // \"App\" is the root: no App export means no custom document, but the\n // pipeline always emits a complete one — the\n // framework default App supplies it. Layout has no such fallback: an\n // omitted layout default export stays a no-DOM passthrough,\n // unchanged from before.\n if (level === \"app\") {\n element = createElement(DefaultApp, { children: element });\n }\n\n continue;\n }\n\n element = createElement(Component as ComponentType<LevelProps>, {\n data: bundle[DATA_KEYS[level]],\n shared: bundle.shared,\n children: element,\n });\n }\n\n return element;\n}\n\n// ---------------------------------------------------------------------------\n// Document assembly — stage 10 (10a apply + 10b flush) lives at the call site\n// ---------------------------------------------------------------------------\n\n/**\n * The root (App or the framework default) now ALWAYS renders a complete\n * `<html>…</html>` document itself — `<Head/>`/\n * `<Scripts/>` read the metadata/payload from `DocumentContext` (provided\n * around the element in `finishRender`, below) and emit real elements.\n * There is nothing left for this stage to assemble by string surgery; it\n * only prepends the doctype `renderToString` never includes.\n */\nfunction emitDocument(body: string): string {\n return \"<!DOCTYPE html>\" + body;\n}\n\n// ---------------------------------------------------------------------------\n// The shared tail (stages 9–10) — both orchestrators end here\n// ---------------------------------------------------------------------------\n\n/**\n * The real request/response pair `capturingCreateHttp` captured for this\n * call. It is used at\n * the two orchestrator call sites for the `as` impersonation write\n * (`state.captured.request.user = as`, below) and to read the document\n * slots (`documentSlotsFrom`, below).\n */\ntype CapturedHttp = {\n request: Request;\n response: Response;\n};\n\n/**\n * Wrap the caller's createHttp to capture the real pair (for the document\n * slots, `documentSlotsFrom` below), the matched entry (the only place a\n * URL-based caller learns which triple to render), and to apply `as` —\n * `user` is a plain public property on core's Request\n * (core/src/http/request.ts:92), exactly the write auth middleware performs.\n */\nfunction capturingCreateHttp(\n registry: PageRoutesRegistry,\n as: unknown,\n): {\n state: { captured?: CapturedHttp; match?: PageRouteMatch };\n createHttp: ExecutePageRequestOptions[\"createHttp\"];\n} {\n const state: { captured?: CapturedHttp; match?: PageRouteMatch } = {};\n\n return {\n state,\n createHttp(match) {\n state.match = match;\n state.captured = registry.createHttp(match);\n\n // `!= null` (not just `!== undefined`): `Request.user` is `RequestUser\n // | undefined` (core/src/http/request.ts:93) — it has no `null` member,\n // so an explicit `as: null` is treated the same as \"no impersonation\"\n // rather than written through.\n if (as != null) state.captured.request.user = as;\n\n return state.captured;\n },\n };\n}\n\n/**\n * The two request-derived document slots (`nonce`/`lang` on\n * `DocumentContextValue`), extracted at the orchestrator call sites\n * because `finishRender` no longer carries `captured` (D1). `dir` is not\n * here: core's Request has no dir-like field (checked\n * core/src/http/request.ts — only `nonce` at :177 and `locale` at :343\n * exist) — an app supplies `dir` via its own convention.\n */\ntype DocumentSlots = {\n nonce?: string;\n lang?: string;\n};\n\n/** Reads document slots directly from core's Request. */\nfunction documentSlotsFrom(captured: CapturedHttp | undefined): DocumentSlots {\n const request = captured?.request;\n\n return { nonce: request?.nonce, lang: request?.locale };\n}\n\nasync function finishRender(\n triple: PageRouteEntry[\"triple\"],\n bundle: PageDataBundle,\n documentSlots: DocumentSlots,\n response: Response,\n loadErrorPage: ErrorPageModuleLoader | undefined,\n): Promise<RenderedPage> {\n // Read from the stage 7 commit, never live off `response` — this function\n // writes (and now reads) the live response zero times. A bundle with no\n // commit (no loader ran at all) simply has no headers/cookies to report.\n const headers = committedHeaders(bundle);\n const cookies = committedCookies(bundle);\n\n // Middleware and validation short-circuits emit no document. Loader-returned\n // Response instances never reach this function.\n if (bundle.shortCircuit) {\n const status =\n bundle.shortCircuit.stage === \"validation\"\n ? bundle.shortCircuit.status\n : (bundle.shortCircuit.statusCode ?? 200);\n return {\n html: \"\",\n status,\n headers,\n cookies,\n data: bundle.pageData,\n bundle,\n };\n }\n\n // The framework's closed-by-default answer (README rule 8): every document\n // is `Cache-Control: private` unless a loader's committed headers already\n // answered for the key. Map-only — the caller applies the returned headers.\n if (headers[\"cache-control\"] === undefined) {\n headers[\"cache-control\"] = \"private\";\n }\n\n // ── stage 9 · RENDER ─────────────────────────────────────────────────────\n // Lazy import: react-dom is a peer used only on this path, so merely\n // loading the server barrel never requires it.\n const { renderToString } = await import(\"react-dom/server\");\n\n // JSON.stringify omits object properties whose value is undefined. Loader\n // `<Head/>`/`<Scripts/>` read this context — metadata and the payload are\n // both already final by this point (stages 1-8 are done), so there is\n // nothing left for the root to await.\n //\n // The payload comes from `buildHydrationPayload` rather than being assembled\n // here, so that this document and the `_loader` route hand the browser the\n // SAME object. See that module for why the two must not drift.\n let documentValue: DocumentContextValue = {\n metadata: bundle.metadata,\n payload: buildHydrationPayload(bundle),\n nonce: documentSlots.nonce,\n lang: documentSlots.lang,\n };\n\n const renderWithContext = (element: ReactNode): string =>\n renderToString(\n createElement(DocumentContext.Provider, {\n value: documentValue,\n children: element,\n }),\n );\n\n // A boundary that throws while rendering escalates to\n // the next enclosing boundary rootward; if none survives, the framework's\n // last-resort terminal renders. `currentError` starts as whatever stage\n // 1-8 already designated (`bundle.error`, undefined for a normal page\n // render) and is replaced by each escalation — `bundle.error` itself is\n // never mutated, staying a truthful stage 1-8 record.\n let currentError = bundle.error;\n let renderTimeThrow = false;\n let body: string;\n\n const renderFrameworkRoot = (): string =>\n renderWithContext(\n createElement(DefaultApp, {\n children: createElement(FrameworkRootBoundary, {}),\n }),\n );\n const renderFrameworkAfterErrorPageFailure = (): string => {\n bundle.errorPage = undefined;\n bundle.metadata = ERROR_PAGE_METADATA;\n documentValue = {\n ...documentValue,\n metadata: bundle.metadata,\n payload: buildHydrationPayload(bundle),\n };\n return renderFrameworkRoot();\n };\n\n const renderErrorPage = async (\n thrown: unknown,\n serializableError: unknown = thrown,\n ): Promise<string | undefined> => {\n if (!loadErrorPage) return undefined;\n\n const props: ServerErrorPageProps = { error: thrown, status: 500 };\n const module = await loadErrorPage();\n registerModules([module as RegisterableModuleNamespace]);\n const errorPage = hydrationErrorPageProps(props, serializableError);\n bundle.errorPage = errorPage;\n bundle.metadata = resolveErrorPageMetadata(module, props);\n documentValue = {\n ...documentValue,\n metadata: bundle.metadata,\n payload: buildHydrationPayload(bundle),\n };\n return renderWithContext(\n wrapRootward(triple, bundle, \"page\", errorPageElement(module, props)),\n );\n };\n\n for (;;) {\n try {\n // The application error page is the framework terminal, never a rival\n // to an authored boundary. It is reached only after no app boundary\n // exists (or after that boundary has itself thrown below).\n if (\n currentError?.boundary.boundaryLevel === \"app\" &&\n !triple.app.ErrorBoundary\n ) {\n try {\n body =\n (await renderErrorPage(\n currentError.originalError ?? currentError.error,\n currentError.error,\n )) ?? renderFrameworkRoot();\n } catch {\n body = renderFrameworkAfterErrorPageFailure();\n }\n renderTimeThrow = true;\n break;\n }\n\n const element = currentError\n ? buildBoundaryElement(triple, bundle, currentError)\n : buildPageElement(triple, bundle);\n\n body = renderWithContext(element);\n break;\n } catch (thrown) {\n renderTimeThrow = true;\n\n if (currentError?.boundary.boundaryLevel === \"app\") {\n // The floor: the app-level boundary's own render just threw, so\n // there is nothing rootward of `app` to escalate to (§2's \"none\n // survives\"). Render the framework's trivial boundary directly —\n // bypassing the app's ErrorBoundary/App component, since that is\n // what just failed — wrapped in DefaultApp so the response is still\n // a complete `<html>` document (default-app.tsx:22-46) rather than\n // a bare `<main>` fragment.\n try {\n body = (await renderErrorPage(thrown)) ?? renderFrameworkRoot();\n } catch {\n body = renderFrameworkAfterErrorPageFailure();\n }\n break;\n }\n\n // Escalate from the level rootward of whatever just threw — searching\n // from the SAME level would re-select the boundary that just failed.\n // A throw not yet attributable to a level (a normal page render, no\n // prior designation) starts the search at `page`.\n const throwingLevel: PageLevelName =\n currentError?.boundary.boundaryLevel === \"layout\"\n ? \"app\"\n : currentError\n ? \"layout\"\n : \"page\";\n\n currentError = buildErrorRecord(\n thrown,\n designateBoundary(throwingLevel, triple),\n );\n }\n }\n\n // Status is chosen after render — the last thing that can change the\n // outcome — and RETURNED, never applied: `finishRender` writes the live\n // response zero times. The caller applies status + headers at one site and\n // flushes immediately after (stage 10a/10b). \"The framework owns the status\n // whenever a boundary renders\" (design/request-lifecycle.md stage 7): ANY\n // boundary — nested or app-level, discovered pre-render or escalated during\n // render — forces 500. The boundary's LEVEL only decides which component\n // renders, never the status; the committed status from stage 7\n // (`bundle.commit.statusCode`) stands only for a page with no error at all\n // — read off the commit, never off the live `response`, same as `headers`\n // above. No committed status (no loader called `setStatusCode`) is the\n // ordinary 200.\n const status = currentError\n ? 500\n : ((bundle as Bundle).commit?.statusCode ?? 200);\n\n const html = emitDocument(body);\n\n return { html, status, headers, cookies, data: bundle.pageData, bundle };\n}\n\n/**\n * Render failures that happen before the page pipeline has a triple (notably a\n * module-load or registration throw). This deliberately owns one terminal\n * attempt: an error-page failure falls straight to FrameworkRootBoundary.\n *\n * There is no triple yet, so there is no trustworthy server composition for\n * the browser to hydrate against — every response this function produces is\n * marked `markNonHydrating` (page-render-bundle.ts), on both the bundle and\n * the document payload, whether or not it managed to render the app's own\n * `error.page.tsx`. A normal app error page reached through `finishRender`\n * renders inside a real triple and stays hydratable; this path never does.\n */\nexport async function renderPageFailure(\n options: RenderPageFailureOptions,\n): Promise<RenderedPage> {\n const { request, response, name, path, thrown, loadErrorPage } = options;\n const bundle: PageDataBundle = markNonHydrating({\n route: { name, path, params: {}, query: {} },\n });\n // No pipeline ran (there is no triple), so there is no commit to read —\n // never a live `response.getHeaders()` read either; see `finishRender`.\n const headers: Record<string, string> = { \"cache-control\": \"private\" };\n\n const { renderToString } = await import(\"react-dom/server\");\n const slots = documentSlotsFrom({ request, response });\n const frameworkPayload = markNonHydrating(buildHydrationPayload(bundle));\n let value: DocumentContextValue = {\n metadata: undefined,\n payload: frameworkPayload,\n nonce: slots.nonce,\n lang: slots.lang,\n };\n const renderWithContext = (element: ReactNode): string =>\n renderToString(\n createElement(DocumentContext.Provider, { value, children: element }),\n );\n let body: string;\n\n try {\n if (!loadErrorPage)\n throw new Error(\"No application error page is configured.\");\n const props: ServerErrorPageProps = { error: thrown, status: 500 };\n const module = await loadErrorPage();\n registerModules([module as RegisterableModuleNamespace]);\n const errorPage = hydrationErrorPageProps(props);\n bundle.errorPage = errorPage;\n value = {\n ...value,\n metadata: resolveErrorPageMetadata(module, props),\n payload: markNonHydrating({ ...frameworkPayload, errorPage }),\n };\n body = renderWithContext(\n createElement(DefaultApp, { children: errorPageElement(module, props) }),\n );\n } catch {\n bundle.errorPage = undefined;\n bundle.metadata = ERROR_PAGE_METADATA;\n value = {\n ...value,\n metadata: bundle.metadata,\n payload: markNonHydrating(buildHydrationPayload(bundle)),\n };\n body = renderWithContext(\n createElement(DefaultApp, {\n children: createElement(FrameworkRootBoundary, {}),\n }),\n );\n }\n\n return {\n html: emitDocument(body),\n status: 500,\n headers,\n cookies: [],\n data: undefined,\n bundle,\n };\n}\n\n// ---------------------------------------------------------------------------\n// The orchestrators\n// ---------------------------------------------------------------------------\n\nexport async function renderPage(\n routeName: string,\n options: RenderPageOptions = {},\n): Promise<RenderedPage | Response> {\n const registry = requireRegistry(options);\n const entry = registry.routes.find(\n (candidate) => candidate.name === routeName,\n );\n\n if (!entry) {\n const known = registry.routes\n .map((candidate) => `\"${candidate.name}\"`)\n .join(\", \");\n\n throw new Error(\n `renderPage(\"${routeName}\"): no route with that name ` +\n `(web/src/server/render-page.ts). Known route names: ${known}. ` +\n \"Fix: use a name from the manifest, or connect the manifest that \" +\n \"declares this one.\",\n );\n }\n\n const url = buildUrl(entry, options.params ?? {}, options.query ?? {});\n const { state, createHttp } = capturingCreateHttp(registry, options.as);\n\n const rendered = await executePageRequest({\n url,\n routes: registry.routes,\n createHttp,\n finish: (bundle) =>\n finishRender(\n entry.triple,\n bundle,\n documentSlotsFrom(state.captured),\n state.captured!.response,\n options.loadErrorPage,\n ),\n });\n\n if (!rendered) {\n throw new Error(\n `renderPage(\"${routeName}\"): the built URL \"${url}\" did not match ` +\n \"stage 1 (web/src/server/render-page.ts). The name resolved but the \" +\n \"matcher disagreed — that is a manifest bug, not a caller bug.\",\n );\n }\n\n return rendered;\n}\n\n/**\n * The URL-based sibling of `renderPage` — the production render surface: a\n * real HTTP server has a URL, not a route name. The url goes STRAIGHT to\n * executePageRequest's stage-1 matcher (no buildUrl), then the same shared\n * tail renders and emits.\n *\n * No-match here is NOT the manifest bug renderPage throws on: an arbitrary\n * URL matching no route is a legitimate 404, and a server must ANSWER it —\n * `{ html: \"\", status: 404 }` with an undefined `bundle` (see RenderedPage).\n */\nexport async function renderPageRequest(\n url: string,\n options: RenderPageRequestOptions = {},\n): Promise<RenderedPage | Response> {\n const registry = requireRegistry(options);\n const { state, createHttp } = capturingCreateHttp(registry, options.as);\n\n const rendered = await executePageRequest({\n url,\n routes: registry.routes,\n createHttp,\n finish: (bundle) =>\n finishRender(\n state.match!.entry.triple,\n bundle,\n documentSlotsFrom(state.captured),\n state.captured!.response,\n options.loadErrorPage,\n ),\n });\n\n if (!rendered) {\n return {\n html: \"\",\n status: 404,\n headers: {},\n cookies: [],\n data: undefined,\n bundle: undefined,\n };\n }\n\n // executePageRequest only produces a bundle after createHttp ran for the\n // match, so the captured entry is present whenever the bundle is.\n return rendered;\n}\n"],"mappings":";;;;;;;;;;;;;;AA8CA,SAAS,iBAAiB,QAAgD;CACxE,MAAM,UAAkC,CAAC;CAEzC,KAAK,MAAM,UAAW,OAAkB,QAAQ,WAAW,CAAC,GAC1D,QAAQ,OAAO,IAAI,YAAY,KAAK,OAAO;CAG7C,OAAO;AACT;;AAGA,SAAS,iBAAiB,QAA0C;CAClE,OAAQ,OAAkB,QAAQ,WAA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MAAM,SAAS,OAAO,QAAQ,UAAU,CAAC,GAAG,QAAQ,SAAS,CAAC,CAAC;CACrE,MAAM,EAAE,OAAO,eAAe,oBAAoB,UAAU,QAAQ,EAAE;CAEtE,MAAM,WAAW,MAAM,mBAAmB;EACxC;EACA,QAAQ,SAAS;EACjB;EACA,SAAS,WACP,aACE,MAAM,QACN,QACA,kBAAkB,MAAM,QAAQ,GAChC,MAAM,SAAU,UAChB,QAAQ,aACV;CACJ,CAAC;CAED,IAAI,CAAC,UACH,MAAM,IAAI,MACR,eAAe,UAAU,qBAAqB,IAAI,iJAGpD;CAGF,OAAO;AACT;;;;;;;;;;;AAYA,eAAsB,kBACpB,KACA,UAAoC,CAAC,GACH;CAClC,MAAM,WAAW,gBAAgB,OAAO;CACxC,MAAM,EAAE,OAAO,eAAe,oBAAoB,UAAU,QAAQ,EAAE;CAEtE,MAAM,WAAW,MAAM,mBAAmB;EACxC;EACA,QAAQ,SAAS;EACjB;EACA,SAAS,WACP,aACE,MAAM,MAAO,MAAM,QACnB,QACA,kBAAkB,MAAM,QAAQ,GAChC,MAAM,SAAU,UAChB,QAAQ,aACV;CACJ,CAAC;CAED,IAAI,CAAC,UACH,OAAO;EACL,MAAM;EACN,QAAQ;EACR,SAAS,CAAC;EACV,SAAS,CAAC;EACV,MAAM;EACN,QAAQ;CACV;CAKF,OAAO;AACT"}
1
+ {"version":3,"file":"render-page.mjs","names":[],"sources":["../../../../../../../web/src/server/render-page.ts"],"sourcesContent":["import { createElement, type ComponentType, type ReactNode } from \"react\";\nimport { Response, type Request } from \"@warlock.js/core\";\nimport DefaultApp from \"../components/default-app\";\nimport {\n DocumentContext,\n escapePayload,\n PAYLOAD_SCRIPT_ID,\n type DocumentContextValue,\n} from \"../components/document-context\";\nimport type { SharedContext } from \"../index\";\nimport { buildHydrationPayload } from \"./build-hydration-payload\";\nimport {\n hydrationErrorPageProps,\n resolveErrorPageMetadata,\n type ErrorPageModule,\n type ErrorPageModuleLoader,\n} from \"./error-page\";\nimport { ERROR_PAGE_METADATA } from \"./resolve-page-metadata\";\nimport {\n registerModules,\n type RegisterableModuleNamespace,\n} from \"../runtime/register-modules\";\nimport { markNonHydrating } from \"./page-render-bundle\";\nimport type { ServerErrorPageProps } from \"../props\";\nimport {\n buildErrorRecord,\n designateBoundary,\n executePageRequest,\n type BufferedCookie,\n type ExecutePageRequestOptions,\n type PageDataBundle,\n type PageErrorRecord,\n type PageLevelName,\n type PageResponseCommit,\n type PageRouteEntry,\n type PageRouteMatch,\n type PageTripleModule,\n} from \"./execute-page-request\";\n\nexport { escapePayload, PAYLOAD_SCRIPT_ID };\nexport type { BufferedCookie };\n\n/** Widens `PageDataBundle` with the stage 7 commit record — see `execute-page-request.ts`. */\ntype Bundle = PageDataBundle & { commit?: PageResponseCommit };\n\n/** Reads the stage 7 commit into the lowercased header map `RenderedPage` carries. */\nfunction committedHeaders(bundle: PageDataBundle): Record<string, string> {\n const headers: Record<string, string> = {};\n\n for (const header of (bundle as Bundle).commit?.headers ?? []) {\n headers[header.key.toLowerCase()] = header.value;\n }\n\n return headers;\n}\n\n/** Reads the stage 7 commit into the cookie list `RenderedPage` carries. */\nfunction committedCookies(bundle: PageDataBundle): BufferedCookie[] {\n return (bundle as Bundle).commit?.cookies ?? [];\n}\n\n/**\n * Pipeline stages 9–10: RENDER the page tree from the\n * data bundle stages 1–8 produced, then return finalized { html, status,\n * headers }. Stage 10 happens at the CALL SITE in two halves —\n * 10a the caller applies status + headers (the single live-response write,\n * after render, before anything flushes), 10b it flushes\n * the document. Nothing in this module writes the live response. It never\n * re-runs any earlier stage — `renderPage` calls `executePageRequest` and\n * everything here consumes its bundle as-is.\n *\n * `renderPage` is deliberately double-duty (dx-differentiators.md §3): it is\n * the production orchestrator AND the test helper. Because a loader IS a\n * controller, `renderPage(\"products.details\", { params: { id: \"42\" } })`\n * returns `{ html, status, headers, data }` in one call — asserting a page's\n * data and its response headers is a unit test, no browser, no server boot.\n */\n\n// ---------------------------------------------------------------------------\n// The routes seam (same pattern as connectPageContext: boot wiring, once)\n// ---------------------------------------------------------------------------\n\nexport type PageRoutesRegistry = {\n routes: readonly PageRouteEntry[];\n /** Same contract as ExecutePageRequestOptions[\"createHttp\"]. */\n createHttp: ExecutePageRequestOptions[\"createHttp\"];\n};\n\nlet pageRoutesRegistry: PageRoutesRegistry | undefined;\n\n/**\n * Boot-time wiring so `renderPage(name, options)` can resolve a route NAME\n * without each call site carrying the manifest. Returns the previous registry\n * so tests can restore it. A per-call `routes`/`createHttp` override wins.\n */\nexport function connectPageRoutes(\n registry: PageRoutesRegistry | undefined,\n): PageRoutesRegistry | undefined {\n const previous = pageRoutesRegistry;\n pageRoutesRegistry = registry;\n return previous;\n}\n\n// ---------------------------------------------------------------------------\n// renderPage surface\n// ---------------------------------------------------------------------------\n\nexport type RenderPageOptions = {\n params?: Record<string, string>;\n query?: Record<string, string>;\n /**\n * Impersonation for tests: assigned to `request.user` right after the\n * request pair is constructed — `user` is a plain public property on core's\n * Request (core/src/http/request.ts:92) and this is exactly the write auth\n * middleware would have performed.\n */\n as?: unknown;\n /** Per-call overrides of the connected registry (tests, mostly). */\n routes?: readonly PageRouteEntry[];\n createHttp?: ExecutePageRequestOptions[\"createHttp\"];\n /** Loaded only after the ordinary boundary chain has been exhausted. */\n loadErrorPage?: ErrorPageModuleLoader;\n};\n\n/**\n * `renderPageRequest` takes the URL itself, so `params`/`query` (the\n * name-based sugar buildUrl consumes) have no meaning here — everything else\n * is the same seam.\n */\nexport type RenderPageRequestOptions = Omit<\n RenderPageOptions,\n \"params\" | \"query\"\n>;\n\nexport type RenderedPage = {\n /** The full document (\"\" when the pipeline short-circuited before render). */\n html: string;\n status: number;\n /** Committed response headers, lowercased key → value. */\n headers: Record<string, string>;\n /** Committed response cookies, in commit order — stage 7's `bundle.commit.cookies`. */\n cookies: BufferedCookie[];\n /**\n * The PAGE loader's data — `data.product.name` reads as the dx story\n * writes it. `unknown`: the pipeline never checks a loader's return shape.\n */\n data: unknown;\n /**\n * The full stages-1–8 bundle, for assertions beyond the page's own data.\n * Undefined ONLY on `renderPageRequest`'s no-match path: no route matched,\n * so no pipeline ran and there is no bundle — the 404 answer stands alone.\n * `renderPage` always carries one (its no-match throws instead).\n */\n bundle: PageDataBundle | undefined;\n};\n\nexport type RenderPageFailureOptions = {\n name: string;\n path: string;\n request: Request;\n response: Response;\n thrown: unknown;\n loadErrorPage?: ErrorPageModuleLoader;\n};\n\nfunction requireRegistry(\n options: Pick<RenderPageOptions, \"routes\" | \"createHttp\">,\n): PageRoutesRegistry {\n const routes = options.routes ?? pageRoutesRegistry?.routes;\n const createHttp = options.createHttp ?? pageRoutesRegistry?.createHttp;\n\n if (!routes || !createHttp) {\n throw new Error(\n \"renderPage()/renderPageRequest() has no route registry connected \" +\n \"(web/src/server/render-page.ts). Both resolve against the page \" +\n \"manifest, which the server bootstrap owns. Fix: \" +\n \"call connectPageRoutes({ routes, createHttp }) at boot (tests: in \" +\n \"beforeAll), or pass { routes, createHttp } to this call.\",\n );\n }\n\n return { routes, createHttp };\n}\n\nfunction buildUrl(\n entry: PageRouteEntry,\n params: Record<string, string>,\n query: Record<string, string>,\n): string {\n const path = entry.path\n .split(\"/\")\n .map((segment) => {\n if (!segment.startsWith(\":\")) return segment;\n\n const name = segment.slice(1);\n const value = params[name];\n\n if (value === undefined) {\n throw new Error(\n `renderPage(\"${entry.name}\"): route path \"${entry.path}\" needs ` +\n `param \"${name}\" and the call did not provide it ` +\n \"(web/src/server/render-page.ts). Fix: pass it in \" +\n `\\`params: { ${name}: … }\\`.`,\n );\n }\n\n return encodeURIComponent(value);\n })\n .join(\"/\");\n\n const queryString = new URLSearchParams(query).toString();\n\n return queryString ? `${path}?${queryString}` : path;\n}\n\n// ---------------------------------------------------------------------------\n// Stage 9 — RENDER\n// ---------------------------------------------------------------------------\n\n/**\n * The framework-owned terminal boundary (P1 §4: designation falls back to\n * `app` even when no level exports one — \"the framework owns a root\n * boundary\"). Deliberately generic: the error itself is server knowledge and\n * never serialized into the document.\n */\nfunction FrameworkRootBoundary(): ReactNode {\n return createElement(\"main\", { role: \"alert\" }, \"Something went wrong.\");\n}\n\nfunction errorPageElement(\n module: ErrorPageModule,\n props: ServerErrorPageProps,\n): ReactNode {\n const ErrorPage = module.default as\n ((input: ServerErrorPageProps) => ReactNode) | undefined;\n if (!ErrorPage) {\n throw new Error(\n \"The application error.page.tsx module has no default export.\",\n );\n }\n return createElement(ErrorPage, props);\n}\n\ntype LevelProps = {\n data: unknown;\n shared: Readonly<SharedContext> | undefined;\n children?: ReactNode;\n};\n\n/** The ordinary page leaf alone receives the route match's params. */\ntype PageLevelProps = {\n data: unknown;\n shared: Readonly<SharedContext> | undefined;\n params: Readonly<Record<string, string>>;\n};\n\nconst DATA_KEYS: Record<PageLevelName, \"appData\" | \"layoutData\" | \"pageData\"> =\n {\n app: \"appData\",\n layout: \"layoutData\",\n page: \"pageData\",\n };\n\n/**\n * Compose the tree root→leaf: `<App><Layout><Page/></Layout></App>`, each\n * level receiving ITS OWN loader data and the same sealed `shared` — the\n * exact props the M1 contract declares (web/src/props.ts) and never\n * request/response (the component also renders on a machine where neither\n * exists, props.ts:19-22).\n *\n * A level with no default export contributes no DOM and passes children\n * through — that is `layout.tsx` omitting its default export to be a guard\n * with no DOM.\n */\nfunction buildPageElement(\n triple: Record<PageLevelName, PageTripleModule>,\n bundle: PageDataBundle,\n): ReactNode {\n return wrapRootward(triple, bundle, \"page\", buildLeaf(triple.page, bundle));\n}\n\n/**\n * The error path renders the DESIGNATED boundary in place of the level it\n * covers, still wrapped by every level rootward of it — a page-level throw\n * keeps its App and Layout chrome, whose data survived the settle rules\n * (P1 §4: fulfilled sibling data stays in the bundle).\n *\n * `record` is explicit rather than read from `bundle.error` — a render-time\n * throw (`finishRender`'s stage 9 escalation loop) designates a NEW boundary on the fly that the stage 1-8 bundle never saw.\n */\nfunction buildBoundaryElement(\n triple: Record<PageLevelName, PageTripleModule>,\n bundle: PageDataBundle,\n record: PageErrorRecord,\n): ReactNode {\n const { boundary, error } = record;\n const Boundary = triple[boundary.boundaryLevel].ErrorBoundary as\n ((props: { error: unknown }) => ReactNode) | undefined;\n\n const element = Boundary\n ? createElement(Boundary, { error })\n : createElement(FrameworkRootBoundary, {});\n\n const wrapped = wrapRootward(triple, bundle, boundary.boundaryLevel, element);\n\n // \"App\" has no level rootward of it, so `wrapRootward` returns `wrapped`\n // unwrapped when the boundary covers the app level itself — but the\n // pipeline always emits a complete document, so the\n // framework default supplies the shell here even though the app's own\n // (broken) root is what's being bypassed.\n return boundary.boundaryLevel === \"app\"\n ? createElement(DefaultApp, { children: wrapped })\n : wrapped;\n}\n\nfunction buildLeaf(\n module: PageTripleModule,\n bundle: PageDataBundle,\n): ReactNode {\n const Component = module.default as\n ((props: PageLevelProps) => ReactNode) | undefined;\n\n if (!Component) return null;\n\n return createElement(Component as ComponentType<PageLevelProps>, {\n data: bundle.pageData,\n shared: bundle.shared,\n params: bundle.route.params,\n });\n}\n\nfunction wrapRootward(\n triple: Record<PageLevelName, PageTripleModule>,\n bundle: PageDataBundle,\n from: PageLevelName,\n leaf: ReactNode,\n): ReactNode {\n const wrappers: PageLevelName[] =\n from === \"page\" ? [\"layout\", \"app\"] : from === \"layout\" ? [\"app\"] : [];\n\n let element = leaf;\n\n for (const level of wrappers) {\n const Component = triple[level].default as\n ((props: LevelProps) => ReactNode) | undefined;\n\n if (!Component) {\n // \"App\" is the root: no App export means no custom document, but the\n // pipeline always emits a complete one — the\n // framework default App supplies it. Layout has no such fallback: an\n // omitted layout default export stays a no-DOM passthrough,\n // unchanged from before.\n if (level === \"app\") {\n element = createElement(DefaultApp, { children: element });\n }\n\n continue;\n }\n\n element = createElement(Component as ComponentType<LevelProps>, {\n data: bundle[DATA_KEYS[level]],\n shared: bundle.shared,\n children: element,\n });\n }\n\n return element;\n}\n\n// ---------------------------------------------------------------------------\n// Document assembly — stage 10 (10a apply + 10b flush) lives at the call site\n// ---------------------------------------------------------------------------\n\n/**\n * The root (App or the framework default) now ALWAYS renders a complete\n * `<html>…</html>` document itself — `<Head/>`/\n * `<Scripts/>` read the metadata/payload from `DocumentContext` (provided\n * around the element in `finishRender`, below) and emit real elements.\n * There is nothing left for this stage to assemble by string surgery; it\n * only prepends the doctype `renderToString` never includes.\n */\nfunction emitDocument(body: string): string {\n return \"<!DOCTYPE html>\" + body;\n}\n\n// ---------------------------------------------------------------------------\n// The shared tail (stages 9–10) — both orchestrators end here\n// ---------------------------------------------------------------------------\n\n/**\n * The real request/response pair `capturingCreateHttp` captured for this\n * call. It is used at\n * the two orchestrator call sites for the `as` impersonation write\n * (`state.captured.request.user = as`, below) and to read the document\n * slots (`documentSlotsFrom`, below).\n */\ntype CapturedHttp = {\n request: Request;\n response: Response;\n};\n\n/**\n * Wrap the caller's createHttp to capture the real pair (for the document\n * slots, `documentSlotsFrom` below), the matched entry (the only place a\n * URL-based caller learns which triple to render), and to apply `as` —\n * `user` is a plain public property on core's Request\n * (core/src/http/request.ts:92), exactly the write auth middleware performs.\n */\nfunction capturingCreateHttp(\n registry: PageRoutesRegistry,\n as: unknown,\n): {\n state: { captured?: CapturedHttp; match?: PageRouteMatch };\n createHttp: ExecutePageRequestOptions[\"createHttp\"];\n} {\n const state: { captured?: CapturedHttp; match?: PageRouteMatch } = {};\n\n return {\n state,\n createHttp(match) {\n state.match = match;\n state.captured = registry.createHttp(match);\n\n // `!= null` (not just `!== undefined`): `Request.user` is `RequestUser\n // | undefined` (core/src/http/request.ts:93) — it has no `null` member,\n // so an explicit `as: null` is treated the same as \"no impersonation\"\n // rather than written through.\n if (as != null) state.captured.request.user = as;\n\n return state.captured;\n },\n };\n}\n\n/**\n * The two request-derived document slots (`nonce`/`lang` on\n * `DocumentContextValue`), extracted at the orchestrator call sites\n * because `finishRender` no longer carries `captured` (D1). `dir` is not\n * here: core's Request has no dir-like field (checked\n * core/src/http/request.ts — only `nonce` at :177 and `locale` at :343\n * exist) — an app supplies `dir` via its own convention.\n */\ntype DocumentSlots = {\n nonce?: string;\n lang?: string;\n};\n\n/** Reads document slots directly from core's Request. */\nfunction documentSlotsFrom(captured: CapturedHttp | undefined): DocumentSlots {\n const request = captured?.request;\n\n return { nonce: request?.nonce, lang: request?.locale };\n}\n\nasync function finishRender(\n triple: PageRouteEntry[\"triple\"],\n bundle: PageDataBundle,\n documentSlots: DocumentSlots,\n response: Response,\n loadErrorPage: ErrorPageModuleLoader | undefined,\n): Promise<RenderedPage> {\n // Read from the stage 7 commit, never live off `response` — this function\n // writes (and now reads) the live response zero times. A bundle with no\n // commit (no loader ran at all) simply has no headers/cookies to report.\n const headers = committedHeaders(bundle);\n const cookies = committedCookies(bundle);\n\n // Middleware and validation short-circuits emit no document. Loader-returned\n // Response instances never reach this function.\n if (bundle.shortCircuit) {\n const status =\n bundle.shortCircuit.stage === \"validation\"\n ? bundle.shortCircuit.status\n : (bundle.shortCircuit.statusCode ?? 200);\n return {\n html: \"\",\n status,\n headers,\n cookies,\n data: bundle.pageData,\n bundle,\n };\n }\n\n // The framework's closed-by-default answer (README rule 8): every document\n // is `Cache-Control: private` unless a loader's committed headers already\n // answered for the key. Map-only — the caller applies the returned headers.\n if (headers[\"cache-control\"] === undefined) {\n headers[\"cache-control\"] = \"private\";\n }\n\n // ── stage 9 · RENDER ─────────────────────────────────────────────────────\n // Lazy import: react-dom is a peer used only on this path, so merely\n // loading the server barrel never requires it.\n const { renderToString } = await import(\"react-dom/server\");\n\n // JSON.stringify omits object properties whose value is undefined. Loader\n // `<Head/>`/`<Scripts/>` read this context — metadata and the payload are\n // both already final by this point (stages 1-8 are done), so there is\n // nothing left for the root to await.\n //\n // The payload comes from `buildHydrationPayload` rather than being assembled\n // here, so that this document and the `_loader` route hand the browser the\n // SAME object. See that module for why the two must not drift.\n let documentValue: DocumentContextValue = {\n metadata: bundle.metadata,\n payload: buildHydrationPayload(bundle),\n nonce: documentSlots.nonce,\n lang: documentSlots.lang,\n };\n\n const renderWithContext = (element: ReactNode): string =>\n renderToString(\n createElement(DocumentContext.Provider, {\n value: documentValue,\n children: element,\n }),\n );\n\n // A boundary that throws while rendering escalates to\n // the next enclosing boundary rootward; if none survives, the framework's\n // last-resort terminal renders. `currentError` starts as whatever stage\n // 1-8 already designated (`bundle.error`, undefined for a normal page\n // render) and is replaced by each escalation — `bundle.error` itself is\n // never mutated, staying a truthful stage 1-8 record.\n let currentError = bundle.error;\n let renderTimeThrow = false;\n let body: string;\n\n const renderFrameworkRoot = (): string =>\n renderWithContext(\n createElement(DefaultApp, {\n children: createElement(FrameworkRootBoundary, {}),\n }),\n );\n const renderFrameworkAfterErrorPageFailure = (): string => {\n bundle.errorPage = undefined;\n bundle.metadata = ERROR_PAGE_METADATA;\n documentValue = {\n ...documentValue,\n metadata: bundle.metadata,\n payload: buildHydrationPayload(bundle),\n };\n return renderFrameworkRoot();\n };\n\n const renderErrorPage = async (\n thrown: unknown,\n serializableError: unknown = thrown,\n ): Promise<string | undefined> => {\n if (!loadErrorPage) return undefined;\n\n const props: ServerErrorPageProps = { error: thrown, status: 500 };\n const module = await loadErrorPage();\n registerModules([module as RegisterableModuleNamespace]);\n const errorPage = hydrationErrorPageProps(props, serializableError);\n bundle.errorPage = errorPage;\n bundle.metadata = resolveErrorPageMetadata(module, props);\n documentValue = {\n ...documentValue,\n metadata: bundle.metadata,\n payload: buildHydrationPayload(bundle),\n };\n return renderWithContext(\n wrapRootward(triple, bundle, \"page\", errorPageElement(module, props)),\n );\n };\n\n for (;;) {\n try {\n // The application error page is the framework terminal, never a rival\n // to an authored boundary. It is reached only after no app boundary\n // exists (or after that boundary has itself thrown below).\n if (\n currentError?.boundary.boundaryLevel === \"app\" &&\n !triple.app.ErrorBoundary\n ) {\n try {\n body =\n (await renderErrorPage(\n currentError.originalError ?? currentError.error,\n currentError.error,\n )) ?? renderFrameworkRoot();\n } catch {\n body = renderFrameworkAfterErrorPageFailure();\n }\n renderTimeThrow = true;\n break;\n }\n\n const element = currentError\n ? buildBoundaryElement(triple, bundle, currentError)\n : buildPageElement(triple, bundle);\n\n body = renderWithContext(element);\n break;\n } catch (thrown) {\n renderTimeThrow = true;\n\n if (currentError?.boundary.boundaryLevel === \"app\") {\n // The floor: the app-level boundary's own render just threw, so\n // there is nothing rootward of `app` to escalate to (§2's \"none\n // survives\"). Render the framework's trivial boundary directly —\n // bypassing the app's ErrorBoundary/App component, since that is\n // what just failed — wrapped in DefaultApp so the response is still\n // a complete `<html>` document (default-app.tsx:22-46) rather than\n // a bare `<main>` fragment.\n try {\n body = (await renderErrorPage(thrown)) ?? renderFrameworkRoot();\n } catch {\n body = renderFrameworkAfterErrorPageFailure();\n }\n break;\n }\n\n // Escalate from the level rootward of whatever just threw — searching\n // from the SAME level would re-select the boundary that just failed.\n // A throw not yet attributable to a level (a normal page render, no\n // prior designation) starts the search at `page`.\n const throwingLevel: PageLevelName =\n currentError?.boundary.boundaryLevel === \"layout\"\n ? \"app\"\n : currentError\n ? \"layout\"\n : \"page\";\n\n currentError = buildErrorRecord(\n thrown,\n designateBoundary(throwingLevel, triple),\n );\n }\n }\n\n // Status is chosen after render — the last thing that can change the\n // outcome — and RETURNED, never applied: `finishRender` writes the live\n // response zero times. The caller applies status + headers at one site and\n // flushes immediately after (stage 10a/10b). \"The framework owns the status\n // whenever a boundary renders\" (design/request-lifecycle.md stage 7): ANY\n // boundary — nested or app-level, discovered pre-render or escalated during\n // render — forces 500. The boundary's LEVEL only decides which component\n // renders, never the status; the committed status from stage 7\n // (`bundle.commit.statusCode`) stands only for a page with no error at all\n // — read off the commit, never off the live `response`, same as `headers`\n // above. No committed status (no loader called `setStatusCode`) is the\n // ordinary 200.\n const status = currentError\n ? 500\n : ((bundle as Bundle).commit?.statusCode ?? 200);\n\n const html = emitDocument(body);\n\n return { html, status, headers, cookies, data: bundle.pageData, bundle };\n}\n\n/**\n * Render failures that happen before the page pipeline has a triple (notably a\n * module-load or registration throw). This deliberately owns one terminal\n * attempt: an error-page failure falls straight to FrameworkRootBoundary.\n *\n * There is no triple yet, so there is no trustworthy server composition for\n * the browser to hydrate against — every response this function produces is\n * marked `markNonHydrating` (page-render-bundle.ts), on both the bundle and\n * the document payload, whether or not it managed to render the app's own\n * `error.page.tsx`. A normal app error page reached through `finishRender`\n * renders inside a real triple and stays hydratable; this path never does.\n */\nexport async function renderPageFailure(\n options: RenderPageFailureOptions,\n): Promise<RenderedPage> {\n const { request, response, name, path, thrown, loadErrorPage } = options;\n const bundle: PageDataBundle = markNonHydrating({\n route: { name, path, params: {}, query: {} },\n });\n // No pipeline ran (there is no triple), so there is no commit to read —\n // never a live `response.getHeaders()` read either; see `finishRender`.\n const headers: Record<string, string> = { \"cache-control\": \"private\" };\n\n const { renderToString } = await import(\"react-dom/server\");\n const slots = documentSlotsFrom({ request, response });\n const frameworkPayload = markNonHydrating(buildHydrationPayload(bundle));\n let value: DocumentContextValue = {\n metadata: undefined,\n payload: frameworkPayload,\n nonce: slots.nonce,\n lang: slots.lang,\n };\n const renderWithContext = (element: ReactNode): string =>\n renderToString(\n createElement(DocumentContext.Provider, { value, children: element }),\n );\n let body: string;\n\n try {\n if (!loadErrorPage)\n throw new Error(\"No application error page is configured.\");\n const props: ServerErrorPageProps = { error: thrown, status: 500 };\n const module = await loadErrorPage();\n registerModules([module as RegisterableModuleNamespace]);\n const errorPage = hydrationErrorPageProps(props);\n bundle.errorPage = errorPage;\n value = {\n ...value,\n metadata: resolveErrorPageMetadata(module, props),\n payload: markNonHydrating({ ...frameworkPayload, errorPage }),\n };\n body = renderWithContext(\n createElement(DefaultApp, { children: errorPageElement(module, props) }),\n );\n } catch {\n bundle.errorPage = undefined;\n bundle.metadata = ERROR_PAGE_METADATA;\n value = {\n ...value,\n metadata: bundle.metadata,\n payload: markNonHydrating(buildHydrationPayload(bundle)),\n };\n body = renderWithContext(\n createElement(DefaultApp, {\n children: createElement(FrameworkRootBoundary, {}),\n }),\n );\n }\n\n return {\n html: emitDocument(body),\n status: 500,\n headers,\n cookies: [],\n data: undefined,\n bundle,\n };\n}\n\n// ---------------------------------------------------------------------------\n// The orchestrators\n// ---------------------------------------------------------------------------\n\nexport async function renderPage(\n routeName: string,\n options: RenderPageOptions = {},\n): Promise<RenderedPage | Response> {\n const registry = requireRegistry(options);\n const entry = registry.routes.find(\n (candidate) => candidate.name === routeName,\n );\n\n if (!entry) {\n const known = registry.routes\n .map((candidate) => `\"${candidate.name}\"`)\n .join(\", \");\n\n throw new Error(\n `renderPage(\"${routeName}\"): no route with that name ` +\n `(web/src/server/render-page.ts). Known route names: ${known}. ` +\n \"Fix: use a name from the manifest, or connect the manifest that \" +\n \"declares this one.\",\n );\n }\n\n const url = buildUrl(entry, options.params ?? {}, options.query ?? {});\n const { state, createHttp } = capturingCreateHttp(registry, options.as);\n\n const rendered = await executePageRequest({\n url,\n routes: registry.routes,\n createHttp,\n finish: (bundle) =>\n finishRender(\n entry.triple,\n bundle,\n documentSlotsFrom(state.captured),\n state.captured!.response,\n options.loadErrorPage,\n ),\n });\n\n if (!rendered) {\n throw new Error(\n `renderPage(\"${routeName}\"): the built URL \"${url}\" did not match ` +\n \"stage 1 (web/src/server/render-page.ts). The name resolved but the \" +\n \"matcher disagreed — that is a manifest bug, not a caller bug.\",\n );\n }\n\n return rendered;\n}\n\n/**\n * The URL-based sibling of `renderPage` — the production render surface: a\n * real HTTP server has a URL, not a route name. The url goes STRAIGHT to\n * executePageRequest's stage-1 matcher (no buildUrl), then the same shared\n * tail renders and emits.\n *\n * No-match here is NOT the manifest bug renderPage throws on: an arbitrary\n * URL matching no route is a legitimate 404, and a server must ANSWER it —\n * `{ html: \"\", status: 404 }` with an undefined `bundle` (see RenderedPage).\n */\nexport async function renderPageRequest(\n url: string,\n options: RenderPageRequestOptions = {},\n): Promise<RenderedPage | Response> {\n const registry = requireRegistry(options);\n const { state, createHttp } = capturingCreateHttp(registry, options.as);\n\n const rendered = await executePageRequest({\n url,\n routes: registry.routes,\n createHttp,\n finish: (bundle) =>\n finishRender(\n state.match!.entry.triple,\n bundle,\n documentSlotsFrom(state.captured),\n state.captured!.response,\n options.loadErrorPage,\n ),\n });\n\n if (!rendered) {\n return {\n html: \"\",\n status: 404,\n headers: {},\n cookies: [],\n data: undefined,\n bundle: undefined,\n };\n }\n\n // executePageRequest only produces a bundle after createHttp ran for the\n // match, so the captured entry is present whenever the bundle is.\n return rendered;\n}\n"],"mappings":";;;;;;;;;;;;;;AA8CA,SAAS,iBAAiB,QAAgD;CACxE,MAAM,UAAkC,CAAC;CAEzC,KAAK,MAAM,UAAW,OAAkB,QAAQ,WAAW,CAAC,GAC1D,QAAQ,OAAO,IAAI,YAAY,KAAK,OAAO;CAG7C,OAAO;AACT;;AAGA,SAAS,iBAAiB,QAA0C;CAClE,OAAQ,OAAkB,QAAQ,WAAW,CAAC;AAChD;AA6BA,IAAI;;;;;;AAOJ,SAAgB,kBACd,UACgC;CAChC,MAAM,WAAW;CACjB,qBAAqB;CACrB,OAAO;AACT;AAgEA,SAAS,gBACP,SACoB;CACpB,MAAM,SAAS,QAAQ,UAAU,oBAAoB;CACrD,MAAM,aAAa,QAAQ,cAAc,oBAAoB;CAE7D,IAAI,CAAC,UAAU,CAAC,YACd,MAAM,IAAI,MACR,4SAKF;CAGF,OAAO;EAAE;EAAQ;CAAW;AAC9B;AAEA,SAAS,SACP,OACA,QACA,OACQ;CACR,MAAM,OAAO,MAAM,KAChB,MAAM,GAAG,EACT,KAAK,YAAY;EAChB,IAAI,CAAC,QAAQ,WAAW,GAAG,GAAG,OAAO;EAErC,MAAM,OAAO,QAAQ,MAAM,CAAC;EAC5B,MAAM,QAAQ,OAAO;EAErB,IAAI,UAAU,QACZ,MAAM,IAAI,MACR,eAAe,MAAM,KAAK,kBAAkB,MAAM,KAAK,iBAC3C,KAAK,iGAEA,KAAK,SACxB;EAGF,OAAO,mBAAmB,KAAK;CACjC,CAAC,EACA,KAAK,GAAG;CAEX,MAAM,cAAc,IAAI,gBAAgB,KAAK,EAAE,SAAS;CAExD,OAAO,cAAc,GAAG,KAAK,GAAG,gBAAgB;AAClD;;;;;;;AAYA,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EACV,MAAM;EACN,QAAQ;CACV;CAKF,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- //#region web/src/server/resolve-page-metadata.ts
1
+ //#region ../web/src/server/resolve-page-metadata.ts
2
2
  /**
3
3
  * What `<head>` gets when the page did not render.
4
4
  *
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-page-metadata.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/resolve-page-metadata.ts"],"sourcesContent":["/**\r\n * Stage 8 of the page pipeline — METADATA.\r\n *\r\n * Its own file because the behaviour that matters here is about ERRORS, and\r\n * reaching an error path through the full ten-stage pipeline means standing up\r\n * a real Request/Response pair to observe a `try`/`catch`. See\r\n * `resolve-page-metadata.spec.ts`.\r\n *\r\n * ## Why a page's `metadata` never runs after a failed loader\r\n *\r\n * It used to. `design/request-lifecycle.md` said \"exactly one of data/error\r\n * set\", and stage 8 duly called `metadata({ data: undefined, error })` when a\r\n * loader rejected — while `PageMetadata` declared `data` as always present.\r\n * **The type lied**, so the natural way to write a metadata function was also\r\n * the broken way:\r\n *\r\n * ```ts\r\n * export const metadata: PageMetadata<typeof loader> = ({ data }) => ({\r\n * title: \"Home\",\r\n * description: `${data.products.length} products in stock`,\r\n * });\r\n * ```\r\n *\r\n * All three function-form metadata exports in the reference app were written\r\n * exactly like that, and all three turned a loader's real error — a\r\n * `MissingDataSourceError`, say — into `TypeError: Cannot read properties of\r\n * undefined`, reported against a different file in a different subsystem. The\r\n * cost was never the crash; it was that every future debugging session on a\r\n * failed loader would start by investigating the wrong thing.\r\n *\r\n * The alternative was to widen `data` to `| undefined` and make every author\r\n * handle a path almost none of them care about — and without a discriminant,\r\n * TypeScript cannot narrow `data` from `if (error)` anyway, so authors would\r\n * have reached for `data!` and re-created the lie with extra syntax.\r\n *\r\n * So: a page describes a page it actually has. When there is no data there is\r\n * no page-authored description, and the framework supplies\r\n * {@link ERROR_PAGE_METADATA} instead.\r\n *\r\n * ## Partial failure\r\n *\r\n * Stage 7 runs app, layout and page loaders root-to-leaf, so an ancestor\n * rejection prevents the page loader from starting. `failed` is still the\n * relevant guard here: any recorded error means a boundary renders instead of\n * the page, and metadata describes what is on screen. Describing a page the\n * visitor never received is the same defect in a quieter form.\n *\r\n * If per-page error metadata is ever wanted, it is a separate `errorMetadata`\r\n * export — a distinct signature for a distinct situation, not an arm of this\r\n * one. Nothing has asked for it.\r\n */\r\n\r\nimport type { SharedContext } from \"../index\";\r\nimport type { MetadataOutput, PageMetadata } from \"../metadata\";\r\nimport type { PipelineLoader } from \"./execute-page-request\";\r\n\r\n/**\r\n * What `<head>` gets when the page did not render.\r\n *\r\n * `robots` is the load-bearing member, not `title`. An error render is a\r\n * transient server state that happens to be reachable at a real URL; letting a\r\n * crawler index it puts \"Something went wrong\" in a search result for a page\r\n * that works. `title` is a fallback a boundary is free to improve on.\r\n */\r\nexport const ERROR_PAGE_METADATA: MetadataOutput = Object.freeze({\n title: \"Something went wrong\",\r\n robots: \"noindex\",\r\n});\r\n\r\nexport type ResolvePageMetadataInput = {\r\n /** The page module's `metadata` export — absent, object, or function. */\r\n metadata: PageMetadata<PipelineLoader> | undefined;\r\n /** `bundle.pageData`. Read only when `failed` is false. */\r\n data: unknown;\r\n /** The value an earlier stage already recorded. Diagnostics only. */\r\n error: unknown;\r\n /** Whether an earlier stage recorded an error at all. */\r\n failed: boolean;\r\n shared: Readonly<SharedContext>;\r\n};\r\n\r\nexport type ResolvedPageMetadata = {\r\n metadata: MetadataOutput | undefined;\r\n /**\r\n * Set only when the page's own metadata function threw on the SUCCESS path.\r\n * Returned rather than rethrown so the caller can record it the same way a\r\n * loader throw is recorded — the boundary renders and the framework keeps\r\n * ownership of the status, instead of an exception escaping stage 8.\r\n *\r\n * Never set on the error path: nothing runs there that could throw, and an\r\n * error arriving at stage 8 has already won.\r\n */\r\n thrown?: unknown;\r\n};\r\n\r\n/** The function arm of `PageMetadata`, for the one call this module makes. */\r\ntype PageMetadataFunction = Extract<PageMetadata<PipelineLoader>, (...args: never) => unknown>;\r\n\r\nexport function resolvePageMetadata(input: ResolvePageMetadataInput): ResolvedPageMetadata {\r\n if (input.failed) {\r\n return { metadata: ERROR_PAGE_METADATA };\r\n }\r\n\r\n const { metadata } = input;\r\n\r\n if (typeof metadata !== \"function\") {\r\n return { metadata };\r\n }\r\n\r\n try {\r\n return {\r\n metadata: (metadata as PageMetadataFunction)({\r\n data: input.data as Parameters<PageMetadataFunction>[0][\"data\"],\r\n shared: input.shared,\r\n }),\r\n };\r\n } catch (thrown) {\r\n return { metadata: undefined, thrown };\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;AAgEA,MAAa,sBAAsC,OAAO,OAAO;CAC/D,OAAO;CACP,QAAQ;AACV,CAAC;AA+BD,SAAgB,oBAAoB,OAAuD;CACzF,IAAI,MAAM,QACR,OAAO,EAAE,UAAU,oBAAoB;CAGzC,MAAM,EAAE,aAAa;CAErB,IAAI,OAAO,aAAa,YACtB,OAAO,EAAE,SAAS;CAGpB,IAAI;EACF,OAAO,EACL,UAAW,SAAkC;GAC3C,MAAM,MAAM;GACZ,QAAQ,MAAM;EAChB,CAAC,EACH;CACF,SAAS,QAAQ;EACf,OAAO;GAAE,UAAU;GAAW;EAAO;CACvC;AACF"}
1
+ {"version":3,"file":"resolve-page-metadata.mjs","names":[],"sources":["../../../../../../../web/src/server/resolve-page-metadata.ts"],"sourcesContent":["/**\r\n * Stage 8 of the page pipeline — METADATA.\r\n *\r\n * Its own file because the behaviour that matters here is about ERRORS, and\r\n * reaching an error path through the full ten-stage pipeline means standing up\r\n * a real Request/Response pair to observe a `try`/`catch`. See\r\n * `resolve-page-metadata.spec.ts`.\r\n *\r\n * ## Why a page's `metadata` never runs after a failed loader\r\n *\r\n * It used to. `design/request-lifecycle.md` said \"exactly one of data/error\r\n * set\", and stage 8 duly called `metadata({ data: undefined, error })` when a\r\n * loader rejected — while `PageMetadata` declared `data` as always present.\r\n * **The type lied**, so the natural way to write a metadata function was also\r\n * the broken way:\r\n *\r\n * ```ts\r\n * export const metadata: PageMetadata<typeof loader> = ({ data }) => ({\r\n * title: \"Home\",\r\n * description: `${data.products.length} products in stock`,\r\n * });\r\n * ```\r\n *\r\n * All three function-form metadata exports in the reference app were written\r\n * exactly like that, and all three turned a loader's real error — a\r\n * `MissingDataSourceError`, say — into `TypeError: Cannot read properties of\r\n * undefined`, reported against a different file in a different subsystem. The\r\n * cost was never the crash; it was that every future debugging session on a\r\n * failed loader would start by investigating the wrong thing.\r\n *\r\n * The alternative was to widen `data` to `| undefined` and make every author\r\n * handle a path almost none of them care about — and without a discriminant,\r\n * TypeScript cannot narrow `data` from `if (error)` anyway, so authors would\r\n * have reached for `data!` and re-created the lie with extra syntax.\r\n *\r\n * So: a page describes a page it actually has. When there is no data there is\r\n * no page-authored description, and the framework supplies\r\n * {@link ERROR_PAGE_METADATA} instead.\r\n *\r\n * ## Partial failure\r\n *\r\n * Stage 7 runs app, layout and page loaders root-to-leaf, so an ancestor\n * rejection prevents the page loader from starting. `failed` is still the\n * relevant guard here: any recorded error means a boundary renders instead of\n * the page, and metadata describes what is on screen. Describing a page the\n * visitor never received is the same defect in a quieter form.\n *\r\n * If per-page error metadata is ever wanted, it is a separate `errorMetadata`\r\n * export — a distinct signature for a distinct situation, not an arm of this\r\n * one. Nothing has asked for it.\r\n */\r\n\r\nimport type { SharedContext } from \"../index\";\r\nimport type { MetadataOutput, PageMetadata } from \"../metadata\";\r\nimport type { PipelineLoader } from \"./execute-page-request\";\r\n\r\n/**\r\n * What `<head>` gets when the page did not render.\r\n *\r\n * `robots` is the load-bearing member, not `title`. An error render is a\r\n * transient server state that happens to be reachable at a real URL; letting a\r\n * crawler index it puts \"Something went wrong\" in a search result for a page\r\n * that works. `title` is a fallback a boundary is free to improve on.\r\n */\r\nexport const ERROR_PAGE_METADATA: MetadataOutput = Object.freeze({\n title: \"Something went wrong\",\r\n robots: \"noindex\",\r\n});\r\n\r\nexport type ResolvePageMetadataInput = {\r\n /** The page module's `metadata` export — absent, object, or function. */\r\n metadata: PageMetadata<PipelineLoader> | undefined;\r\n /** `bundle.pageData`. Read only when `failed` is false. */\r\n data: unknown;\r\n /** The value an earlier stage already recorded. Diagnostics only. */\r\n error: unknown;\r\n /** Whether an earlier stage recorded an error at all. */\r\n failed: boolean;\r\n shared: Readonly<SharedContext>;\r\n};\r\n\r\nexport type ResolvedPageMetadata = {\r\n metadata: MetadataOutput | undefined;\r\n /**\r\n * Set only when the page's own metadata function threw on the SUCCESS path.\r\n * Returned rather than rethrown so the caller can record it the same way a\r\n * loader throw is recorded — the boundary renders and the framework keeps\r\n * ownership of the status, instead of an exception escaping stage 8.\r\n *\r\n * Never set on the error path: nothing runs there that could throw, and an\r\n * error arriving at stage 8 has already won.\r\n */\r\n thrown?: unknown;\r\n};\r\n\r\n/** The function arm of `PageMetadata`, for the one call this module makes. */\r\ntype PageMetadataFunction = Extract<PageMetadata<PipelineLoader>, (...args: never) => unknown>;\r\n\r\nexport function resolvePageMetadata(input: ResolvePageMetadataInput): ResolvedPageMetadata {\r\n if (input.failed) {\r\n return { metadata: ERROR_PAGE_METADATA };\r\n }\r\n\r\n const { metadata } = input;\r\n\r\n if (typeof metadata !== \"function\") {\r\n return { metadata };\r\n }\r\n\r\n try {\r\n return {\r\n metadata: (metadata as PageMetadataFunction)({\r\n data: input.data as Parameters<PageMetadataFunction>[0][\"data\"],\r\n shared: input.shared,\r\n }),\r\n };\r\n } catch (thrown) {\r\n return { metadata: undefined, thrown };\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;AAgEA,MAAa,sBAAsC,OAAO,OAAO;CAC/D,OAAO;CACP,QAAQ;AACV,CAAC;AA+BD,SAAgB,oBAAoB,OAAuD;CACzF,IAAI,MAAM,QACR,OAAO,EAAE,UAAU,oBAAoB;CAGzC,MAAM,EAAE,aAAa;CAErB,IAAI,OAAO,aAAa,YACtB,OAAO,EAAE,SAAS;CAGpB,IAAI;EACF,OAAO,EACL,UAAW,SAAkC;GAC3C,MAAM,MAAM;GACZ,QAAQ,MAAM;EAChB,CAAC,EACH;CACF,SAAS,QAAQ;EACf,OAAO;GAAE,UAAU;GAAW;EAAO;CACvC;AACF"}
@@ -1,4 +1,4 @@
1
- //#region web/src/server/resolve-validation-data.ts
1
+ //#region ../web/src/server/resolve-validation-data.ts
2
2
  /** The four names a page may list in `validation.validating`. */
3
3
  const SOURCES = {
4
4
  body: (request) => request.body,
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-validation-data.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/resolve-validation-data.ts"],"sourcesContent":["/**\n * Stage 4's input — what the page's `validation.schema` is handed.\n *\n * ## One request, one parse, one grammar\n *\n * This used to draw its four sources from **two** places. `body` and `headers`\n * came from the request; `query` and `params` came from a match object that\n * `execute-page-request.ts` built by re-parsing the URL itself with\n * `Object.fromEntries(new URLSearchParams(...))`.\n *\n * Core's parser is bracket-aware and preserves repeated keys. That one is\n * neither:\n *\n * ```\n * ?tags=a&tags=b&filter[status]=active\n * core → { tags: [\"a\",\"b\"], filter: { status: \"active\" } }\n * match → { tags: \"b\", \"filter[status]\": \"active\" }\n * ```\n *\n * **So a page's validation rules were checking different data than its loader\n * received.** A rule on `filter.status` could never fire — validation saw a key\n * literally named `filter[status]` — and where a key was sent twice, only the\n * last value was ever examined. A field the author believed was validated was\n * not, and nothing about that was visible from reading the validation rules.\n *\n * Every source is now the request. Core has already parsed the URL by the time\n * this runs; parsing it a second time can only ever produce a second answer.\n *\n * Mirrors core's `validateAll.ts:8-31`, with the page default: **params +\n * query, not body** — a page load is a GET.\n */\n\nexport type ValidationRequest = {\n body?: Record<string, unknown>;\n headers?: Record<string, unknown>;\n query?: Record<string, unknown>;\n params?: Record<string, unknown>;\n};\n\n/** The four names a page may list in `validation.validating`. */\nconst SOURCES = {\n body: (request: ValidationRequest) => request.body,\n query: (request: ValidationRequest) => request.query,\n params: (request: ValidationRequest) => request.params,\n headers: (request: ValidationRequest) => request.headers,\n} as const;\n\nexport function resolveValidationData(\n validating: readonly string[] | undefined,\n request: ValidationRequest,\n): Record<string, unknown> {\n // The page default. `params` last so a route parameter wins a query key of\n // the same name — the URL path is the more authoritative of the two.\n if (!validating || validating.length === 0) {\n return { ...request.query, ...request.params };\n }\n\n let data: Record<string, unknown> = {};\n\n for (const source of validating) {\n const read = SOURCES[source as keyof typeof SOURCES];\n\n // An unknown source name contributes nothing rather than throwing: the\n // list is app-authored, and stage 4 is not the place to litigate it.\n if (read) data = { ...data, ...(read(request) ?? {}) };\n }\n\n return data;\n}\n"],"mappings":";;AAwCA,MAAM,UAAU;CACd,OAAO,YAA+B,QAAQ;CAC9C,QAAQ,YAA+B,QAAQ;CAC/C,SAAS,YAA+B,QAAQ;CAChD,UAAU,YAA+B,QAAQ;AACnD;AAEA,SAAgB,sBACd,YACA,SACyB;CAGzB,IAAI,CAAC,cAAc,WAAW,WAAW,GACvC,OAAO;EAAE,GAAG,QAAQ;EAAO,GAAG,QAAQ;CAAO;CAG/C,IAAI,OAAgC,CAAC;CAErC,KAAK,MAAM,UAAU,YAAY;EAC/B,MAAM,OAAO,QAAQ;EAIrB,IAAI,MAAM,OAAO;GAAE,GAAG;GAAM,GAAI,KAAK,OAAO,KAAK,CAAC;EAAG;CACvD;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"resolve-validation-data.mjs","names":[],"sources":["../../../../../../../web/src/server/resolve-validation-data.ts"],"sourcesContent":["/**\n * Stage 4's input — what the page's `validation.schema` is handed.\n *\n * ## One request, one parse, one grammar\n *\n * This used to draw its four sources from **two** places. `body` and `headers`\n * came from the request; `query` and `params` came from a match object that\n * `execute-page-request.ts` built by re-parsing the URL itself with\n * `Object.fromEntries(new URLSearchParams(...))`.\n *\n * Core's parser is bracket-aware and preserves repeated keys. That one is\n * neither:\n *\n * ```\n * ?tags=a&tags=b&filter[status]=active\n * core → { tags: [\"a\",\"b\"], filter: { status: \"active\" } }\n * match → { tags: \"b\", \"filter[status]\": \"active\" }\n * ```\n *\n * **So a page's validation rules were checking different data than its loader\n * received.** A rule on `filter.status` could never fire — validation saw a key\n * literally named `filter[status]` — and where a key was sent twice, only the\n * last value was ever examined. A field the author believed was validated was\n * not, and nothing about that was visible from reading the validation rules.\n *\n * Every source is now the request. Core has already parsed the URL by the time\n * this runs; parsing it a second time can only ever produce a second answer.\n *\n * Mirrors core's `validateAll.ts:8-31`, with the page default: **params +\n * query, not body** — a page load is a GET.\n */\n\nexport type ValidationRequest = {\n body?: Record<string, unknown>;\n headers?: Record<string, unknown>;\n query?: Record<string, unknown>;\n params?: Record<string, unknown>;\n};\n\n/** The four names a page may list in `validation.validating`. */\nconst SOURCES = {\n body: (request: ValidationRequest) => request.body,\n query: (request: ValidationRequest) => request.query,\n params: (request: ValidationRequest) => request.params,\n headers: (request: ValidationRequest) => request.headers,\n} as const;\n\nexport function resolveValidationData(\n validating: readonly string[] | undefined,\n request: ValidationRequest,\n): Record<string, unknown> {\n // The page default. `params` last so a route parameter wins a query key of\n // the same name — the URL path is the more authoritative of the two.\n if (!validating || validating.length === 0) {\n return { ...request.query, ...request.params };\n }\n\n let data: Record<string, unknown> = {};\n\n for (const source of validating) {\n const read = SOURCES[source as keyof typeof SOURCES];\n\n // An unknown source name contributes nothing rather than throwing: the\n // list is app-authored, and stage 4 is not the place to litigate it.\n if (read) data = { ...data, ...(read(request) ?? {}) };\n }\n\n return data;\n}\n"],"mappings":";;AAwCA,MAAM,UAAU;CACd,OAAO,YAA+B,QAAQ;CAC9C,QAAQ,YAA+B,QAAQ;CAC/C,SAAS,YAA+B,QAAQ;CAChD,UAAU,YAA+B,QAAQ;AACnD;AAEA,SAAgB,sBACd,YACA,SACyB;CAGzB,IAAI,CAAC,cAAc,WAAW,WAAW,GACvC,OAAO;EAAE,GAAG,QAAQ;EAAO,GAAG,QAAQ;CAAO;CAG/C,IAAI,OAAgC,CAAC;CAErC,KAAK,MAAM,UAAU,YAAY;EAC/B,MAAM,OAAO,QAAQ;EAIrB,IAAI,MAAM,OAAO;GAAE,GAAG;GAAM,GAAI,KAAK,OAAO,KAAK,CAAC;EAAG;CACvD;CAEA,OAAO;AACT"}
@@ -1,7 +1,7 @@
1
1
  import { PageLevelName } from "./execute-page-request.types.mjs";
2
2
  import { Response } from "@warlock.js/core";
3
3
 
4
- //#region web/src/server/settle-page-response.d.ts
4
+ //#region ../web/src/server/settle-page-response.d.ts
5
5
  /** A single committed response header, in application order. */
6
6
  type BufferedHeader = {
7
7
  key: string;
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
 
3
- //#region web/src/server/settle-page-response.ts
3
+ //#region ../web/src/server/settle-page-response.ts
4
4
  const LEVEL_ORDER = [
5
5
  "app",
6
6
  "layout",
@@ -1 +1 @@
1
- {"version":3,"file":"settle-page-response.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/settle-page-response.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { Response } from \"@warlock.js/core\";\nimport type {\n PageBoundaryDesignation,\n PageErrorRecord,\n PageLevelName,\n PageRouteEntry,\n} from \"./execute-page-request.types\";\n\nexport const LEVEL_ORDER: readonly PageLevelName[] = [\"app\", \"layout\", \"page\"];\n\nexport function designateBoundary(\n throwingLevel: PageLevelName,\n triple: PageRouteEntry[\"triple\"],\n): PageBoundaryDesignation {\n const throwingIndex = LEVEL_ORDER.indexOf(throwingLevel);\n\n for (let index = throwingIndex; index >= 0; index--) {\n const level = LEVEL_ORDER[index];\n\n if (triple[level].ErrorBoundary) {\n return { throwingLevel, boundaryLevel: level };\n }\n }\n\n return { throwingLevel, boundaryLevel: \"app\" };\n}\n\nexport function buildErrorRecord(\n thrown: unknown,\n boundary: PageBoundaryDesignation,\n requestPath?: string,\n): PageErrorRecord {\n const digest = randomUUID();\n\n console.error(\"[warlock] page error\", digest, ...(requestPath ? [requestPath] : []), thrown);\n\n if (process.env.NODE_ENV === \"production\") {\n const surrogate = new Error(\"An unexpected error occurred.\");\n\n (surrogate as Error & { digest: string }).digest = digest;\n\n return { originalError: thrown, error: surrogate, boundary, digest, scrubbed: true };\n }\n\n // `error` already IS the real thrown value here — `originalError` only ever\n // needs to diverge from it on the scrubbed (production) path above. Leaving\n // it `undefined` rather than a redundant second reference to the same object\n // keeps the record's `toEqual` shape honest (undefined properties compare as\n // absent) and readers still get the real error via\n // `record.originalError ?? record.error`.\n return { originalError: undefined, error: thrown, boundary, digest, scrubbed: false };\n}\n\n// ---------------------------------------------------------------------------\n// Stage 6/7 — buffered per-level responses, and the root→leaf commit\n// ---------------------------------------------------------------------------\n\n/** A single committed response header, in application order. */\nexport type BufferedHeader = { key: string; value: string };\n\n/** A single committed response cookie — the shape `applyBufferedCookie` replays. */\nexport type BufferedCookie = {\n name: string;\n value: unknown;\n options?: Record<string, unknown>;\n};\n\n/** The two loader short-circuit kinds a buffered response can signal. */\nexport type LoaderShortCircuitKind = \"redirect\" | \"notFound\";\n\nconst LOADER_SHORT_CIRCUIT = Symbol(\"warlock.page.loaderShortCircuit\");\n\n/**\n * What `response.redirect()` / `response.permanentRedirect()` / `response.notFound()`\n * return from inside a loader — a branded value the stage 7 settle scan\n * recognises by symbol, never by shape (so an app returning an\n * accidentally-similar plain object can't be mistaken for one).\n */\nexport type LoaderShortCircuitSignal = {\n readonly [LOADER_SHORT_CIRCUIT]: true;\n kind: LoaderShortCircuitKind;\n statusCode: number;\n url?: string;\n body?: unknown;\n};\n\nexport function isLoaderShortCircuit(value: unknown): value is LoaderShortCircuitSignal {\n return Boolean(value) && typeof value === \"object\" && LOADER_SHORT_CIRCUIT in (value as object);\n}\n\n/** One level's scratch buffer — what `response.header()`/`.cookie()` write into. */\nexport type LevelBuffer = {\n headers: BufferedHeader[];\n cookies: BufferedCookie[];\n statusCode?: number;\n};\n\nexport function createLevelBuffer(): LevelBuffer {\n return { headers: [], cookies: [] };\n}\n\n/**\n * The response surface a LOADER sees — never the live core `Response`.\n * `header()`/`cookie()` queue into the level's own buffer; nothing here\n * touches the real reply. `redirect()`/`permanentRedirect()`/`notFound()`\n * queue the buffer's own status (+ `Location`, for the two redirects) AND\n * return the branded signal stage 7 detects — the loader is expected to\n * `return response.redirect(...)`.\n */\nexport type BufferedResponse = {\n header(key: string, value: unknown): BufferedResponse;\n headers(bag: Record<string, unknown>): BufferedResponse;\n cookie(name: string, value: unknown, options?: Record<string, unknown>): BufferedResponse;\n setStatusCode(statusCode: number): BufferedResponse;\n redirect(url: string, statusCode?: number): LoaderShortCircuitSignal;\n permanentRedirect(url: string): LoaderShortCircuitSignal;\n notFound(body?: unknown): LoaderShortCircuitSignal;\n};\n\nexport function createBufferedResponse(buffer: LevelBuffer): BufferedResponse {\n const bufferedResponse: BufferedResponse = {\n header(key, value) {\n buffer.headers.push({ key, value: String(value) });\n return bufferedResponse;\n },\n headers(bag) {\n for (const [key, value] of Object.entries(bag)) bufferedResponse.header(key, value);\n return bufferedResponse;\n },\n cookie(name, value, options) {\n buffer.cookies.push({ name, value, options });\n return bufferedResponse;\n },\n setStatusCode(statusCode) {\n buffer.statusCode = statusCode;\n return bufferedResponse;\n },\n redirect(url, statusCode = 302) {\n buffer.statusCode = statusCode;\n buffer.headers.push({ key: \"Location\", value: url });\n return { [LOADER_SHORT_CIRCUIT]: true, kind: \"redirect\", statusCode, url, body: undefined };\n },\n permanentRedirect(url) {\n return bufferedResponse.redirect(url, 301);\n },\n notFound(body) {\n buffer.statusCode = 404;\n return { [LOADER_SHORT_CIRCUIT]: true, kind: \"notFound\", statusCode: 404, url: undefined, body };\n },\n };\n\n return bufferedResponse;\n}\n\n/** Stage 7's folded, applied result — what `bundle.commit` carries. */\nexport type PageResponseCommit = {\n committedLevels: PageLevelName[];\n headers: BufferedHeader[];\n cookies: BufferedCookie[];\n statusCode?: number;\n};\n\n/**\n * Fold every surviving buffer root→leaf into ONE map per key (header key\n * case-insensitively, cookie by name) — leafward wins, insertion position\n * stays where the key FIRST appeared. Applies the folded headers and status\n * to the REAL response (`header()`/`setStatusCode()` are idempotent keyed\n * sets, so this is safe even though `commitBuffers` can run before render\n * changes its mind about the status later). Cookies are NOT applied to the\n * real response here — `cookie()` APPENDS, so mirroring it here and again at\n * the wire emit would duplicate every `Set-Cookie`. The single application\n * site is the emit (`create-page-route-handler.ts`, via `applyBufferedCookie`\n * over `bundle.commit.cookies`).\n */\nexport function commitBuffers(\n response: Response,\n buffers: Record<PageLevelName, LevelBuffer>,\n committedLevels: PageLevelName[],\n): PageResponseCommit {\n const headerOrder: string[] = [];\n const headerMap = new Map<string, BufferedHeader>();\n const cookieOrder: string[] = [];\n const cookieMap = new Map<string, BufferedCookie>();\n let statusCode: number | undefined;\n\n for (const level of committedLevels) {\n const buffer = buffers[level];\n\n for (const header of buffer.headers) {\n const key = header.key.toLowerCase();\n if (!headerMap.has(key)) headerOrder.push(key);\n headerMap.set(key, header);\n }\n\n for (const cookie of buffer.cookies) {\n if (!cookieMap.has(cookie.name)) cookieOrder.push(cookie.name);\n cookieMap.set(cookie.name, cookie);\n }\n\n if (buffer.statusCode !== undefined) statusCode = buffer.statusCode;\n }\n\n const headers = headerOrder.map(key => headerMap.get(key)!);\n const cookies = cookieOrder.map(name => cookieMap.get(name)!);\n\n for (const header of headers) response.header(header.key, header.value);\n if (statusCode !== undefined) response.setStatusCode(statusCode);\n\n return { committedLevels, headers, cookies, statusCode };\n}\n"],"mappings":";;;AASA,MAAa,cAAwC;CAAC;CAAO;CAAU;AAAM;AAE7E,SAAgB,kBACd,eACA,QACyB;CACzB,MAAM,gBAAgB,YAAY,QAAQ,aAAa;CAEvD,KAAK,IAAI,QAAQ,eAAe,SAAS,GAAG,SAAS;EACnD,MAAM,QAAQ,YAAY;EAE1B,IAAI,OAAO,OAAO,eAChB,OAAO;GAAE;GAAe,eAAe;EAAM;CAEjD;CAEA,OAAO;EAAE;EAAe,eAAe;CAAM;AAC/C;AAEA,SAAgB,iBACd,QACA,UACA,aACiB;CACjB,MAAM,SAAS,WAAW;CAE1B,QAAQ,MAAM,wBAAwB,QAAQ,GAAI,cAAc,CAAC,WAAW,IAAI,CAAC,GAAI,MAAM;CA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YAAY;IAAK,KAAK;IAAW;GAAK;EACjG;CACF;CAEA,OAAO;AACT;;;;;;;;;;;;;AAsBA,SAAgB,cACd,UACA,SACA,iBACoB;CACpB,MAAM,cAAwB,CAAC;CAC/B,MAAM,4BAAY,IAAI,IAA4B;CAClD,MAAM,cAAwB,CAAC;CAC/B,MAAM,4BAAY,IAAI,IAA4B;CAClD,IAAI;CAEJ,KAAK,MAAM,SAAS,iBAAiB;EACnC,MAAM,SAAS,QAAQ;EAEvB,KAAK,MAAM,UAAU,OAAO,SAAS;GACnC,MAAM,MAAM,OAAO,IAAI,YAAY;GACnC,IAAI,CAAC,UAAU,IAAI,GAAG,GAAG,YAAY,KAAK,GAAG;GAC7C,UAAU,IAAI,KAAK,MAAM;EAC3B;EAEA,KAAK,MAAM,UAAU,OAAO,SAAS;GACnC,IAAI,CAAC,UAAU,IAAI,OAAO,IAAI,GAAG,YAAY,KAAK,OAAO,IAAI;GAC7D,UAAU,IAAI,OAAO,MAAM,MAAM;EACnC;EAEA,IAAI,OAAO,eAAe,QAAW,aAAa,OAAO;CAC3D;CAEA,MAAM,UAAU,YAAY,KAAI,QAAO,UAAU,IAAI,GAAG,CAAE;CAC1D,MAAM,UAAU,YAAY,KAAI,SAAQ,UAAU,IAAI,IAAI,CAAE;CAE5D,KAAK,MAAM,UAAU,SAAS,SAAS,OAAO,OAAO,KAAK,OAAO,KAAK;CACtE,IAAI,eAAe,QAAW,SAAS,cAAc,UAAU;CAE/D,OAAO;EAAE;EAAiB;EAAS;EAAS;CAAW;AACzD"}
1
+ {"version":3,"file":"settle-page-response.mjs","names":[],"sources":["../../../../../../../web/src/server/settle-page-response.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { Response } from \"@warlock.js/core\";\nimport type {\n PageBoundaryDesignation,\n PageErrorRecord,\n PageLevelName,\n PageRouteEntry,\n} from \"./execute-page-request.types\";\n\nexport const LEVEL_ORDER: readonly PageLevelName[] = [\"app\", \"layout\", \"page\"];\n\nexport function designateBoundary(\n throwingLevel: PageLevelName,\n triple: PageRouteEntry[\"triple\"],\n): PageBoundaryDesignation {\n const throwingIndex = LEVEL_ORDER.indexOf(throwingLevel);\n\n for (let index = throwingIndex; index >= 0; index--) {\n const level = LEVEL_ORDER[index];\n\n if (triple[level].ErrorBoundary) {\n return { throwingLevel, boundaryLevel: level };\n }\n }\n\n return { throwingLevel, boundaryLevel: \"app\" };\n}\n\nexport function buildErrorRecord(\n thrown: unknown,\n boundary: PageBoundaryDesignation,\n requestPath?: string,\n): PageErrorRecord {\n const digest = randomUUID();\n\n console.error(\"[warlock] page error\", digest, ...(requestPath ? [requestPath] : []), thrown);\n\n if (process.env.NODE_ENV === \"production\") {\n const surrogate = new Error(\"An unexpected error occurred.\");\n\n (surrogate as Error & { digest: string }).digest = digest;\n\n return { originalError: thrown, error: surrogate, boundary, digest, scrubbed: true };\n }\n\n // `error` already IS the real thrown value here — `originalError` only ever\n // needs to diverge from it on the scrubbed (production) path above. Leaving\n // it `undefined` rather than a redundant second reference to the same object\n // keeps the record's `toEqual` shape honest (undefined properties compare as\n // absent) and readers still get the real error via\n // `record.originalError ?? record.error`.\n return { originalError: undefined, error: thrown, boundary, digest, scrubbed: false };\n}\n\n// ---------------------------------------------------------------------------\n// Stage 6/7 — buffered per-level responses, and the root→leaf commit\n// ---------------------------------------------------------------------------\n\n/** A single committed response header, in application order. */\nexport type BufferedHeader = { key: string; value: string };\n\n/** A single committed response cookie — the shape `applyBufferedCookie` replays. */\nexport type BufferedCookie = {\n name: string;\n value: unknown;\n options?: Record<string, unknown>;\n};\n\n/** The two loader short-circuit kinds a buffered response can signal. */\nexport type LoaderShortCircuitKind = \"redirect\" | \"notFound\";\n\nconst LOADER_SHORT_CIRCUIT = Symbol(\"warlock.page.loaderShortCircuit\");\n\n/**\n * What `response.redirect()` / `response.permanentRedirect()` / `response.notFound()`\n * return from inside a loader — a branded value the stage 7 settle scan\n * recognises by symbol, never by shape (so an app returning an\n * accidentally-similar plain object can't be mistaken for one).\n */\nexport type LoaderShortCircuitSignal = {\n readonly [LOADER_SHORT_CIRCUIT]: true;\n kind: LoaderShortCircuitKind;\n statusCode: number;\n url?: string;\n body?: unknown;\n};\n\nexport function isLoaderShortCircuit(value: unknown): value is LoaderShortCircuitSignal {\n return Boolean(value) && typeof value === \"object\" && LOADER_SHORT_CIRCUIT in (value as object);\n}\n\n/** One level's scratch buffer — what `response.header()`/`.cookie()` write into. */\nexport type LevelBuffer = {\n headers: BufferedHeader[];\n cookies: BufferedCookie[];\n statusCode?: number;\n};\n\nexport function createLevelBuffer(): LevelBuffer {\n return { headers: [], cookies: [] };\n}\n\n/**\n * The response surface a LOADER sees — never the live core `Response`.\n * `header()`/`cookie()` queue into the level's own buffer; nothing here\n * touches the real reply. `redirect()`/`permanentRedirect()`/`notFound()`\n * queue the buffer's own status (+ `Location`, for the two redirects) AND\n * return the branded signal stage 7 detects — the loader is expected to\n * `return response.redirect(...)`.\n */\nexport type BufferedResponse = {\n header(key: string, value: unknown): BufferedResponse;\n headers(bag: Record<string, unknown>): BufferedResponse;\n cookie(name: string, value: unknown, options?: Record<string, unknown>): BufferedResponse;\n setStatusCode(statusCode: number): BufferedResponse;\n redirect(url: string, statusCode?: number): LoaderShortCircuitSignal;\n permanentRedirect(url: string): LoaderShortCircuitSignal;\n notFound(body?: unknown): LoaderShortCircuitSignal;\n};\n\nexport function createBufferedResponse(buffer: LevelBuffer): BufferedResponse {\n const bufferedResponse: BufferedResponse = {\n header(key, value) {\n buffer.headers.push({ key, value: String(value) });\n return bufferedResponse;\n },\n headers(bag) {\n for (const [key, value] of Object.entries(bag)) bufferedResponse.header(key, value);\n return bufferedResponse;\n },\n cookie(name, value, options) {\n buffer.cookies.push({ name, value, options });\n return bufferedResponse;\n },\n setStatusCode(statusCode) {\n buffer.statusCode = statusCode;\n return bufferedResponse;\n },\n redirect(url, statusCode = 302) {\n buffer.statusCode = statusCode;\n buffer.headers.push({ key: \"Location\", value: url });\n return { [LOADER_SHORT_CIRCUIT]: true, kind: \"redirect\", statusCode, url, body: undefined };\n },\n permanentRedirect(url) {\n return bufferedResponse.redirect(url, 301);\n },\n notFound(body) {\n buffer.statusCode = 404;\n return { [LOADER_SHORT_CIRCUIT]: true, kind: \"notFound\", statusCode: 404, url: undefined, body };\n },\n };\n\n return bufferedResponse;\n}\n\n/** Stage 7's folded, applied result — what `bundle.commit` carries. */\nexport type PageResponseCommit = {\n committedLevels: PageLevelName[];\n headers: BufferedHeader[];\n cookies: BufferedCookie[];\n statusCode?: number;\n};\n\n/**\n * Fold every surviving buffer root→leaf into ONE map per key (header key\n * case-insensitively, cookie by name) — leafward wins, insertion position\n * stays where the key FIRST appeared. Applies the folded headers and status\n * to the REAL response (`header()`/`setStatusCode()` are idempotent keyed\n * sets, so this is safe even though `commitBuffers` can run before render\n * changes its mind about the status later). Cookies are NOT applied to the\n * real response here — `cookie()` APPENDS, so mirroring it here and again at\n * the wire emit would duplicate every `Set-Cookie`. The single application\n * site is the emit (`create-page-route-handler.ts`, via `applyBufferedCookie`\n * over `bundle.commit.cookies`).\n */\nexport function commitBuffers(\n response: Response,\n buffers: Record<PageLevelName, LevelBuffer>,\n committedLevels: PageLevelName[],\n): PageResponseCommit {\n const headerOrder: string[] = [];\n const headerMap = new Map<string, BufferedHeader>();\n const cookieOrder: string[] = [];\n const cookieMap = new Map<string, BufferedCookie>();\n let statusCode: number | undefined;\n\n for (const level of committedLevels) {\n const buffer = buffers[level];\n\n for (const header of buffer.headers) {\n const key = header.key.toLowerCase();\n if (!headerMap.has(key)) headerOrder.push(key);\n headerMap.set(key, header);\n }\n\n for (const cookie of buffer.cookies) {\n if (!cookieMap.has(cookie.name)) cookieOrder.push(cookie.name);\n cookieMap.set(cookie.name, cookie);\n }\n\n if (buffer.statusCode !== undefined) statusCode = buffer.statusCode;\n }\n\n const headers = headerOrder.map(key => headerMap.get(key)!);\n const cookies = cookieOrder.map(name => cookieMap.get(name)!);\n\n for (const header of headers) response.header(header.key, header.value);\n if (stat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,IAAI,GAAG,CAAE;CAC1D,MAAM,UAAU,YAAY,KAAI,SAAQ,UAAU,IAAI,IAAI,CAAE;CAE5D,KAAK,MAAM,UAAU,SAAS,SAAS,OAAO,OAAO,KAAK,OAAO,KAAK;CACtE,IAAI,eAAe,QAAW,SAAS,cAAc,UAAU;CAE/D,OAAO;EAAE;EAAiB;EAAS;EAAS;CAAW;AACzD"}
@@ -1,4 +1,4 @@
1
- //#region web/src/server/stylesheet-urls.d.ts
1
+ //#region ../web/src/server/stylesheet-urls.d.ts
2
2
  /**
3
3
  * A stylesheet Vite serves in DEV must be requested with `?direct`.
4
4
  *
@@ -2,7 +2,7 @@ import { CLIENT_ASSET_URL_PREFIX } from "./client-asset-url-prefix.mjs";
2
2
  import { readFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
 
5
- //#region web/src/server/stylesheet-urls.ts
5
+ //#region ../web/src/server/stylesheet-urls.ts
6
6
  /**
7
7
  * Which stylesheets a REGISTERED HANDLER must link, in each of the two modes.
8
8
  *
@@ -1 +1 @@
1
- {"version":3,"file":"stylesheet-urls.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/stylesheet-urls.ts"],"sourcesContent":["/**\n * Which stylesheets a REGISTERED HANDLER must link, in each of the two modes.\n *\n * WHY THIS EXISTS AT ALL. Nothing used to put CSS into the server-rendered\n * document. A stylesheet reached the browser only because the CLIENT bundle\n * imported it, which means JavaScript applied it after the module graph\n * loaded — so every full page load painted unstyled first and restyled a\n * moment later. The markup was correct the whole time, which is precisely why\n * it was easy to miss.\n *\n * THE SCOPE IS PER HANDLER, NOT PER APPLICATION. Every page renders inside\n * `[root, ...outer-to-inner matched layouts, page]` — that is the exact triple\n * (widened to a chain) `create-page-route-handler.ts` loads per request — so a\n * handler's CSS is the ordered, deduped union of what those specific source\n * files pull in, and nothing else. Collecting across the WHOLE application\n * (every page's manifest entry, every root import) is the bug this shape\n * exists to avoid: it ships page B's stylesheet on page A's response, and it\n * only gets worse as an application grows.\n *\n * The two modes learn the answer from different places, and neither can use\n * the other's:\n *\n * - PRODUCTION reads Vite's client manifest, matching each source file's own\n * id and walking its recorded `css` and imported chunks.\n * - DEV has no manifest — Vite serves modules on demand — so the URLs are\n * derived from each source file's own import statements.\n */\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { CLIENT_ASSET_URL_PREFIX } from \"./client-asset-url-prefix\";\n\n/** Stylesheet extensions Vite can serve directly. Mirrors the build's list. */\nconst STYLE_EXTENSIONS = [\".css\", \".scss\", \".sass\", \".less\", \".styl\"];\n\n/**\n * A stylesheet Vite serves in DEV must be requested with `?direct`.\n *\n * Without it Vite answers the same URL with `text/javascript` — its CSS-as-JS\n * module transform, meant for `import \"./app.css\"` — and a\n * `<link rel=\"stylesheet\">` pointing at a JavaScript response applies\n * NOTHING, silently. No console error, no network failure, just an unstyled\n * page. `?direct` is what makes Vite reply with real `text/css`.\n */\nexport const VITE_DIRECT_CSS_QUERY = \"?direct\";\n\n/**\n * ONE source file's own directly imported stylesheets, as dev URLs.\n *\n * Dev has no manifest, so the source is the file itself: whatever it imports\n * with a stylesheet extension is what it needs. This is deliberately narrow —\n * it answers \"what CSS does THIS file set up\", not \"what CSS does the whole\n * module graph this file eventually reaches end up pulling in\" — because the\n * latter would require reproducing Vite's module graph, which is precisely\n * what dev has no manifest to shortcut.\n *\n * The narrowness is the honest part: production splits CSS per chunk and can\n * follow imported chunks (`productionStylesheetUrls` below); dev can only read\n * the ONE file handed to it. A page whose own module imports its own\n * stylesheet still gets it in dev — Vite's client graph injects it as before —\n * it simply is not render-blocking the way a chain member's own import is.\n *\n * Called once per chain member — root, then every matched layout outer to\n * inner, then the page — by the installers below, which is what turns \"one\n * file's own imports\" into a handler's whole CSS chain.\n *\n * Specifiers are resolved against `sourceFile` and expressed relative to\n * `appRoot`, because that is the shape Vite's dev server serves from.\n */\nexport function devStylesheetUrls(appRoot: string, sourceFile: string): string[] {\n let source: string;\n\n try {\n source = readFileSync(sourceFile, \"utf-8\");\n } catch {\n return [];\n }\n\n const urls: string[] = [];\n const pattern = /\\bimport\\s*(?:\\(\\s*)?[\"']([^\"']+)[\"']/g;\n\n let match = pattern.exec(source);\n\n while (match !== null) {\n const specifier = match[1];\n const lowered = specifier.toLowerCase();\n\n if (STYLE_EXTENSIONS.some((extension) => lowered.endsWith(extension))) {\n const absolute = path.resolve(path.dirname(sourceFile), specifier);\n const relative = path.relative(appRoot, absolute).split(path.sep).join(\"/\");\n\n // Outside the app root Vite would need an `/@fs/` URL and a widened\n // `fs.allow`; a stylesheet living there is unusual enough that guessing\n // is worse than leaving it to the client import.\n if (!relative.startsWith(\"..\")) {\n const url = `/${relative}${VITE_DIRECT_CSS_QUERY}`;\n\n if (!urls.includes(url)) urls.push(url);\n }\n }\n\n match = pattern.exec(source);\n }\n\n return urls;\n}\n\n/**\n * ONE handler's whole dev CSS chain: every `sourceFiles` member's own direct\n * stylesheet imports (`devStylesheetUrls`), in the order given — the caller\n * passes `[root, ...outer-to-inner matched layouts, page]` — concatenated and\n * deduped across the WHOLE chain, not just within one file.\n *\n * Cross-file dedup matters as much as within-file dedup: an application-wide\n * `app.css` imported by both the root and a page must still produce one\n * `<link>`, not two.\n */\nexport function devHandlerStylesheetUrls(\n appRoot: string,\n sourceFiles: readonly string[],\n): string[] {\n const urls: string[] = [];\n\n for (const sourceFile of sourceFiles) {\n for (const url of devStylesheetUrls(appRoot, sourceFile)) {\n if (!urls.includes(url)) urls.push(url);\n }\n }\n\n return urls;\n}\n\ntype ManifestEntry = {\n css?: unknown;\n imports?: unknown;\n};\n\n/**\n * Find the manifest key for an app-root-relative POSIX source id.\n *\n * VITE KEYS BY SOURCE PATH RELATIVE TO ITS OWN `root`, not to the app's\n * `appRoot` — the client build's `root` is the framework's own package\n * (`build-client.ts`), so a key for an app source file carries a `../`-laden\n * prefix (`\"../my-app/src/web/root.tsx\"`) rather than matching `sourceFile`\n * (`\"src/web/root.tsx\"`) byte for byte. The two forms always share the same\n * TAIL, though — both are anchored at the same file — so an exact match is\n * tried first (the case where the client build's root IS the app root, which\n * every fixture and every test below uses) and a `/`-boundary suffix match\n * second, rather than trying to reconstruct the build's own root here, which\n * this runtime read has no way to independently confirm.\n */\nfunction findManifestKey(\n manifest: Record<string, ManifestEntry | undefined>,\n sourceFile: string,\n): string | undefined {\n if (manifest[sourceFile] !== undefined) return sourceFile;\n\n const suffix = `/${sourceFile}`;\n\n for (const key of Object.keys(manifest)) {\n if (key.endsWith(suffix)) return key;\n }\n\n return undefined;\n}\n\n/**\n * Every stylesheet reachable from ONE manifest entry: its own recorded `css`,\n * plus the same walk repeated over every chunk it STATICALLY `imports`.\n *\n * `imports` only, never `dynamicImports`. Vite's manifest records\n * `dynamicImports` on shared entry points (the hydration entry names every\n * page as one) precisely because the browser must NOT download them eagerly —\n * walking that array here would pull every other page's CSS onto this one,\n * which is the exact \"unrelated pages\" leak this module exists to end.\n * `imports`, by contrast, are chunks THIS module synchronously depends on:\n * code Vite split out of it but that loads whenever it does, so their CSS is\n * this handler's CSS too.\n *\n * `visited` guards against a chunk graph cycle; sharing one set across the\n * whole walk from a single entry is enough; a shared chunk revisited from a\n * SEPARATE top-level entry (root vs. a layout vs. the page) is deliberately\n * walked again — the final merge in `productionStylesheetUrls` dedupes by URL,\n * and a fresh `visited` set per entry is simpler to reason about than one\n * threaded across unrelated chains.\n */\nfunction collectManifestCss(\n manifest: Record<string, ManifestEntry | undefined>,\n key: string,\n visited: Set<string>,\n): string[] {\n if (visited.has(key)) return [];\n visited.add(key);\n\n const entry = manifest[key];\n if (entry === undefined) return [];\n\n const ownCss = Array.isArray(entry.css)\n ? entry.css.filter((file): file is string => typeof file === \"string\" && file !== \"\")\n : [];\n\n const imports = Array.isArray(entry.imports)\n ? entry.imports.filter((id): id is string => typeof id === \"string\")\n : [];\n\n return [\n ...ownCss,\n ...imports.flatMap((importedKey) => collectManifestCss(manifest, importedKey, visited)),\n ];\n}\n\n/**\n * ONE handler's whole production CSS chain.\n *\n * `sourceFiles` is `[root, ...outer-to-inner matched layouts, page]`, each an\n * app-root-relative POSIX source id — the SAME id\n * `install-page-routes-from-manifest.ts` already carries as `sourceFile` on\n * every manifest entry, because that identity is what lets this function match\n * EXPLICITLY rather than guess: every id is looked up on its own\n * (`findManifestKey`), its own chunk's CSS is collected\n * (`collectManifestCss`), and an id with no matching entry contributes\n * nothing — it is never treated as license to fall back to scanning the whole\n * manifest, which is what let an unrelated page's CSS leak onto this handler\n * before.\n *\n * Duplicates are collapsed and order is preserved across the WHOLE chain, in\n * the order `sourceFiles` was given — root's own CSS first, then each\n * layout's outer to inner, then the page's — so cascade order matches the\n * chain's own outer-to-inner rendering order.\n *\n * A missing or malformed manifest returns NOTHING rather than throwing. The\n * hydration resolver already fails loudly on exactly those conditions, from\n * exactly the same file, and it runs first — a second, worse error for the\n * same cause helps nobody.\n */\nexport function productionStylesheetUrls(\n clientDir: string,\n sourceFiles: readonly string[],\n): string[] {\n const manifestPath = path.join(clientDir, \".vite\", \"manifest.json\");\n\n let manifest: Record<string, ManifestEntry | undefined>;\n\n try {\n manifest = JSON.parse(readFileSync(manifestPath, \"utf-8\")) as Record<\n string,\n ManifestEntry | undefined\n >;\n } catch {\n return [];\n }\n\n if (typeof manifest !== \"object\" || manifest === null) return [];\n\n const files: string[] = [];\n\n for (const sourceFile of sourceFiles) {\n const key = findManifestKey(manifest, sourceFile);\n if (key === undefined) continue;\n\n files.push(...collectManifestCss(manifest, key, new Set()));\n }\n\n const urls: string[] = [];\n\n for (const file of files) {\n // Built EXACTLY as the hydration entry's URL is built — `/${file}`, then\n // checked against the prefix — rather than reassembled from a basename.\n // The manifest already records `assets/root-<hash>.css`, and rebuilding\n // that path here would be a second expression of a convention\n // `client-asset-url-prefix.ts` owns.\n const url = `/${file}`;\n\n // A stylesheet outside the directory the asset route mounts would 404.\n // Dropped rather than emitted, because a dead <link> in <head> is a\n // silent styling failure — the exact thing this module exists to end.\n if (!url.startsWith(`${CLIENT_ASSET_URL_PREFIX}/`)) continue;\n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IAAI,CAAC,KAAK,SAAS,GAAG,GAAG,KAAK,KAAK,GAAG;CACxC;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"stylesheet-urls.mjs","names":[],"sources":["../../../../../../../web/src/server/stylesheet-urls.ts"],"sourcesContent":["/**\n * Which stylesheets a REGISTERED HANDLER must link, in each of the two modes.\n *\n * WHY THIS EXISTS AT ALL. Nothing used to put CSS into the server-rendered\n * document. A stylesheet reached the browser only because the CLIENT bundle\n * imported it, which means JavaScript applied it after the module graph\n * loaded — so every full page load painted unstyled first and restyled a\n * moment later. The markup was correct the whole time, which is precisely why\n * it was easy to miss.\n *\n * THE SCOPE IS PER HANDLER, NOT PER APPLICATION. Every page renders inside\n * `[root, ...outer-to-inner matched layouts, page]` — that is the exact triple\n * (widened to a chain) `create-page-route-handler.ts` loads per request — so a\n * handler's CSS is the ordered, deduped union of what those specific source\n * files pull in, and nothing else. Collecting across the WHOLE application\n * (every page's manifest entry, every root import) is the bug this shape\n * exists to avoid: it ships page B's stylesheet on page A's response, and it\n * only gets worse as an application grows.\n *\n * The two modes learn the answer from different places, and neither can use\n * the other's:\n *\n * - PRODUCTION reads Vite's client manifest, matching each source file's own\n * id and walking its recorded `css` and imported chunks.\n * - DEV has no manifest — Vite serves modules on demand — so the URLs are\n * derived from each source file's own import statements.\n */\nimport { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { CLIENT_ASSET_URL_PREFIX } from \"./client-asset-url-prefix\";\n\n/** Stylesheet extensions Vite can serve directly. Mirrors the build's list. */\nconst STYLE_EXTENSIONS = [\".css\", \".scss\", \".sass\", \".less\", \".styl\"];\n\n/**\n * A stylesheet Vite serves in DEV must be requested with `?direct`.\n *\n * Without it Vite answers the same URL with `text/javascript` — its CSS-as-JS\n * module transform, meant for `import \"./app.css\"` — and a\n * `<link rel=\"stylesheet\">` pointing at a JavaScript response applies\n * NOTHING, silently. No console error, no network failure, just an unstyled\n * page. `?direct` is what makes Vite reply with real `text/css`.\n */\nexport const VITE_DIRECT_CSS_QUERY = \"?direct\";\n\n/**\n * ONE source file's own directly imported stylesheets, as dev URLs.\n *\n * Dev has no manifest, so the source is the file itself: whatever it imports\n * with a stylesheet extension is what it needs. This is deliberately narrow —\n * it answers \"what CSS does THIS file set up\", not \"what CSS does the whole\n * module graph this file eventually reaches end up pulling in\" — because the\n * latter would require reproducing Vite's module graph, which is precisely\n * what dev has no manifest to shortcut.\n *\n * The narrowness is the honest part: production splits CSS per chunk and can\n * follow imported chunks (`productionStylesheetUrls` below); dev can only read\n * the ONE file handed to it. A page whose own module imports its own\n * stylesheet still gets it in dev — Vite's client graph injects it as before —\n * it simply is not render-blocking the way a chain member's own import is.\n *\n * Called once per chain member — root, then every matched layout outer to\n * inner, then the page — by the installers below, which is what turns \"one\n * file's own imports\" into a handler's whole CSS chain.\n *\n * Specifiers are resolved against `sourceFile` and expressed relative to\n * `appRoot`, because that is the shape Vite's dev server serves from.\n */\nexport function devStylesheetUrls(appRoot: string, sourceFile: string): string[] {\n let source: string;\n\n try {\n source = readFileSync(sourceFile, \"utf-8\");\n } catch {\n return [];\n }\n\n const urls: string[] = [];\n const pattern = /\\bimport\\s*(?:\\(\\s*)?[\"']([^\"']+)[\"']/g;\n\n let match = pattern.exec(source);\n\n while (match !== null) {\n const specifier = match[1];\n const lowered = specifier.toLowerCase();\n\n if (STYLE_EXTENSIONS.some((extension) => lowered.endsWith(extension))) {\n const absolute = path.resolve(path.dirname(sourceFile), specifier);\n const relative = path.relative(appRoot, absolute).split(path.sep).join(\"/\");\n\n // Outside the app root Vite would need an `/@fs/` URL and a widened\n // `fs.allow`; a stylesheet living there is unusual enough that guessing\n // is worse than leaving it to the client import.\n if (!relative.startsWith(\"..\")) {\n const url = `/${relative}${VITE_DIRECT_CSS_QUERY}`;\n\n if (!urls.includes(url)) urls.push(url);\n }\n }\n\n match = pattern.exec(source);\n }\n\n return urls;\n}\n\n/**\n * ONE handler's whole dev CSS chain: every `sourceFiles` member's own direct\n * stylesheet imports (`devStylesheetUrls`), in the order given — the caller\n * passes `[root, ...outer-to-inner matched layouts, page]` — concatenated and\n * deduped across the WHOLE chain, not just within one file.\n *\n * Cross-file dedup matters as much as within-file dedup: an application-wide\n * `app.css` imported by both the root and a page must still produce one\n * `<link>`, not two.\n */\nexport function devHandlerStylesheetUrls(\n appRoot: string,\n sourceFiles: readonly string[],\n): string[] {\n const urls: string[] = [];\n\n for (const sourceFile of sourceFiles) {\n for (const url of devStylesheetUrls(appRoot, sourceFile)) {\n if (!urls.includes(url)) urls.push(url);\n }\n }\n\n return urls;\n}\n\ntype ManifestEntry = {\n css?: unknown;\n imports?: unknown;\n};\n\n/**\n * Find the manifest key for an app-root-relative POSIX source id.\n *\n * VITE KEYS BY SOURCE PATH RELATIVE TO ITS OWN `root`, not to the app's\n * `appRoot` — the client build's `root` is the framework's own package\n * (`build-client.ts`), so a key for an app source file carries a `../`-laden\n * prefix (`\"../my-app/src/web/root.tsx\"`) rather than matching `sourceFile`\n * (`\"src/web/root.tsx\"`) byte for byte. The two forms always share the same\n * TAIL, though — both are anchored at the same file — so an exact match is\n * tried first (the case where the client build's root IS the app root, which\n * every fixture and every test below uses) and a `/`-boundary suffix match\n * second, rather than trying to reconstruct the build's own root here, which\n * this runtime read has no way to independently confirm.\n */\nfunction findManifestKey(\n manifest: Record<string, ManifestEntry | undefined>,\n sourceFile: string,\n): string | undefined {\n if (manifest[sourceFile] !== undefined) return sourceFile;\n\n const suffix = `/${sourceFile}`;\n\n for (const key of Object.keys(manifest)) {\n if (key.endsWith(suffix)) return key;\n }\n\n return undefined;\n}\n\n/**\n * Every stylesheet reachable from ONE manifest entry: its own recorded `css`,\n * plus the same walk repeated over every chunk it STATICALLY `imports`.\n *\n * `imports` only, never `dynamicImports`. Vite's manifest records\n * `dynamicImports` on shared entry points (the hydration entry names every\n * page as one) precisely because the browser must NOT download them eagerly —\n * walking that array here would pull every other page's CSS onto this one,\n * which is the exact \"unrelated pages\" leak this module exists to end.\n * `imports`, by contrast, are chunks THIS module synchronously depends on:\n * code Vite split out of it but that loads whenever it does, so their CSS is\n * this handler's CSS too.\n *\n * `visited` guards against a chunk graph cycle; sharing one set across the\n * whole walk from a single entry is enough; a shared chunk revisited from a\n * SEPARATE top-level entry (root vs. a layout vs. the page) is deliberately\n * walked again — the final merge in `productionStylesheetUrls` dedupes by URL,\n * and a fresh `visited` set per entry is simpler to reason about than one\n * threaded across unrelated chains.\n */\nfunction collectManifestCss(\n manifest: Record<string, ManifestEntry | undefined>,\n key: string,\n visited: Set<string>,\n): string[] {\n if (visited.has(key)) return [];\n visited.add(key);\n\n const entry = manifest[key];\n if (entry === undefined) return [];\n\n const ownCss = Array.isArray(entry.css)\n ? entry.css.filter((file): file is string => typeof file === \"string\" && file !== \"\")\n : [];\n\n const imports = Array.isArray(entry.imports)\n ? entry.imports.filter((id): id is string => typeof id === \"string\")\n : [];\n\n return [\n ...ownCss,\n ...imports.flatMap((importedKey) => collectManifestCss(manifest, importedKey, visited)),\n ];\n}\n\n/**\n * ONE handler's whole production CSS chain.\n *\n * `sourceFiles` is `[root, ...outer-to-inner matched layouts, page]`, each an\n * app-root-relative POSIX source id — the SAME id\n * `install-page-routes-from-manifest.ts` already carries as `sourceFile` on\n * every manifest entry, because that identity is what lets this function match\n * EXPLICITLY rather than guess: every id is looked up on its own\n * (`findManifestKey`), its own chunk's CSS is collected\n * (`collectManifestCss`), and an id with no matching entry contributes\n * nothing — it is never treated as license to fall back to scanning the whole\n * manifest, which is what let an unrelated page's CSS leak onto this handler\n * before.\n *\n * Duplicates are collapsed and order is preserved across the WHOLE chain, in\n * the order `sourceFiles` was given — root's own CSS first, then each\n * layout's outer to inner, then the page's — so cascade order matches the\n * chain's own outer-to-inner rendering order.\n *\n * A missing or malformed manifest returns NOTHING rather than throwing. The\n * hydration resolver already fails loudly on exactly those conditions, from\n * exactly the same file, and it runs first — a second, worse error for the\n * same cause helps nobody.\n */\nexport function productionStylesheetUrls(\n clientDir: string,\n sourceFiles: readonly string[],\n): string[] {\n const manifestPath = path.join(clientDir, \".vite\", \"manifest.json\");\n\n let manifest: Record<string, ManifestEntry | undefined>;\n\n try {\n manifest = JSON.parse(readFileSync(manifestPath, \"utf-8\")) as Record<\n string,\n ManifestEntry | undefined\n >;\n } catch {\n return [];\n }\n\n if (typeof manifest !== \"object\" || manifest === null) return [];\n\n const files: string[] = [];\n\n for (const sourceFile of sourceFiles) {\n const key = findManifestKey(manifest, sourceFile);\n if (key === undefined) continue;\n\n files.push(...collectManifestCss(manifest, key, new Set()));\n }\n\n const urls: string[] = [];\n\n for (const file of files) {\n // Built EXACTLY as the hydration entry's URL is built — `/${file}`, then\n // checked against the prefix — rather than reassembled from a basename.\n // The manifest already records `assets/root-<hash>.css`, and rebuilding\n // that path here would be a second expression of a convention\n // `client-asset-url-prefix.ts` owns.\n const url = `/${file}`;\n\n // A stylesheet outside the directory the asset route mounts would 404.\n // Dropped rather than emitted, because a dead <link> in <head> is a\n // silent styling failure — the exact thing this module exists to end.\n if (!url.startsWith(`${CLIENT_ASSET_URL_PREFIX}/`)) continue;\n\n if (!urls.includes(url)) urls.push(url);\n }\n\n return urls;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAM,mBAAmB;CAAC;CAAQ;CAAS;CAAS;CAAS;AAAO;;;;;;;;;;AAWpE,MAAa,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;AAyBrC,SAAgB,kBAAkB,SAAiB,YAA8B;CAC/E,IAAI;CAEJ,IAAI;EACF,SAAS,aAAa,YAAY,OAAO;CAC3C,QAAQ;EACN,OAAO,CAAC;CACV;CAEA,MAAM,OAAiB,CAAC;CACxB,MAAM,UAAU;CAEhB,IAAI,QAAQ,QAAQ,KAAK,MAAM;CAE/B,OAAO,UAAU,MAAM;EACrB,MAAM,YAAY,MAAM;EACxB,MAAM,UAAU,UAAU,YAAY;EAEtC,IAAI,iBAAiB,MAAM,cAAc,QAAQ,SAAS,SAAS,CAAC,GAAG;G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S,gBAAgB,mBAAmB,UAAU,aAAa,OAAO,CAAC,CACxF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,yBACd,WACA,aACU;CACV,MAAM,eAAe,KAAK,KAAK,WAAW,SAAS,eAAe;CAElE,IAAI;CAEJ,IAAI;EACF,WAAW,KAAK,MAAM,aAAa,cAAc,OAAO,CAAC;CAI3D,QAAQ;EACN,OAAO,CAAC;CACV;CAEA,IAAI,OAAO,aAAa,YAAY,aAAa,MAAM,OAAO,CAAC;CAE/D,MAAM,QAAkB,CAAC;CAEzB,KAAK,MAAM,cAAc,aAAa;EACpC,MAAM,MAAM,gBAAgB,UAAU,UAAU;EAChD,IAAI,QAAQ,QAAW;EAEvB,MAAM,KAAK,GAAG,mBAAmB,UAAU,qBAAK,IAAI,IAAI,CAAC,CAAC;CAC5D;CAEA,MAAM,OAAiB,CAAC;CAExB,KAAK,MAAM,QAAQ,OAAO;EAMxB,MAAM,MAAM,IAAI;EAKhB,IAAI,CAAC,IAAI,WAAW,aAA2B,EAAE,GAAG;EAEpD,IAAI,CAAC,KAAK,SAAS,GAAG,GAAG,KAAK,KAAK,GAAG;CACxC;CAEA,OAAO;AACT"}
@@ -3,7 +3,7 @@ import { isNotFoundPageFile } from "./not-found-page.mjs";
3
3
  import { discoverPages, isDiscoveredRoutablePage, toPosix } from "../build/discover-pages.mjs";
4
4
  import path from "node:path";
5
5
 
6
- //#region web/src/server/unregistered-pages.ts
6
+ //#region ../web/src/server/unregistered-pages.ts
7
7
  function fileKey(file) {
8
8
  const posix = toPosix(file);
9
9
  return process.platform === "win32" ? posix.toLowerCase() : posix;
@@ -1 +1 @@
1
- {"version":3,"file":"unregistered-pages.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/unregistered-pages.ts"],"sourcesContent":["import path from \"node:path\";\nimport {\n discoverPages,\n isDiscoveredRoutablePage,\n toPosix,\n type DiscoverPagesOptions,\n type DiscoveredPage,\n} from \"../build/discover-pages\";\nimport { matchPath } from \"./match-page-route\";\nimport { isNotFoundPageFile } from \"./not-found-page\";\n\ntype DiscoveredGlobalPage = Extract<DiscoveredPage, { type: \"page\" }>;\ntype DiscoverPages = (options: DiscoverPagesOptions) => readonly DiscoveredPage[];\n\nexport type UnregisteredPagesOptions = {\n appRoot: string;\n appSrcRoot: string;\n registeredPageFiles: () => readonly string[];\n discover?: DiscoverPages;\n warn?: (message: string) => void;\n};\n\nfunction fileKey(file: string): string {\n const posix = toPosix(file);\n\n return process.platform === \"win32\" ? posix.toLowerCase() : posix;\n}\n\nfunction findUnregisteredPages(options: UnregisteredPagesOptions): DiscoveredGlobalPage[] {\n const { appRoot, appSrcRoot, registeredPageFiles, discover = discoverPages } = options;\n const registered = new Set(registeredPageFiles().map(fileKey));\n const webRoot = path.resolve(appSrcRoot, \"web\");\n\n return discover({ appRoot, srcDir: path.relative(appRoot, appSrcRoot) })\n .filter(isDiscoveredRoutablePage)\n .filter(\n (page) =>\n path.resolve(page.webRoot) === webRoot &&\n !isNotFoundPageFile(page.pageFile) &&\n !registered.has(fileKey(page.pageFile)),\n );\n}\n\nexport function findUnregisteredPageFiles(options: UnregisteredPagesOptions): string[] {\n return findUnregisteredPages(options).map((page) => page.pageFile);\n}\n\nexport function describeUnregisteredPages(\n pageFiles: readonly string[],\n appRoot: string,\n request: { method: string; url: string },\n): string {\n const named = pageFiles\n .map((pageFile) => ` - ${toPosix(path.relative(appRoot, pageFile))}`)\n .join(\"\\n\");\n\n return (\n `[warlock:web] ${request.method} ${request.url} answered 404. ` +\n \"These src/web page files exist on disk but are absent from the active route table:\\n\" +\n named\n );\n}\n\nexport function createUnregisteredPageReporter(\n options: UnregisteredPagesOptions,\n): (request: { method: string; url: string; pathname: string }) => void {\n const { appRoot, warn = console.warn } = options;\n const reported = new Set<string>();\n\n return (request) => {\n // `discoverPages()` deliberately refuses malformed pages. Its install/build\n // diagnostic is authoritative, so a response hook must leave this 404 alone.\n try {\n const unregistered = findUnregisteredPages(options).find(\n (page) =>\n !reported.has(fileKey(page.pageFile)) &&\n matchPath(page.routePath, request.pathname) !== undefined,\n );\n\n if (unregistered === undefined) return;\n\n reported.add(fileKey(unregistered.pageFile));\n warn(describeUnregisteredPages([unregistered.pageFile], appRoot, request));\n } catch {\n return;\n }\n };\n}\n"],"mappings":";;;;;;AAsBA,SAAS,QAAQ,MAAsB;CACrC,MAAM,QAAQ,QAAQ,IAAI;CAE1B,OAAO,QAAQ,aAAa,UAAU,MAAM,YAAY,IAAI;AAC9D;AAEA,SAAS,sBAAsB,SAA2D;CACxF,MAAM,EAAE,SAAS,YAAY,qBAAqB,WAAW,kBAAkB;CAC/E,MAAM,aAAa,IAAI,IAAI,oBAAoB,EAAE,IAAI,OAAO,CAAC;CAC7D,MAAM,UAAU,KAAK,QAAQ,YAAY,KAAK;CAE9C,OAAO,SAAS;EAAE;EAAS,QAAQ,KAAK,SAAS,SAAS,UAAU;CAAE,CAAC,EACpE,OAAO,wBAAwB,EAC/B,QACE,SACD,KAAK,QAAQ,KAAK,OAAO,MAAM,WAC/B,CAAC,mBAAmB,KAAK,QAAQ,KACjC,CAAC,WAAW,IAAI,QAAQ,KAAK,QAAQ,CAAC,CACxC;AACJ;AAMA,SAAgB,0BACd,WACA,SACA,SACQ;CACR,MAAM,QAAQ,UACX,KAAK,aAAa,OAAO,QAAQ,KAAK,SAAS,SAAS,QAAQ,CAAC,GAAG,EACpE,KAAK,IAAI;CAEZ,OACE,iBAAiB,QAAQ,OAAO,GAAG,QAAQ,IAAI;IAE/C;AAEJ;AAEA,SAAgB,+BACd,SACsE;CACtE,MAAM,EAAE,SAAS,OAAO,QAAQ,SAAS;CACzC,MAAM,2BAAW,IAAI,IAAY;CAEjC,QAAQ,YAAY;EAGlB,IAAI;GACF,MAAM,eAAe,sBAAsB,OAAO,EAAE,MACjD,SACC,CAAC,SAAS,IAAI,QAAQ,KAAK,QAAQ,CAAC,KACpC,UAAU,KAAK,WAAW,QAAQ,QAAQ,MAAM,MACpD;GAEA,IAAI,iBAAiB,QAAW;GAEhC,SAAS,IAAI,QAAQ,aAAa,QAAQ,CAAC;GAC3C,KAAK,0BAA0B,CAAC,aAAa,QAAQ,GAAG,SAAS,OAAO,CAAC;EAC3E,QAAQ;GACN;EACF;CACF;AACF"}
1
+ {"version":3,"file":"unregistered-pages.mjs","names":[],"sources":["../../../../../../../web/src/server/unregistered-pages.ts"],"sourcesContent":["import path from \"node:path\";\nimport {\n discoverPages,\n isDiscoveredRoutablePage,\n toPosix,\n type DiscoverPagesOptions,\n type DiscoveredPage,\n} from \"../build/discover-pages\";\nimport { matchPath } from \"./match-page-route\";\nimport { isNotFoundPageFile } from \"./not-found-page\";\n\ntype DiscoveredGlobalPage = Extract<DiscoveredPage, { type: \"page\" }>;\ntype DiscoverPages = (options: DiscoverPagesOptions) => readonly DiscoveredPage[];\n\nexport type UnregisteredPagesOptions = {\n appRoot: string;\n appSrcRoot: string;\n registeredPageFiles: () => readonly string[];\n discover?: DiscoverPages;\n warn?: (message: string) => void;\n};\n\nfunction fileKey(file: string): string {\n const posix = toPosix(file);\n\n return process.platform === \"win32\" ? posix.toLowerCase() : posix;\n}\n\nfunction findUnregisteredPages(options: UnregisteredPagesOptions): DiscoveredGlobalPage[] {\n const { appRoot, appSrcRoot, registeredPageFiles, discover = discoverPages } = options;\n const registered = new Set(registeredPageFiles().map(fileKey));\n const webRoot = path.resolve(appSrcRoot, \"web\");\n\n return discover({ appRoot, srcDir: path.relative(appRoot, appSrcRoot) })\n .filter(isDiscoveredRoutablePage)\n .filter(\n (page) =>\n path.resolve(page.webRoot) === webRoot &&\n !isNotFoundPageFile(page.pageFile) &&\n !registered.has(fileKey(page.pageFile)),\n );\n}\n\nexport function findUnregisteredPageFiles(options: UnregisteredPagesOptions): string[] {\n return findUnregisteredPages(options).map((page) => page.pageFile);\n}\n\nexport function describeUnregisteredPages(\n pageFiles: readonly string[],\n appRoot: string,\n request: { method: string; url: string },\n): string {\n const named = pageFiles\n .map((pageFile) => ` - ${toPosix(path.relative(appRoot, pageFile))}`)\n .join(\"\\n\");\n\n return (\n `[warlock:web] ${request.method} ${request.url} answered 404. ` +\n \"These src/web page files exist on disk but are absent from the active route table:\\n\" +\n named\n );\n}\n\nexport function createUnregisteredPageReporter(\n options: UnregisteredPagesOptions,\n): (request: { method: string; url: string; pathname: string }) => void {\n const { appRoot, warn = console.warn } = options;\n const reported = new Set<string>();\n\n return (request) => {\n // `discoverPages()` deliberately refuses malformed pages. Its install/build\n // diagnostic is authoritative, so a response hook must leave this 404 alone.\n try {\n const unregistered = findUnregisteredPages(options).find(\n (page) =>\n !reported.has(fileKey(page.pageFile)) &&\n matchPath(page.routePath, request.pathname) !== undefined,\n );\n\n if (unregistered === undefined) return;\n\n reported.add(fileKey(unregistered.pageFile));\n warn(describeUnregisteredPages([unregistered.pageFile], appRoot, request));\n } catch {\n return;\n }\n };\n}\n"],"mappings":";;;;;;AAsBA,SAAS,QAAQ,MAAsB;CACrC,MAAM,QAAQ,QAAQ,IAAI;CAE1B,OAAO,QAAQ,aAAa,UAAU,MAAM,YAAY,IAAI;AAC9D;AAEA,SAAS,sBAAsB,SAA2D;CACxF,MAAM,EAAE,SAAS,YAAY,qBAAqB,WAAW,kBAAkB;CAC/E,MAAM,aAAa,IAAI,IAAI,oBAAoB,EAAE,IAAI,OAAO,CAAC;CAC7D,MAAM,UAAU,KAAK,QAAQ,YAAY,KAAK;CAE9C,OAAO,SAAS;EAAE;EAAS,QAAQ,KAAK,SAAS,SAAS,UAAU;CAAE,CAAC,EACpE,OAAO,wBAAwB,EAC/B,QACE,SACD,KAAK,QAAQ,KAAK,OAAO,MAAM,WAC/B,CAAC,mBAAmB,KAAK,QAAQ,KACjC,CAAC,WAAW,IAAI,QAAQ,KAAK,QAAQ,CAAC,CACxC;AACJ;AAMA,SAAgB,0BACd,WACA,SACA,SACQ;CACR,MAAM,QAAQ,UACX,KAAK,aAAa,OAAO,QAAQ,KAAK,SAAS,SAAS,QAAQ,CAAC,GAAG,EACpE,KAAK,IAAI;CAEZ,OACE,iBAAiB,QAAQ,OAAO,GAAG,QAAQ,IAAI;IAE/C;AAEJ;AAEA,SAAgB,+BACd,SACsE;CACtE,MAAM,EAAE,SAAS,OAAO,QAAQ,SAAS;CACzC,MAAM,2BAAW,IAAI,IAAY;CAEjC,QAAQ,YAAY;EAGlB,IAAI;GACF,MAAM,eAAe,sBAAsB,OAAO,EAAE,MACjD,SACC,CAAC,SAAS,IAAI,QAAQ,KAAK,QAAQ,CAAC,KACpC,UAAU,KAAK,WAAW,QAAQ,QAAQ,MAAM,MACpD;GAEA,IAAI,iBAAiB,QAAW;GAEhC,SAAS,IAAI,QAAQ,aAAa,QAAQ,CAAC;GAC3C,KAAK,0BAA0B,CAAC,aAAa,QAAQ,GAAG,SAAS,OAAO,CAAC;EAC3E,QAAQ;GACN;EACF;CACF;AACF"}
@@ -2,7 +2,7 @@ import { WebBuildOptions } from "../build/contribution.mjs";
2
2
  import { WebConnectorOptions } from "./web-connector.mjs";
3
3
  import { Connector } from "@warlock.js/core";
4
4
 
5
- //#region web/src/server/web-connector-factory.d.ts
5
+ //#region ../web/src/server/web-connector-factory.d.ts
6
6
  type WebConnectorFactoryOptions = WebConnectorOptions & {
7
7
  /**
8
8
  * What web contributes to `warlock build`. Passed straight to
@@ -3,7 +3,7 @@ import { ConnectorLifecyclePhase } from "@warlock.js/core";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
 
6
- //#region web/src/server/web-connector-factory.ts
6
+ //#region ../web/src/server/web-connector-factory.ts
7
7
  /**
8
8
  * `webConnector()` — the ONE thing `warlock.config.ts` imports from
9
9
  * `@warlock.js/web/connector`, and the only value the `./connector` barrel
@@ -1 +1 @@
1
- {"version":3,"file":"web-connector-factory.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/web-connector-factory.ts"],"sourcesContent":["/**\n * `webConnector()` — the ONE thing `warlock.config.ts` imports from\n * `@warlock.js/web/connector`, and the only value the `./connector` barrel\n * adds beyond the build/runtime seams.\n *\n * WHY THIS MODULE EXISTS AT ALL, rather than the barrel exporting\n * `WebConnector` directly: `./web-connector.ts` imports `../vite`\n * (`web-connector.ts:52` → `@babel/parser` + `magic-string`),\n * `../../../core/src/router/router` (`:51`) and `./dev-server` (`:53`, which\n * itself pulls core's http stack and `../vite`) at VALUE level. Re-exporting\n * that class from `web/src/connector/index.ts` would drag every one of those\n * into the static graph of every consuming app's config file — the exact\n * config-load weight the `./connector` subpath was created to prevent.\n *\n * So the factory returns a LAZY DELEGATE: a `Connector` whose identity fields\n * (`name`, `priority`, `lifecyclePhase`, `build`) are plain data available\n * synchronously, and whose lifecycle methods `await import(\"./web-connector\")`\n * on first use. `warlock build` reads `build` off this object and never boots\n * anything, so a build never loads Vite or React through\n * here either. This is the third instance of a pattern the codebase already\n * uses twice — `core/src/connectors/access-connector.ts:39` and\n * `web/src/server/dev-cli.ts:61` — not a new one.\n *\n * KEEP THIS MODULE LIGHT. Its whole value-level static graph is `node:path`,\n * `node:url`, `../../../core/src/connectors/types` (whose own two imports are\n * both `import type` and therefore erased — `core/src/connectors/types.ts:1-2`)\n * and `../build/contribution` (`node:fs` + `node:path` + type-only core).\n * Everything else here is `import type`, which `verbatimModuleSyntax` erases.\n */\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n type Connector,\n type ConnectorBuildContribution,\n ConnectorLifecyclePhase,\n type ConnectorName,\n} from \"@warlock.js/core\";\nimport {\n createWebBuildContribution,\n type WebBuildOptions,\n} from \"../build/contribution\";\nimport type { WebConnector, WebConnectorOptions } from \"./web-connector\";\n\n/**\n * Boot/shutdown position relative to core's own connectors.\n *\n * `ConnectorPriority.HTTP` is `5` and `ConnectorPriority.STORAGE` is `6`\n * (`core/src/connectors/types.ts:187-188`), and the manager sorts on a plain\n * numeric compare (`core/src/connectors/connectors-manager.ts:46`) — so `5.5`\n * is \"immediately after http, before everything else\".\n *\n * Defined HERE and re-exported by `./web-connector` rather than the other way\n * round: the delegate must publish `priority` synchronously, and reading it\n * from the heavy module would defeat the whole point of the delegate.\n */\nexport const WEB_CONNECTOR_PRIORITY = 5.5;\n\nexport type WebConnectorFactoryOptions = WebConnectorOptions & {\n /**\n * What web contributes to `warlock build`. Passed straight to\n * {@link createWebBuildContribution}; JSON-serializable values only.\n */\n build?: WebBuildOptions;\n};\n\n/**\n * The `@warlock.js/web` package root, derived once from THIS module's location\n * and then passed EXPLICITLY to both halves.\n *\n * `web/src/server/web-connector-factory.ts` → `web/src/server` → `web/src` →\n * `web`; published as `web/esm/server/web-connector-factory.js`, two levels up\n * is the package root under both layouts — the same arithmetic\n * `contribution.ts:136-140` documents.\n *\n * Deriving it here and handing it down means the build contribution never falls\n * back to its own `import.meta.url` guess (`contribution.ts:129-141`): one\n * derivation, one place to be wrong, and `assertWebPackageRoot` verifies it\n * against `<root>/package.json`'s `name` either way.\n */\nfunction deriveWebRoot(): string {\n return path.resolve(path.dirname(fileURLToPath(import.meta.url)), \"..\", \"..\");\n}\n\n/**\n * Construct web's connector for `warlock.config.ts > connectors`.\n *\n * @example\n * ```ts\n * export default defineConfig({ connectors: [webConnector()] });\n * ```\n */\nexport function webConnector(\n options: WebConnectorFactoryOptions = {},\n): Connector {\n const { build: buildOptions, ...connectorOptions } = options;\n const webRoot = connectorOptions.webRoot ?? deriveWebRoot();\n // One snapshot feeds both halves. Mutating the caller's array after config\n // construction cannot make dev and `warlock build` observe different lists.\n const connectorPlugins = [...(connectorOptions.plugins ?? [])];\n\n const build: ConnectorBuildContribution = createWebBuildContribution(\n {\n ...buildOptions,\n webRoot: buildOptions?.webRoot ?? webRoot,\n },\n connectorPlugins,\n );\n\n let instance: WebConnector | undefined;\n\n /**\n * Load the heavy half on first lifecycle call. `boot()` is always the first\n * of these to run (`core/src/connectors/connectors-manager.ts:87-93`), so the\n * import lands in a process that has already committed to serving pages.\n */\n const load = async (): Promise<WebConnector> => {\n if (!instance) {\n const { WebConnector: WebConnectorClass } =\n await import(\"./web-connector\");\n\n instance = new WebConnectorClass({\n ...connectorOptions,\n plugins: connectorPlugins,\n webRoot,\n });\n }\n\n return instance;\n };\n\n return {\n name: \"web\" satisfies ConnectorName,\n priority: WEB_CONNECTOR_PRIORITY,\n lifecyclePhase: ConnectorLifecyclePhase.Late,\n build,\n\n // Never loads the heavy half: a connector that was never booted is not\n // active, and answering that must not cost a Vite import.\n isActive: () => instance?.isActive() ?? false,\n\n boot: async () => {\n await (await load()).boot();\n },\n start: async () => {\n await (await load()).start();\n },\n restart: async () => {\n await (await load()).restart();\n },\n\n // Both of these are asked of every registered connector, including ones\n // that never booted — so neither may force the import.\n shutdown: async () => {\n await instance?.shutdown();\n },\n\n // Asked on EVERY watcher batch, so the `instance?.` is load-bearing twice:\n // it keeps the answer free for a connector that never booted, and it is the\n // only reason this delegate can forward the question at all — by the time a\n // watcher batch exists, `boot()` has already loaded the heavy half, so\n // reading the real answer off it costs nothing beyond the call.\n //\n // It used to be a hard `false`, which meant a `*.page.tsx` created while\n // `warlock dev` was running was never noticed: page routes are installed\n // once, in `WebConnector.boot()`, so the new page's URL 404'd in silence.\n // The connector itself now decides: add/remove and route-identity edits are\n // live route-table work; component-body-only edits remain Vite HMR work.\n shouldRestart: (changedFiles: string[]) =>\n instance?.shouldRestart(changedFiles) ?? false,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAa,yBAAyB;;;;;;;;;;;;;;;AAwBtC,SAAS,gBAAwB;CAC/B,OAAO,KAAK,QAAQ,KAAK,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC,GAAG,MAAM,IAAI;AAC9E;;;;;;;;;AAUA,SAAgB,aACd,UAAsC,CAAC,GAC5B;CACX,MAAM,EAAE,OAAO,cAAc,GAAG,qBAAqB;CACrD,MAAM,UAAU,iBAAiB,WAAW,cAAc;CAG1D,MAAM,mBAAmB,CAAC,GAAI,iBAAiB,WAAW,CAAC,CAAE;CAE7D,MAAM,QAAoC,2BACxC;EACE,GAAG;EACH,SAAS,cAAc,WAAW;CACpC,GACA,gBACF;CAEA,IAAI;;;;;;CAOJ,MAAM,OAAO,YAAmC;EAC9C,IAAI,CAAC,UAAU;GACb,MAAM,EAAE,cAAc,sBACpB,MAAM,OAAO;GAEf,WAAW,IAAI,kBAAkB;IAC/B,GAAG;IACH,SAAS;IACT;GACF,CAAC;EACH;EAEA,OAAO;CACT;CAEA,OAAO;EACL,MAAM;EACN,UAAU;EACV,gBAAgB,wBAAwB;EACxC;EAIA,gBAAgB,UAAU,SAAS,KAAK;EAExC,MAAM,YAAY;GAChB,OAAO,MAAM,KAAK,GAAG,KAAK;EAC5B;EACA,OAAO,YAAY;GACjB,OAAO,MAAM,KAAK,GAAG,MAAM;EAC7B;EACA,SAAS,YAAY;GACnB,OAAO,MAAM,KAAK,GAAG,QAAQ;EAC/B;EAIA,UAAU,YAAY;GACpB,MAAM,UAAU,SAAS;EAC3B;EAaA,gBAAgB,iBACd,UAAU,cAAc,YAAY,KAAK;CAC7C;AACF"}
1
+ {"version":3,"file":"web-connector-factory.mjs","names":[],"sources":["../../../../../../../web/src/server/web-connector-factory.ts"],"sourcesContent":["/**\n * `webConnector()` — the ONE thing `warlock.config.ts` imports from\n * `@warlock.js/web/connector`, and the only value the `./connector` barrel\n * adds beyond the build/runtime seams.\n *\n * WHY THIS MODULE EXISTS AT ALL, rather than the barrel exporting\n * `WebConnector` directly: `./web-connector.ts` imports `../vite`\n * (`web-connector.ts:52` → `@babel/parser` + `magic-string`),\n * `../../../core/src/router/router` (`:51`) and `./dev-server` (`:53`, which\n * itself pulls core's http stack and `../vite`) at VALUE level. Re-exporting\n * that class from `web/src/connector/index.ts` would drag every one of those\n * into the static graph of every consuming app's config file — the exact\n * config-load weight the `./connector` subpath was created to prevent.\n *\n * So the factory returns a LAZY DELEGATE: a `Connector` whose identity fields\n * (`name`, `priority`, `lifecyclePhase`, `build`) are plain data available\n * synchronously, and whose lifecycle methods `await import(\"./web-connector\")`\n * on first use. `warlock build` reads `build` off this object and never boots\n * anything, so a build never loads Vite or React through\n * here either. This is the third instance of a pattern the codebase already\n * uses twice — `core/src/connectors/access-connector.ts:39` and\n * `web/src/server/dev-cli.ts:61` — not a new one.\n *\n * KEEP THIS MODULE LIGHT. Its whole value-level static graph is `node:path`,\n * `node:url`, `../../../core/src/connectors/types` (whose own two imports are\n * both `import type` and therefore erased — `core/src/connectors/types.ts:1-2`)\n * and `../build/contribution` (`node:fs` + `node:path` + type-only core).\n * Everything else here is `import type`, which `verbatimModuleSyntax` erases.\n */\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n type Connector,\n type ConnectorBuildContribution,\n ConnectorLifecyclePhase,\n type ConnectorName,\n} from \"@warlock.js/core\";\nimport {\n createWebBuildContribution,\n type WebBuildOptions,\n} from \"../build/contribution\";\nimport type { WebConnector, WebConnectorOptions } from \"./web-connector\";\n\n/**\n * Boot/shutdown position relative to core's own connectors.\n *\n * `ConnectorPriority.HTTP` is `5` and `ConnectorPriority.STORAGE` is `6`\n * (`core/src/connectors/types.ts:187-188`), and the manager sorts on a plain\n * numeric compare (`core/src/connectors/connectors-manager.ts:46`) — so `5.5`\n * is \"immediately after http, before everything else\".\n *\n * Defined HERE and re-exported by `./web-connector` rather than the other way\n * round: the delegate must publish `priority` synchronously, and reading it\n * from the heavy module would defeat the whole point of the delegate.\n */\nexport const WEB_CONNECTOR_PRIORITY = 5.5;\n\nexport type WebConnectorFactoryOptions = WebConnectorOptions & {\n /**\n * What web contributes to `warlock build`. Passed straight to\n * {@link createWebBuildContribution}; JSON-serializable values only.\n */\n build?: WebBuildOptions;\n};\n\n/**\n * The `@warlock.js/web` package root, derived once from THIS module's location\n * and then passed EXPLICITLY to both halves.\n *\n * `web/src/server/web-connector-factory.ts` → `web/src/server` → `web/src` →\n * `web`; published as `web/esm/server/web-connector-factory.js`, two levels up\n * is the package root under both layouts — the same arithmetic\n * `contribution.ts:136-140` documents.\n *\n * Deriving it here and handing it down means the build contribution never falls\n * back to its own `import.meta.url` guess (`contribution.ts:129-141`): one\n * derivation, one place to be wrong, and `assertWebPackageRoot` verifies it\n * against `<root>/package.json`'s `name` either way.\n */\nfunction deriveWebRoot(): string {\n return path.resolve(path.dirname(fileURLToPath(import.meta.url)), \"..\", \"..\");\n}\n\n/**\n * Construct web's connector for `warlock.config.ts > connectors`.\n *\n * @example\n * ```ts\n * export default defineConfig({ connectors: [webConnector()] });\n * ```\n */\nexport function webConnector(\n options: WebConnectorFactoryOptions = {},\n): Connector {\n const { build: buildOptions, ...connectorOptions } = options;\n const webRoot = connectorOptions.webRoot ?? deriveWebRoot();\n // One snapshot feeds both halves. Mutating the caller's array after config\n // construction cannot make dev and `warlock build` observe different lists.\n const connectorPlugins = [...(connectorOptions.plugins ?? [])];\n\n const build: ConnectorBuildContribution = createWebBuildContribution(\n {\n ...buildOptions,\n webRoot: buildOptions?.webRoot ?? webRoot,\n },\n connectorPlugins,\n );\n\n let instance: WebConnector | undefined;\n\n /**\n * Load the heavy half on first lifecycle call. `boot()` is always the first\n * of these to run (`core/src/connectors/connectors-manager.ts:87-93`), so the\n * import lands in a process that has already committed to serving pages.\n */\n const load = async (): Promise<WebConnector> => {\n if (!instance) {\n const { WebConnector: WebConnectorClass } =\n await import(\"./web-connector\");\n\n instance = new WebConnectorClass({\n ...connectorOptions,\n plugins: connectorPlugins,\n webRoot,\n });\n }\n\n return instance;\n };\n\n return {\n name: \"web\" satisfies ConnectorName,\n priority: WEB_CONNECTOR_PRIORITY,\n lifecyclePhase: ConnectorLifecyclePhase.Late,\n build,\n\n // Never loads the heavy half: a connector that was never booted is not\n // active, and answering that must not cost a Vite import.\n isActive: () => instance?.isActive() ?? false,\n\n boot: async () => {\n await (await load()).boot();\n },\n start: async () => {\n await (await load()).start();\n },\n restart: async () => {\n await (await load()).restart();\n },\n\n // Both of these are asked of every registered connector, including ones\n // that never booted — so neither may force the import.\n shutdown: async () => {\n await instance?.shutdown();\n },\n\n // Asked on EVERY watcher batch, so the `instance?.` is load-bearing twice:\n // it keeps the answer free for a connector that never booted, and it is the\n // only reason this delegate can forward the question at all — by the time a\n // watcher batch exists, `boot()` has already loaded the heavy half, so\n // reading the real answer off it costs nothing beyond the call.\n //\n // It used to be a hard `false`, which meant a `*.page.tsx` created while\n // `warlock dev` was running was never noticed: page routes are installed\n // once, in `WebConnector.boot()`, so the new page's URL 404'd in silence.\n // The connector itself now decides: add/remove and route-identity edits are\n // live route-table work; component-body-only edits remain Vite HMR work.\n shouldRestart: (changedFiles: string[]) =>\n instance?.shouldRestart(changedFiles) ?? false,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAa,yBAAyB;;;;;;;;;;;;;;;AAwBtC,SAAS,gBAAwB;CAC/B,OAAO,KAAK,QAAQ,KAAK,QAAQ,cAAc,OAAO,KAAK,GAAG,CAAC,GAAG,MAAM,IAAI;AAC9E;;;;;;;;;AAUA,SAAgB,aACd,UAAsC,CAAC,GAC5B;CACX,MAAM,EAAE,OAAO,cAAc,GAAG,qBAAqB;CACrD,MAAM,UAAU,iBAAiB,WAAW,cAAc;CAG1D,MAAM,mBAAmB,CAAC,GAAI,iBAAiB,WAAW,CAAC,CAAE;CAE7D,MAAM,QAAoC,2BACxC;EACE,GAAG;EACH,SAAS,cAAc,WAAW;CACpC,GACA,gBACF;CAEA,IAAI;;;;;;CAOJ,MAAM,OAAO,YAAmC;EAC9C,IAAI,CAAC,UAAU;GACb,MAAM,EAAE,cAAc,sBACpB,MAAM,OAAO;GAEf,WAAW,IAAI,kBAAkB;IAC/B,GAAG;IACH,SAAS;IACT;GACF,CAAC;EACH;EAEA,OAAO;CACT;CAEA,OAAO;EACL,MAAM;EACN,UAAU;EACV,gBAAgB,wBAAwB;EACxC;EAIA,gBAAgB,UAAU,SAAS,KAAK;EAExC,MAAM,YAAY;GAChB,OAAO,MAAM,KAAK,GAAG,KAAK;EAC5B;EACA,OAAO,YAAY;GACjB,OAAO,MAAM,KAAK,GAAG,MAAM;EAC7B;EACA,SAAS,YAAY;GACnB,OAAO,MAAM,KAAK,GAAG,QAAQ;EAC/B;EAIA,UAAU,YAAY;GACpB,MAAM,UAAU,SAAS;EAC3B;EAaA,gBAAgB,iBACd,UAAU,cAAc,YAAY,KAAK;CAC7C;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { BaseConnector, ConnectorLifecyclePhase } from "@warlock.js/core";
2
2
  import { Alias, PluginOption, ViteDevServer } from "vite";
3
3
 
4
- //#region web/src/server/web-connector.d.ts
4
+ //#region ../web/src/server/web-connector.d.ts
5
5
  type WebConnectorOptions = {
6
6
  /**
7
7
  * Vite's `root` — the application directory that owns `src/`, `package.json`
@@ -18,7 +18,7 @@ import fs from "node:fs";
18
18
  import path from "node:path";
19
19
  import { fileURLToPath } from "node:url";
20
20
 
21
- //#region web/src/server/web-connector.ts
21
+ //#region ../web/src/server/web-connector.ts
22
22
  /**
23
23
  * `WebConnector` — the SSR page surface as a first-class Warlock connector.
24
24
  *