@warlock.js/web 5.1.0 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/README.md +126 -12
  3. package/esm/build/contribution.d.mts +11 -14
  4. package/esm/build/contribution.mjs +46 -58
  5. package/esm/build/contribution.mjs.map +1 -1
  6. package/esm/build/discover-pages.mjs +105 -45
  7. package/esm/build/discover-pages.mjs.map +1 -1
  8. package/esm/build/generate-client-registry.mjs +47 -13
  9. package/esm/build/generate-client-registry.mjs.map +1 -1
  10. package/esm/build/generate-pages-barrel.mjs +55 -13
  11. package/esm/build/generate-pages-barrel.mjs.map +1 -1
  12. package/esm/build/page-default-export.mjs +48 -0
  13. package/esm/build/page-default-export.mjs.map +1 -0
  14. package/esm/build/page-routes-manifest.mjs +21 -0
  15. package/esm/build/page-routes-manifest.mjs.map +1 -0
  16. package/esm/build/public-files.mjs +45 -0
  17. package/esm/build/public-files.mjs.map +1 -0
  18. package/esm/build/read-route-exports.mjs +1 -1
  19. package/esm/build/read-route-exports.mjs.map +1 -1
  20. package/esm/client/build-hydrated-tree.mjs +40 -9
  21. package/esm/client/build-hydrated-tree.mjs.map +1 -1
  22. package/esm/client/hydrate-page.mjs +1 -1
  23. package/esm/client/hydrate-page.mjs.map +1 -1
  24. package/esm/client/navigation/current-route.d.mts +1 -1
  25. package/esm/client/navigation/current-route.mjs +1 -1
  26. package/esm/client/navigation/current-route.mjs.map +1 -1
  27. package/esm/client/navigation/fetch-page-data.mjs +1 -1
  28. package/esm/client/navigation/fetch-page-data.mjs.map +1 -1
  29. package/esm/client/navigation/navigation-root.mjs +1 -1
  30. package/esm/client/navigation/navigation-root.mjs.map +1 -1
  31. package/esm/client/navigation/prefetch.mjs +1 -1
  32. package/esm/client/navigation/prefetch.mjs.map +1 -1
  33. package/esm/client/navigation/refresh.d.mts +1 -1
  34. package/esm/client/navigation/refresh.mjs +1 -1
  35. package/esm/client/navigation/refresh.mjs.map +1 -1
  36. package/esm/client/navigation/scroll-to-fragment.mjs +1 -1
  37. package/esm/client/navigation/scroll-to-fragment.mjs.map +1 -1
  38. package/esm/client/navigation/verbs.d.mts +1 -1
  39. package/esm/client/navigation/verbs.mjs +1 -1
  40. package/esm/client/navigation/verbs.mjs.map +1 -1
  41. package/esm/client/runtime/index.d.mts +2 -1
  42. package/esm/client/runtime/index.mjs +2 -1
  43. package/esm/client/runtime/manifest.d.mts +1 -1
  44. package/esm/client/runtime/manifest.mjs +3 -2
  45. package/esm/client/runtime/manifest.mjs.map +1 -1
  46. package/esm/client/runtime/matcher.d.mts +13 -1
  47. package/esm/client/runtime/matcher.mjs +13 -1
  48. package/esm/client/runtime/matcher.mjs.map +1 -1
  49. package/esm/client/runtime/types.d.mts +15 -2
  50. package/esm/components/default-app.mjs +1 -1
  51. package/esm/components/default-app.mjs.map +1 -1
  52. package/esm/components/document-context.d.mts +40 -2
  53. package/esm/components/document-context.mjs +1 -1
  54. package/esm/components/document-context.mjs.map +1 -1
  55. package/esm/components/head.d.mts +1 -1
  56. package/esm/components/head.mjs +1 -1
  57. package/esm/components/head.mjs.map +1 -1
  58. package/esm/components/link.d.mts +1 -1
  59. package/esm/components/link.mjs +1 -1
  60. package/esm/components/link.mjs.map +1 -1
  61. package/esm/components/scripts.d.mts +1 -1
  62. package/esm/components/scripts.mjs +4 -2
  63. package/esm/components/scripts.mjs.map +1 -1
  64. package/esm/context.d.mts +6 -102
  65. package/esm/hydration/index.mjs +1 -1
  66. package/esm/hydration/index.mjs.map +1 -1
  67. package/esm/hydration-payload.d.mts +1 -1
  68. package/esm/hydration-payload.mjs +37 -8
  69. package/esm/hydration-payload.mjs.map +1 -1
  70. package/esm/index.d.mts +4 -3
  71. package/esm/loaders.d.mts +7 -36
  72. package/esm/metadata.d.mts +1 -1
  73. package/esm/metadata.mjs +1 -1
  74. package/esm/metadata.mjs.map +1 -1
  75. package/esm/props.d.mts +16 -8
  76. package/esm/route.d.mts +2 -17
  77. package/esm/routing/compose-route-path.d.mts +1 -1
  78. package/esm/routing/compose-route-path.mjs +1 -1
  79. package/esm/routing/compose-route-path.mjs.map +1 -1
  80. package/esm/routing/data-request.mjs +1 -1
  81. package/esm/routing/data-request.mjs.map +1 -1
  82. package/esm/routing/filesystem-route.mjs +45 -0
  83. package/esm/routing/filesystem-route.mjs.map +1 -0
  84. package/esm/routing/layout-policy.mjs +1 -1
  85. package/esm/routing/layout-policy.mjs.map +1 -1
  86. package/esm/routing/navigator.mjs +1 -1
  87. package/esm/routing/navigator.mjs.map +1 -1
  88. package/esm/routing/query-string.d.mts +1 -1
  89. package/esm/routing/query-string.mjs +1 -1
  90. package/esm/routing/query-string.mjs.map +1 -1
  91. package/esm/routing/route-identity.mjs +1 -1
  92. package/esm/routing/route-identity.mjs.map +1 -1
  93. package/esm/routing/route-table.d.mts +1 -1
  94. package/esm/routing/route-table.mjs +1 -1
  95. package/esm/routing/route-table.mjs.map +1 -1
  96. package/esm/routing/router-events.d.mts +1 -1
  97. package/esm/routing/router-events.mjs +1 -1
  98. package/esm/routing/router-events.mjs.map +1 -1
  99. package/esm/routing/url-fragment.mjs +1 -1
  100. package/esm/routing/url-fragment.mjs.map +1 -1
  101. package/esm/runtime/register-modules.d.mts +19 -0
  102. package/esm/runtime/register-modules.mjs +22 -0
  103. package/esm/runtime/register-modules.mjs.map +1 -0
  104. package/esm/server/build-hydration-payload.mjs +2 -1
  105. package/esm/server/build-hydration-payload.mjs.map +1 -1
  106. package/esm/server/client-asset-url-prefix.d.mts +1 -1
  107. package/esm/server/client-asset-url-prefix.mjs +1 -1
  108. package/esm/server/client-asset-url-prefix.mjs.map +1 -1
  109. package/esm/server/create-page-module-loader.d.mts +1 -1
  110. package/esm/server/create-page-module-loader.mjs +2 -1
  111. package/esm/server/create-page-module-loader.mjs.map +1 -1
  112. package/esm/server/create-page-route-handler.d.mts +31 -6
  113. package/esm/server/create-page-route-handler.mjs +128 -43
  114. package/esm/server/create-page-route-handler.mjs.map +1 -1
  115. package/esm/server/dev-server.mjs +2 -13
  116. package/esm/server/dev-server.mjs.map +1 -1
  117. package/esm/server/error-page.d.mts +14 -0
  118. package/esm/server/error-page.mjs +39 -0
  119. package/esm/server/error-page.mjs.map +1 -0
  120. package/esm/server/execute-page-request.d.mts +7 -4
  121. package/esm/server/execute-page-request.mjs +79 -80
  122. package/esm/server/execute-page-request.mjs.map +1 -1
  123. package/esm/server/execute-page-request.types.d.mts +33 -92
  124. package/esm/server/hydration-client-url.d.mts +1 -1
  125. package/esm/server/hydration-client-url.mjs +2 -2
  126. package/esm/server/hydration-client-url.mjs.map +1 -1
  127. package/esm/server/index.d.mts +5 -5
  128. package/esm/server/index.mjs +3 -4
  129. package/esm/server/install-page-routes-from-manifest.d.mts +17 -7
  130. package/esm/server/install-page-routes-from-manifest.mjs +71 -10
  131. package/esm/server/install-page-routes-from-manifest.mjs.map +1 -1
  132. package/esm/server/install-page-routes.d.mts +32 -15
  133. package/esm/server/install-page-routes.mjs +91 -39
  134. package/esm/server/install-page-routes.mjs.map +1 -1
  135. package/esm/server/install-production-page-routes.mjs +3 -36
  136. package/esm/server/install-production-page-routes.mjs.map +1 -1
  137. package/esm/server/match-page-route.mjs +2 -2
  138. package/esm/server/match-page-route.mjs.map +1 -1
  139. package/esm/server/not-found-page.d.mts +1 -1
  140. package/esm/server/not-found-page.mjs +2 -2
  141. package/esm/server/not-found-page.mjs.map +1 -1
  142. package/esm/server/page-context.d.mts +3 -9
  143. package/esm/server/page-context.mjs +3 -16
  144. package/esm/server/page-context.mjs.map +1 -1
  145. package/esm/server/page-file-change.mjs +77 -0
  146. package/esm/server/page-file-change.mjs.map +1 -0
  147. package/esm/server/page-manifest.d.mts +25 -10
  148. package/esm/server/page-manifest.mjs +1 -1
  149. package/esm/server/page-manifest.mjs.map +1 -1
  150. package/esm/server/page-render-bundle.mjs +38 -0
  151. package/esm/server/page-render-bundle.mjs.map +1 -0
  152. package/esm/server/page-route-reload.mjs +54 -0
  153. package/esm/server/page-route-reload.mjs.map +1 -0
  154. package/esm/server/register-production-public-files.mjs +40 -0
  155. package/esm/server/register-production-public-files.mjs.map +1 -0
  156. package/esm/server/render-page.d.mts +11 -14
  157. package/esm/server/render-page.mjs +154 -28
  158. package/esm/server/render-page.mjs.map +1 -1
  159. package/esm/server/resolve-page-metadata.mjs +2 -2
  160. package/esm/server/resolve-page-metadata.mjs.map +1 -1
  161. package/esm/server/resolve-validation-data.mjs +1 -1
  162. package/esm/server/resolve-validation-data.mjs.map +1 -1
  163. package/esm/server/settle-page-response.d.mts +58 -1
  164. package/esm/server/settle-page-response.mjs +111 -46
  165. package/esm/server/settle-page-response.mjs.map +1 -1
  166. package/esm/server/stylesheet-urls.d.mts +41 -30
  167. package/esm/server/stylesheet-urls.mjs +137 -52
  168. package/esm/server/stylesheet-urls.mjs.map +1 -1
  169. package/esm/server/unregistered-pages.mjs +42 -0
  170. package/esm/server/unregistered-pages.mjs.map +1 -0
  171. package/esm/server/web-connector-factory.d.mts +2 -3
  172. package/esm/server/web-connector-factory.mjs +7 -6
  173. package/esm/server/web-connector-factory.mjs.map +1 -1
  174. package/esm/server/web-connector.d.mts +1 -1
  175. package/esm/server/web-connector.mjs +138 -18
  176. package/esm/server/web-connector.mjs.map +1 -1
  177. package/esm/shared.d.mts +18 -3
  178. package/esm/shared.mjs +3 -7
  179. package/esm/shared.mjs.map +1 -1
  180. package/esm/validation.d.mts +1 -1
  181. package/esm/vite/app-convention-aliases.mjs +1 -1
  182. package/esm/vite/app-convention-aliases.mjs.map +1 -1
  183. package/esm/vite/build-client.d.mts +1 -1
  184. package/esm/vite/build-client.mjs +2 -2
  185. package/esm/vite/build-client.mjs.map +1 -1
  186. package/esm/vite/gate-a-resolve.d.mts +1 -1
  187. package/esm/vite/gate-a-resolve.mjs +67 -13
  188. package/esm/vite/gate-a-resolve.mjs.map +1 -1
  189. package/esm/vite/gate-b-secrets.d.mts +1 -1
  190. package/esm/vite/gate-b-secrets.mjs +35 -17
  191. package/esm/vite/gate-b-secrets.mjs.map +1 -1
  192. package/esm/vite/gate-c-verify.d.mts +1 -1
  193. package/esm/vite/gate-c-verify.mjs +6 -6
  194. package/esm/vite/gate-c-verify.mjs.map +1 -1
  195. package/esm/vite/hydration-entries.d.mts +1 -1
  196. package/esm/vite/hydration-entries.mjs +2 -2
  197. package/esm/vite/hydration-entries.mjs.map +1 -1
  198. package/esm/vite/index.d.mts +9 -6
  199. package/esm/vite/index.mjs +124 -11
  200. package/esm/vite/index.mjs.map +1 -1
  201. package/esm/vite/page-registry-plugin.d.mts +22 -3
  202. package/esm/vite/page-registry-plugin.mjs +48 -14
  203. package/esm/vite/page-registry-plugin.mjs.map +1 -1
  204. package/esm/vite/projection.d.mts +2 -2
  205. package/esm/vite/projection.mjs +38 -15
  206. package/esm/vite/projection.mjs.map +1 -1
  207. package/llms-full.txt +220 -56
  208. package/llms.txt +5 -3
  209. package/package.json +3 -3
  210. package/skills/add-web-to-an-app/SKILL.md +3 -3
  211. package/skills/create-a-page/SKILL.md +117 -10
  212. package/skills/load-page-data/SKILL.md +92 -12
  213. package/skills/navigate-on-the-client/SKILL.md +1 -1
  214. package/skills/serve-styles/SKILL.md +13 -12
  215. package/skills/use-layouts/SKILL.md +14 -8
  216. package/skills/write-the-root/SKILL.md +3 -1
  217. package/esm/server/buffered-response.d.mts +0 -58
  218. package/esm/server/buffered-response.mjs +0 -115
  219. package/esm/server/buffered-response.mjs.map +0 -1
@@ -1,7 +1,7 @@
1
1
  import { PageManifest } from "./page-manifest.mjs";
2
2
  import { PageModuleLoader } from "./create-page-route-handler.mjs";
3
3
 
4
- //#region ../web/src/server/create-page-module-loader.d.ts
4
+ //#region web/src/server/create-page-module-loader.d.ts
5
5
  /**
6
6
  * Asked for a module this build does not contain.
7
7
  *
@@ -1,4 +1,4 @@
1
- //#region ../web/src/server/create-page-module-loader.ts
1
+ //#region web/src/server/create-page-module-loader.ts
2
2
  /**
3
3
  * Asked for a module this build does not contain.
4
4
  *
@@ -33,6 +33,7 @@ var PageModuleNotInManifestError = class extends Error {
33
33
  function createPageModuleLoader(manifest) {
34
34
  const modulesById = /* @__PURE__ */ new Map();
35
35
  if (manifest.app) modulesById.set(manifest.app.sourceFile, manifest.app.module);
36
+ if (manifest.errorPage) modulesById.set(manifest.errorPage.sourceFile, manifest.errorPage.module);
36
37
  for (const page of manifest.pages) {
37
38
  modulesById.set(page.sourceFile, page.module);
38
39
  for (const layout of page.layouts) modulesById.set(layout.sourceFile, layout.module);
@@ -1 +1 @@
1
- {"version":3,"file":"create-page-module-loader.mjs","names":[],"sources":["../../../../../../../web/src/server/create-page-module-loader.ts"],"sourcesContent":["/**\n * The production answer to \"how do I load a page module\".\n *\n * `createPageRouteHandler` takes loading a module as an INPUT\n * ({@link PageModuleLoader}) precisely so the two runtimes can answer it\n * differently. Dev hands it `moduleId => vite.ssrLoadModule(moduleId)`;\n * production has no Vite and nothing to evaluate — the generated `pages.ts`\n * barrel already imported every page, layout and the app root statically, and\n * {@link PageManifest} is the table those namespace objects arrived in. So the\n * production loader does not load anything: it is a LOOKUP over modules that\n * are already in memory, and this file is that lookup and nothing else.\n */\nimport type { PageModuleLoader } from \"./create-page-route-handler\";\nimport type { PageManifest } from \"./page-manifest\";\n\n/**\n * Asked for a module this build does not contain.\n *\n * Hard failure, deliberately. Every alternative — returning `undefined`, an\n * empty namespace, or falling back to a dynamic import — turns a build that\n * shipped the wrong module table into a page that renders blank, or into a\n * production process reaching for source files that are not deployed. The id\n * is in the message because the whole diagnosis is \"which id, and why is it\n * not in the table\"; the count is there because zero entries means the build\n * discovered no pages at all, which is a different fault from a mismatch.\n */\nexport class PageModuleNotInManifestError extends Error {\n public constructor(moduleId: string, knownIdCount: number) {\n super(\n `Cannot serve a page module: \"${moduleId}\" is not in this build's page manifest ` +\n `(${knownIdCount} module(s) available). Module ids are the manifest's \\`sourceFile\\` ` +\n \"values — app-root-relative POSIX paths, extension included — and must match exactly. \" +\n \"Re-run `warlock build` so the generated `pages.ts` barrel matches what is being served.\",\n );\n this.name = \"PageModuleNotInManifestError\";\n }\n}\n\n/**\n * Build the loader for ONE manifest.\n *\n * Ids are compared by exact string equality against the `sourceFile` each\n * entry carries — no lowercasing, no separator swapping, no extension\n * stripping. Both sides of that comparison come from the same generator\n * (`generatePagesBarrel` writes every `sourceFile` through one\n * app-root-relative POSIX derivation), so any spelling difference is a real\n * disagreement about which file is meant, and a normalizer would only hide it.\n *\n * A layout shared by several pages appears once per chain it belongs to; the\n * generator emits one identifier per layout file, so every occurrence of an id\n * carries the same namespace object and re-registering it is a no-op.\n */\nexport function createPageModuleLoader(manifest: PageManifest): PageModuleLoader {\n const modulesById = new Map<string, Record<string, unknown>>();\n\n if (manifest.app) {\n modulesById.set(manifest.app.sourceFile, manifest.app.module);\n }\n\n for (const page of manifest.pages) {\n modulesById.set(page.sourceFile, page.module);\n\n for (const layout of page.layouts) {\n modulesById.set(layout.sourceFile, layout.module);\n }\n }\n\n // `async` so an unknown id surfaces as a rejection rather than a synchronous\n // throw: the handler awaits every module through one `Promise.all`, and a\n // loader that fails both ways depending on the reason is a loader callers\n // have to guard twice.\n return async (moduleId: string) => {\n const module = modulesById.get(moduleId);\n\n if (module === undefined) {\n throw new PageModuleNotInManifestError(moduleId, modulesById.size);\n }\n\n return module;\n };\n}\n"],"mappings":";;;;;;;;;;;;AA0BA,IAAa,+BAAb,cAAkD,MAAM;CACtD,AAAO,YAAY,UAAkB,cAAsB;EACzD,MACE,gCAAgC,SAAS,0CACnC,aAAa,qPAGrB;EACA,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,uBAAuB,UAA0C;CAC/E,MAAM,8BAAc,IAAI,IAAqC;CAE7D,IAAI,SAAS,KACX,YAAY,IAAI,SAAS,IAAI,YAAY,SAAS,IAAI,MAAM;CAG9D,KAAK,MAAM,QAAQ,SAAS,OAAO;EACjC,YAAY,IAAI,KAAK,YAAY,KAAK,MAAM;EAE5C,KAAK,MAAM,UAAU,KAAK,SACxB,YAAY,IAAI,OAAO,YAAY,OAAO,MAAM;CAEpD;CAMA,OAAO,OAAO,aAAqB;EACjC,MAAM,SAAS,YAAY,IAAI,QAAQ;EAEvC,IAAI,WAAW,QACb,MAAM,IAAI,6BAA6B,UAAU,YAAY,IAAI;EAGnE,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"create-page-module-loader.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/create-page-module-loader.ts"],"sourcesContent":["/**\n * The production answer to \"how do I load a page module\".\n *\n * `createPageRouteHandler` takes loading a module as an INPUT\n * ({@link PageModuleLoader}) precisely so the two runtimes can answer it\n * differently. Dev hands it `moduleId => vite.ssrLoadModule(moduleId)`;\n * production has no Vite and nothing to evaluate — the generated `pages.ts`\n * barrel already imported every page, layout and the app root statically, and\n * {@link PageManifest} is the table those namespace objects arrived in. So the\n * production loader does not load anything: it is a LOOKUP over modules that\n * are already in memory, and this file is that lookup and nothing else.\n */\nimport type { PageModuleLoader } from \"./create-page-route-handler\";\nimport type { PageManifest } from \"./page-manifest\";\n\n/**\n * Asked for a module this build does not contain.\n *\n * Hard failure, deliberately. Every alternative — returning `undefined`, an\n * empty namespace, or falling back to a dynamic import — turns a build that\n * shipped the wrong module table into a page that renders blank, or into a\n * production process reaching for source files that are not deployed. The id\n * is in the message because the whole diagnosis is \"which id, and why is it\n * not in the table\"; the count is there because zero entries means the build\n * discovered no pages at all, which is a different fault from a mismatch.\n */\nexport class PageModuleNotInManifestError extends Error {\n public constructor(moduleId: string, knownIdCount: number) {\n super(\n `Cannot serve a page module: \"${moduleId}\" is not in this build's page manifest ` +\n `(${knownIdCount} module(s) available). Module ids are the manifest's \\`sourceFile\\` ` +\n \"values — app-root-relative POSIX paths, extension included — and must match exactly. \" +\n \"Re-run `warlock build` so the generated `pages.ts` barrel matches what is being served.\",\n );\n this.name = \"PageModuleNotInManifestError\";\n }\n}\n\n/**\n * Build the loader for ONE manifest.\n *\n * Ids are compared by exact string equality against the `sourceFile` each\n * entry carries — no lowercasing, no separator swapping, no extension\n * stripping. Both sides of that comparison come from the same generator\n * (`generatePagesBarrel` writes every `sourceFile` through one\n * app-root-relative POSIX derivation), so any spelling difference is a real\n * disagreement about which file is meant, and a normalizer would only hide it.\n *\n * A layout shared by several pages appears once per chain it belongs to; the\n * generator emits one identifier per layout file, so every occurrence of an id\n * carries the same namespace object and re-registering it is a no-op.\n */\nexport function createPageModuleLoader(manifest: PageManifest): PageModuleLoader {\n const modulesById = new Map<string, Record<string, unknown>>();\n\n if (manifest.app) {\n modulesById.set(manifest.app.sourceFile, manifest.app.module);\n }\n\n if (manifest.errorPage) {\n modulesById.set(manifest.errorPage.sourceFile, manifest.errorPage.module);\n }\n\n for (const page of manifest.pages) {\n modulesById.set(page.sourceFile, page.module);\n\n for (const layout of page.layouts) {\n modulesById.set(layout.sourceFile, layout.module);\n }\n }\n\n // `async` so an unknown id surfaces as a rejection rather than a synchronous\n // throw: the handler awaits every module through one `Promise.all`, and a\n // loader that fails both ways depending on the reason is a loader callers\n // have to guard twice.\n return async (moduleId: string) => {\n const module = modulesById.get(moduleId);\n\n if (module === undefined) {\n throw new PageModuleNotInManifestError(moduleId, modulesById.size);\n }\n\n return module;\n };\n}\n"],"mappings":";;;;;;;;;;;;AA0BA,IAAa,+BAAb,cAAkD,MAAM;CACtD,AAAO,YAAY,UAAkB,cAAsB;EACzD,MACE,gCAAgC,SAAS,0CACnC,aAAa,qPAGrB;EACA,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,uBAAuB,UAA0C;CAC/E,MAAM,8BAAc,IAAI,IAAqC;CAE7D,IAAI,SAAS,KACX,YAAY,IAAI,SAAS,IAAI,YAAY,SAAS,IAAI,MAAM;CAG9D,IAAI,SAAS,WACX,YAAY,IAAI,SAAS,UAAU,YAAY,SAAS,UAAU,MAAM;CAG1E,KAAK,MAAM,QAAQ,SAAS,OAAO;EACjC,YAAY,IAAI,KAAK,YAAY,KAAK,MAAM;EAE5C,KAAK,MAAM,UAAU,KAAK,SACxB,YAAY,IAAI,OAAO,YAAY,OAAO,MAAM;CAEpD;CAMA,OAAO,OAAO,aAAqB;EACjC,MAAM,SAAS,YAAY,IAAI,QAAQ;EAEvC,IAAI,WAAW,QACb,MAAM,IAAI,6BAA6B,UAAU,YAAY,IAAI;EAGnE,OAAO;CACT;AACF"}
@@ -1,7 +1,9 @@
1
- import { BufferedCookie } from "./buffered-response.mjs";
1
+ import { RegisterableModuleNamespace } from "../runtime/register-modules.mjs";
2
+ import { BufferedCookie } from "./settle-page-response.mjs";
3
+ import { ErrorPageModuleLoader } from "./error-page.mjs";
2
4
  import { HttpContext, Response } from "@warlock.js/core";
3
5
 
4
- //#region ../web/src/server/create-page-route-handler.d.ts
6
+ //#region web/src/server/create-page-route-handler.d.ts
5
7
  /**
6
8
  * How the handler obtains a page/layout/app module, by the same id
7
9
  * (`appFile`/`layoutFile`/`pageFile`) the caller registered it under. In dev
@@ -15,15 +17,24 @@ type PageRouteHandlerOptions = {
15
17
  appFile: string; /** The page module's id. */
16
18
  pageFile: string; /** The page's own-directory `layout.tsx`, when it has one. */
17
19
  layoutFile?: string | undefined;
18
- loadModule: PageModuleLoader; /** Browser module appended after the server-rendered document. */
20
+ loadModule: PageModuleLoader; /** Optional lazy application `error.page.tsx` loader. Never called on success. */
21
+ loadErrorPage?: ErrorPageModuleLoader;
22
+ /**
23
+ * Load the REAL layout module namespaces, outermost first, for universal
24
+ * registration. This stays separate from `loadModule(layoutFile)` because
25
+ * dev may answer that id with a synthetic wrapper whose middleware is the
26
+ * composition of several layouts. That wrapper is a render-pipeline detail,
27
+ * not a module identity, and must never enter `registerModules`' WeakSet.
28
+ */
29
+ loadRegistrationLayouts?: () => Promise<readonly RegisterableModuleNamespace[]>; /** Browser module appended after the server-rendered document. */
19
30
  hydrationClientModuleUrl?: string;
20
31
  /**
21
32
  * Stylesheet URLs for this page, emitted into `<head>` so the FIRST paint is
22
33
  * styled. Absent or empty means the application has no CSS — it never means
23
34
  * a stylesheet failed to resolve, which is the build's job to report.
24
35
  */
25
- stylesheetUrls?: readonly string[]; /** Same helper `dev-server.ts` exports — passed in, never imported. */
26
- applyBufferedCookie: (response: Response, cookie: BufferedCookie) => void;
36
+ stylesheetUrls?: readonly string[];
37
+ /** Same helper `dev-server.ts` exports — passed in, never imported. */
27
38
  /**
28
39
  * The pattern stage 1 matches `request.path` against, when it differs from
29
40
  * the REGISTERED path. Defaults to `path`, which is right for every route
@@ -51,8 +62,22 @@ type PageRouteHandlerOptions = {
51
62
  * a redirect — and overwriting it would report a broken page as a missing one.
52
63
  */
53
64
  statusForRenderedOk?: number;
65
+ /**
66
+ * Exclude the page module's loader from the request triple while preserving
67
+ * the real namespace for `register()` and rendering. Used only by the
68
+ * catch-all 404 page: a missing URL must not run application data work or
69
+ * turn a simple miss into a second failure path.
70
+ */
71
+ skipPageLoader?: boolean;
72
+ /**
73
+ * Replays one committed cookie through core's `Response.cookie()`. Defaults
74
+ * to doing exactly that (`defaultApplyBufferedCookie`, above); injectable so
75
+ * a caller with a different `Response` shape (or a test) can observe/replace
76
+ * the call.
77
+ */
78
+ applyBufferedCookie?: (response: Response, cookie: BufferedCookie) => void;
54
79
  };
55
- type PageRouteHandler = (context: HttpContext) => Promise<void>;
80
+ type PageRouteHandler = (context: HttpContext) => Promise<void | Response>;
56
81
  //#endregion
57
82
  export { PageModuleLoader, PageRouteHandler, PageRouteHandlerOptions };
58
83
  //# sourceMappingURL=create-page-route-handler.d.mts.map
@@ -1,8 +1,56 @@
1
1
  import { DATA_RESPONSE_CONTENT_TYPE, WARLOCK_DATA_REQUEST_HEADER, isDataRequest } from "../routing/data-request.mjs";
2
+ import { isNonHydrating } from "./page-render-bundle.mjs";
3
+ import { registerModules } from "../runtime/register-modules.mjs";
2
4
  import { buildHydrationPayload } from "./build-hydration-payload.mjs";
3
- import { renderPageRequest } from "./render-page.mjs";
5
+ import { renderPageFailure, renderPageRequest } from "./render-page.mjs";
6
+ import { Response } from "@warlock.js/core";
4
7
 
5
- //#region ../web/src/server/create-page-route-handler.ts
8
+ //#region web/src/server/create-page-route-handler.ts
9
+ /**
10
+ * The page handler, as a named seam.
11
+ *
12
+ * This is the request handler `installPageRoutes` used to inline into its
13
+ * `router.get(...)` call (`install-page-routes.ts:236-275` before this
14
+ * extraction; the pre-extraction copy is `scratchpad/install-page-routes.ts.orig`).
15
+ * The behaviour is unchanged, byte for byte — what changes is that it is now
16
+ * a named, exported, independently constructible function instead of a closure
17
+ * over eight ambient bindings of `installPageRoutes`.
18
+ *
19
+ * WHY IT TAKES `loadModule` AND NOT A `ViteDevServer`: loading a module is the
20
+ * only capability the handler ever needed, and the two runtimes answer it
21
+ * differently — dev goes through Vite's SSR graph
22
+ * (`vite.ssrLoadModule`, `install-page-routes.ts:207`), production reads the
23
+ * already-built page manifest (`page-manifest.ts`). Taking "how to load a
24
+ * module" as an INPUT is what lets the same handler serve both, and what lets
25
+ * a test construct it with a plain async function — no Vite, no dev server, no
26
+ * `app/` directory on disk.
27
+ *
28
+ * Scope: this file creates a seam and nothing else. It does not implement
29
+ * `type: "page"` routing, HTML error pages, or any other new capability.
30
+ */
31
+ /**
32
+ * Replay ONE committed cookie through core's own `Response.cookie()` — the
33
+ * same serializer every ordinary controller's cookie goes through, so there
34
+ * is nothing here for a second implementation to drift from. The one-liner
35
+ * `dev-server.ts` wires as the production default; passed in (`applyBufferedCookie`
36
+ * option, below) rather than imported so this file stays free of anything
37
+ * Vite-shaped.
38
+ */
39
+ function defaultApplyBufferedCookie(response, cookie) {
40
+ response.cookie(cookie.name, cookie.value, cookie.options ?? {});
41
+ }
42
+ /**
43
+ * Stage 10a — apply the stage 7 commit (headers, then cookies) to the LIVE
44
+ * response, once, before either terminal write (10b: `html()` or `send()`).
45
+ * Both the document and data representations of a page route go through this
46
+ * so a client navigation never drops a `Set-Cookie` a full load would have
47
+ * kept (`create-page-route-handler.spec.ts` — "applies committed cookies and
48
+ * headers exactly as the document path does").
49
+ */
50
+ function applyCommit(response, rendered, applyBufferedCookie) {
51
+ response.headers(rendered.headers ?? {});
52
+ for (const cookie of rendered.cookies ?? []) applyBufferedCookie(response, cookie);
53
+ }
6
54
  function escapeHtmlAttribute(value) {
7
55
  return value.replace(/[&<>"']/g, (character) => {
8
56
  switch (character) {
@@ -49,58 +97,95 @@ function installStylesheets(html, stylesheetUrls) {
49
97
  /**
50
98
  * Build the handler for ONE page route. Per request it loads the App + layout
51
99
  * + page triple (concurrently, in that order), renders the URL through
52
- * `renderPageRequest`, splices in the hydration module, applies the committed
53
- * cookies and headers, and flushes the document.
100
+ * `renderPageRequest`, splices in the hydration module, and flushes the
101
+ * document.
54
102
  *
55
103
  * No try/catch, deliberately: loader/render throws are already absorbed by the
56
104
  * pipeline's boundary machinery inside `renderPageRequest`, and anything that
57
- * escapes (a module-load failure, the missing-`</body>` throw above) belongs to
58
- * the router's error path — which is exactly where it went before.
105
+ * escapes (a module-load or register failure, the missing-`</body>` throw
106
+ * above) belongs to the router's error path — which is exactly where it went
107
+ * before.
59
108
  */
60
109
  function createPageRouteHandler(options) {
61
- const { path, name, appFile, pageFile, layoutFile, loadModule, hydrationClientModuleUrl, stylesheetUrls, applyBufferedCookie, matchPath, statusForRenderedOk } = options;
110
+ const { path, name, appFile, pageFile, layoutFile, loadModule, loadErrorPage, loadRegistrationLayouts, hydrationClientModuleUrl, stylesheetUrls, matchPath, statusForRenderedOk, skipPageLoader = false, applyBufferedCookie = defaultApplyBufferedCookie } = options;
62
111
  return async ({ request, response }) => {
63
- const [appModule, layoutModule, ownPageModule] = await Promise.all([
64
- loadModule(appFile),
65
- layoutFile ? loadModule(layoutFile) : Promise.resolve({}),
66
- loadModule(pageFile)
67
- ]);
68
- const triple = {
69
- app: appModule,
70
- layout: layoutModule,
71
- page: ownPageModule
72
- };
73
- const routes = [{
74
- path: matchPath === void 0 ? path : matchPath(request.path),
75
- name,
76
- triple
77
- }];
78
112
  const wantsData = isDataRequest(request.header(WARLOCK_DATA_REQUEST_HEADER, void 0));
79
- const rendered = await renderPageRequest(request.path, {
80
- routes,
81
- createHttp: () => ({
82
- request,
83
- response
84
- })
85
- });
86
- const status = rendered.status === 200 && statusForRenderedOk !== void 0 ? statusForRenderedOk : rendered.status;
87
- if (wantsData) {
88
- for (const cookie of rendered.cookies) applyBufferedCookie(response, cookie);
89
- response.headers(rendered.headers);
90
- response.header("Vary", WARLOCK_DATA_REQUEST_HEADER);
91
- if (rendered.bundle === void 0) {
113
+ try {
114
+ const [appModule, layoutModule, ownPageModule, registrationLayouts] = await Promise.all([
115
+ loadModule(appFile),
116
+ layoutFile ? loadModule(layoutFile) : Promise.resolve({}),
117
+ loadModule(pageFile),
118
+ loadRegistrationLayouts?.() ?? Promise.resolve([])
119
+ ]);
120
+ registerModules([
121
+ appModule,
122
+ ...registrationLayouts,
123
+ ownPageModule
124
+ ]);
125
+ const pageModule = ownPageModule;
126
+ const triple = {
127
+ app: appModule,
128
+ layout: layoutModule,
129
+ page: skipPageLoader ? {
130
+ ...pageModule,
131
+ default: pageModule.default,
132
+ loader: void 0
133
+ } : pageModule
134
+ };
135
+ const requestUrl = request.path;
136
+ const [requestPathname] = requestUrl.split("?");
137
+ const rendered = await renderPageRequest(requestUrl, {
138
+ routes: [{
139
+ path: matchPath === void 0 ? path : matchPath(requestPathname),
140
+ name,
141
+ triple
142
+ }],
143
+ createHttp: () => ({
144
+ request,
145
+ response
146
+ }),
147
+ loadErrorPage
148
+ });
149
+ if (rendered instanceof Response) return rendered;
150
+ const status = rendered.status === 200 && statusForRenderedOk !== void 0 ? statusForRenderedOk : rendered.status;
151
+ applyCommit(response, rendered, applyBufferedCookie);
152
+ if (wantsData) {
153
+ response.header("Vary", WARLOCK_DATA_REQUEST_HEADER);
154
+ if (rendered.bundle === void 0) {
155
+ response.setContentType(DATA_RESPONSE_CONTENT_TYPE);
156
+ await response.send(JSON.stringify({ error: "not_found" }), status);
157
+ return;
158
+ }
92
159
  response.setContentType(DATA_RESPONSE_CONTENT_TYPE);
93
- await response.send(JSON.stringify({ error: "not_found" }), status);
160
+ await response.send(JSON.stringify(buildHydrationPayload(rendered.bundle)), status);
94
161
  return;
95
162
  }
96
- response.setContentType(DATA_RESPONSE_CONTENT_TYPE);
97
- await response.send(JSON.stringify(buildHydrationPayload(rendered.bundle)), status);
98
- return;
163
+ const html = installHydrationClientModule(installStylesheets(rendered.html, stylesheetUrls ?? []), hydrationClientModuleUrl, hydrationClientModuleUrl === void 0 ? void 0 : request.nonce);
164
+ await response.html(html, status);
165
+ } catch (thrown) {
166
+ try {
167
+ const rendered = await renderPageFailure({
168
+ name,
169
+ path: request.path,
170
+ request,
171
+ response,
172
+ thrown,
173
+ loadErrorPage
174
+ });
175
+ applyCommit(response, rendered, applyBufferedCookie);
176
+ if (wantsData) {
177
+ response.header("Vary", WARLOCK_DATA_REQUEST_HEADER);
178
+ response.setContentType(DATA_RESPONSE_CONTENT_TYPE);
179
+ await response.send(JSON.stringify(buildHydrationPayload(rendered.bundle)), 500);
180
+ return;
181
+ }
182
+ const styled = installStylesheets(rendered.html, stylesheetUrls ?? []);
183
+ const html = isNonHydrating(rendered.bundle) ? styled : installHydrationClientModule(styled, hydrationClientModuleUrl, hydrationClientModuleUrl === void 0 ? void 0 : request.nonce);
184
+ await response.html(html, 500);
185
+ } catch {
186
+ throw thrown;
187
+ }
99
188
  }
100
- const html = installHydrationClientModule(installStylesheets(rendered.html, stylesheetUrls ?? []), hydrationClientModuleUrl, hydrationClientModuleUrl === void 0 ? void 0 : request.nonce);
101
- for (const cookie of rendered.cookies) applyBufferedCookie(response, cookie);
102
- response.headers(rendered.headers);
103
- await response.html(html, status);
104
189
  };
105
190
  }
106
191
 
@@ -1 +1 @@
1
- {"version":3,"file":"create-page-route-handler.mjs","names":[],"sources":["../../../../../../../web/src/server/create-page-route-handler.ts"],"sourcesContent":["/**\n * The page handler, as a named seam.\n *\n * This is the request handler `installPageRoutes` used to inline into its\n * `router.get(...)` call (`install-page-routes.ts:236-275` before this\n * extraction; the pre-extraction copy is `scratchpad/install-page-routes.ts.orig`).\n * The behaviour is unchanged, byte for byte — what changes is that it is now\n * a named, exported, independently constructible function instead of a closure\n * over eight ambient bindings of `installPageRoutes`.\n *\n * WHY IT TAKES `loadModule` AND NOT A `ViteDevServer`: loading a module is the\n * only capability the handler ever needed, and the two runtimes answer it\n * differently — dev goes through Vite's SSR graph\n * (`vite.ssrLoadModule`, `install-page-routes.ts:207`), production reads the\n * already-built page manifest (`page-manifest.ts`). Taking \"how to load a\n * module\" as an INPUT is what lets the same handler serve both, and what lets\n * a test construct it with a plain async function — no Vite, no dev server, no\n * `app/` directory on disk.\n *\n * Scope: this file creates a seam and nothing else. It does not implement\n * `type: \"page\"` routing, HTML error pages, or any other new capability.\n */\nimport type { HttpContext, Response } from \"@warlock.js/core\";\n\nimport {\n DATA_RESPONSE_CONTENT_TYPE,\n isDataRequest,\n WARLOCK_DATA_REQUEST_HEADER,\n} from \"../routing/data-request\";\nimport { buildHydrationPayload } from \"./build-hydration-payload\";\nimport type { BufferedCookie } from \"./buffered-response\";\nimport type { PageRouteEntry, PageTripleModule } from \"./execute-page-request\";\nimport { renderPageRequest } from \"./render-page\";\n\n/**\n * How the handler obtains a page/layout/app module, by the same id\n * (`appFile`/`layoutFile`/`pageFile`) the caller registered it under. In dev\n * this is `moduleId => vite.ssrLoadModule(moduleId)`; the connector already\n * owns the dev/prod split, so the handler never learns which one it got.\n */\nexport type PageModuleLoader = (moduleId: string) => Promise<unknown>;\n\nexport type PageRouteHandlerOptions = {\n /** The composed, registered route path — `composeRoutePath`'s output. */\n path: string;\n /** The resolved route name; shared namespace with API routes. */\n name: string;\n /** The single global app-root file, e.g. `<appSrcRoot>/web/root.tsx`. */\n appFile: string;\n /** The page module's id. */\n pageFile: string;\n /** The page's own-directory `layout.tsx`, when it has one. */\n layoutFile?: string | undefined;\n loadModule: PageModuleLoader;\n /** Browser module appended after the server-rendered document. */\n hydrationClientModuleUrl?: string;\n /**\n * Stylesheet URLs for this page, emitted into `<head>` so the FIRST paint is\n * styled. Absent or empty means the application has no CSS — it never means\n * a stylesheet failed to resolve, which is the build's job to report.\n */\n stylesheetUrls?: readonly string[];\n /** Same helper `dev-server.ts` exports — passed in, never imported. */\n applyBufferedCookie: (response: Response, cookie: BufferedCookie) => void;\n /**\n * The pattern stage 1 matches `request.path` against, when it differs from\n * the REGISTERED path. Defaults to `path`, which is right for every route\n * whose URL is its own.\n *\n * Exactly one route needs it: the not-found page, registered on the catch-all\n * `*`. `matchRoute` compares segment by segment (`./match-page-route.ts`) and\n * has no wildcard token, so a route registered as `*` matches NOTHING — the\n * pipeline reports no match and `renderPageRequest` answers `{ html: \"\",\n * status: 404 }`. Correct status, empty document: a 404 page that never\n * renders its own body. Handing it `requestPath => requestPath` makes the\n * requested URL the route's pattern for that one request, so the match is\n * trivially true and the page renders for the URL the visitor actually asked\n * for.\n */\n matchPath?: (requestPath: string) => string;\n /**\n * The status this route answers with when the pipeline settles on a plain\n * `200` — the not-found route's `404`, and nothing else uses it.\n *\n * Applied ONLY to `200`, never as a blanket override: a `200` from this\n * pipeline means \"the document rendered and nobody objected\", which for this\n * route is precisely the not-found case. Any other settled status is a real\n * outcome that the page or the boundary decided — a 500 from a failed render,\n * a redirect — and overwriting it would report a broken page as a missing one.\n */\n statusForRenderedOk?: number;\n};\n\nexport type PageRouteHandler = (context: HttpContext) => Promise<void>;\n\nfunction escapeHtmlAttribute(value: string): string {\n return value.replace(/[&<>\"']/g, (character) => {\n switch (character) {\n case \"&\":\n return \"&amp;\";\n case \"<\":\n return \"&lt;\";\n case \">\":\n return \"&gt;\";\n case '\"':\n return \"&quot;\";\n default:\n return \"&#39;\";\n }\n });\n}\n\nfunction installHydrationClientModule(\n html: string,\n moduleUrl: string | undefined,\n nonce: string | undefined,\n): string {\n if (moduleUrl === undefined || html === \"\") return html;\n\n const closingBodyIndex = html.lastIndexOf(\"</body>\");\n if (closingBodyIndex === -1) {\n throw new Error(\n \"installPageRoutes: cannot install the hydration client module because the rendered document has no closing </body> tag.\",\n );\n }\n\n const nonceAttribute = nonce === undefined ? \"\" : ` nonce=\"${escapeHtmlAttribute(nonce)}\"`;\n const script = `<script type=\"module\"${nonceAttribute} src=\"${escapeHtmlAttribute(moduleUrl)}\"></script>`;\n return `${html.slice(0, closingBodyIndex)}${script}${html.slice(closingBodyIndex)}`;\n}\n\n/**\n * Put the page's stylesheets in `<head>`, so the first paint is styled.\n *\n * Without this the document carries no CSS at all. The stylesheet reaches the\n * browser only because the CLIENT bundle imports it, which means it is applied\n * by JavaScript after the module graph loads — the page renders unstyled first\n * and restyles a moment later. Correct markup, wrong-looking page, and nothing\n * in the console to explain it.\n *\n * A `<link>` in `<head>` is render-blocking, which is exactly what is wanted\n * here: the browser holds the first paint until the CSS is in, so there is no\n * flash rather than a faster ugly one.\n *\n * Inserted before `</head>` rather than after `<head>` so an application's own\n * `<link>`/`<style>` in the root document still comes FIRST and can be\n * overridden by these — matching how the framework's tags are documented to\n * behave, and keeping cascade order predictable.\n */\nfunction installStylesheets(html: string, stylesheetUrls: readonly string[]): string {\n if (stylesheetUrls.length === 0 || html === \"\") return html;\n\n const closingHeadIndex = html.lastIndexOf(\"</head>\");\n\n // No `<head>` is not an error the way a missing `</body>` is: a root that\n // renders no head is unusual but legal, and losing the stylesheet is a\n // cosmetic failure where losing hydration is a broken page. Silently\n // dropping it would be the wrong trade the other way, though — so the\n // document is left exactly as rendered and the caller's own missing-`</body>`\n // check remains the loud one.\n if (closingHeadIndex === -1) return html;\n\n const links = stylesheetUrls\n .map((url) => `<link rel=\"stylesheet\" href=\"${escapeHtmlAttribute(url)}\">`)\n .join(\"\");\n\n return `${html.slice(0, closingHeadIndex)}${links}${html.slice(closingHeadIndex)}`;\n}\n\n/**\n * Build the handler for ONE page route. Per request it loads the App + layout\n * + page triple (concurrently, in that order), renders the URL through\n * `renderPageRequest`, splices in the hydration module, applies the committed\n * cookies and headers, and flushes the document.\n *\n * No try/catch, deliberately: loader/render throws are already absorbed by the\n * pipeline's boundary machinery inside `renderPageRequest`, and anything that\n * escapes (a module-load failure, the missing-`</body>` throw above) belongs to\n * the router's error path — which is exactly where it went before.\n */\nexport function createPageRouteHandler(options: PageRouteHandlerOptions): PageRouteHandler {\n const {\n path,\n name,\n appFile,\n pageFile,\n layoutFile,\n loadModule,\n hydrationClientModuleUrl,\n stylesheetUrls,\n applyBufferedCookie,\n matchPath,\n statusForRenderedOk,\n } = options;\n\n return async ({ request, response }: HttpContext) => {\n const [appModule, layoutModule, ownPageModule] = await Promise.all([\n loadModule(appFile),\n layoutFile ? loadModule(layoutFile) : Promise.resolve({}),\n loadModule(pageFile),\n ]);\n\n const triple: PageRouteEntry[\"triple\"] = {\n app: appModule as PageTripleModule,\n layout: layoutModule as PageTripleModule,\n page: ownPageModule as PageTripleModule,\n };\n\n const routes: PageRouteEntry[] = [\n { path: matchPath === undefined ? path : matchPath(request.path), name, triple },\n ];\n\n // A DATA request runs everything above and below this line identically —\n // it is the same route, the same match and the same pipeline — and differs\n // only in what gets written at the end. Decided here, before the render, so\n // the branch is visibly about REPRESENTATION and not about behaviour.\n const wantsData = isDataRequest(request.header(WARLOCK_DATA_REQUEST_HEADER, undefined));\n\n const rendered = await renderPageRequest(request.path, {\n routes,\n createHttp: () => ({ request, response }),\n });\n\n // See `statusForRenderedOk`: a settled 200 is the only status this route is\n // allowed to restate, and both the document and the data branch below must\n // restate it the same way — a client navigation that received 200 with a\n // not-found payload would push the URL into history as a real page.\n const status =\n rendered.status === 200 && statusForRenderedOk !== undefined\n ? statusForRenderedOk\n : rendered.status;\n\n if (wantsData) {\n // Cookies and headers FIRST, exactly as the document path does below and\n // for the same reason: a client navigation must be able to log a user in,\n // set a flash cookie or be redirected, and dropping those on this path\n // would make a navigation behave differently from a page load of the same\n // URL — the one difference this branch is not allowed to introduce.\n for (const cookie of rendered.cookies) {\n applyBufferedCookie(response, cookie);\n }\n\n response.headers(rendered.headers);\n\n // So a shared cache can never serve a document to a client that asked for\n // JSON, or the reverse. See `data-request.ts` on why this stays even\n // while page responses are `no-store`.\n response.header(\"Vary\", WARLOCK_DATA_REQUEST_HEADER);\n\n // `bundle` is absent on exactly one path: nothing matched, so no pipeline\n // ran and there is no payload to build. Fastify already matched this\n // route to get here, so reaching it means `request.path` did not satisfy\n // the entry's own pattern — answered as the 404 it is, rather than\n // synthesising an empty payload the client would try to render as a page.\n if (rendered.bundle === undefined) {\n response.setContentType(DATA_RESPONSE_CONTENT_TYPE);\n await response.send(JSON.stringify({ error: \"not_found\" }), status);\n\n return;\n }\n\n // SERIALIZED HERE, and handed over as a STRING on purpose.\n //\n // `response.send(object)` runs the body through core's `Response.parse`,\n // which recurses the object, calls `toJSON()` on anything that has one\n // (assigning `request` onto it as it goes) and rebuilds arrays. That is\n // the right behaviour for a controller returning Resources; it is the\n // wrong behaviour here, because the DOCUMENT path serializes this exact\n // object with a plain `JSON.stringify` into `#__WARLOCK_DATA__`. Routing\n // one path through a transformer and not the other is precisely the\n // drift `build-hydration-payload.ts` exists to prevent — the browser\n // would build one tree on a page load and a different one on a\n // navigation to the same URL.\n //\n // A string body also bypasses `parseBody()` entirely, so the content type\n // has to be declared rather than inferred from an object body.\n response.setContentType(DATA_RESPONSE_CONTENT_TYPE);\n await response.send(JSON.stringify(buildHydrationPayload(rendered.bundle)), status);\n\n return;\n }\n\n // Stylesheets first: they go in `<head>`, the hydration module goes before\n // `</body>`, and doing the head work on the already-rendered string keeps\n // both splices in one place rather than threading CSS through the React\n // render just to reach the same bytes.\n const styled = installStylesheets(rendered.html, stylesheetUrls ?? []);\n\n const html = installHydrationClientModule(\n styled,\n hydrationClientModuleUrl,\n hydrationClientModuleUrl === undefined ? undefined : request.nonce,\n );\n\n // THE single site that puts a committed cookie on the wire. The commit\n // stage used to mirror the same list onto the live response as well\n // (`commitBuffers`, execute-page-request.ts), and because fastify's\n // `setCookie` APPENDS rather than sets, every page response carried two\n // identical `Set-Cookie` headers — happy path included. The mirror's\n // cookie half is gone; this loop is what remains, and it is the right\n // one: it runs at stage 10a, after the render, alongside the headers and\n // the final status, so it applies the answer the pipeline actually\n // settled on rather than the one it had at stage 7.\n for (const cookie of rendered.cookies) {\n applyBufferedCookie(response, cookie);\n }\n\n response.headers(rendered.headers);\n\n await response.html(html, status);\n };\n}\n"],"mappings":";;;;;AA+FA,SAAS,oBAAoB,OAAuB;CAClD,OAAO,MAAM,QAAQ,aAAa,cAAc;EAC9C,QAAQ,WAAR;GACE,KAAK,KACH,OAAO;GACT,KAAK,KACH,OAAO;GACT,KAAK,KACH,OAAO;GACT,KAAK,MACH,OAAO;GACT,SACE,OAAO;EACX;CACF,CAAC;AACH;AAEA,SAAS,6BACP,MACA,WACA,OACQ;CACR,IAAI,cAAc,UAAa,SAAS,IAAI,OAAO;CAEnD,MAAM,mBAAmB,KAAK,YAAY,SAAS;CACnD,IAAI,qBAAqB,IACvB,MAAM,IAAI,MACR,yHACF;CAIF,MAAM,SAAS,wBADQ,UAAU,SAAY,KAAK,WAAW,oBAAoB,KAAK,EAAE,GAClC,QAAQ,oBAAoB,SAAS,EAAE;CAC7F,OAAO,GAAG,KAAK,MAAM,GAAG,gBAAgB,IAAI,SAAS,KAAK,MAAM,gBAAgB;AAClF;;;;;;;;;;;;;;;;;;;AAoBA,SAAS,mBAAmB,MAAc,gBAA2C;CACnF,IAAI,eAAe,WAAW,KAAK,SAAS,IAAI,OAAO;CAEvD,MAAM,mBAAmB,KAAK,YAAY,SAAS;CAQnD,IAAI,qBAAqB,IAAI,OAAO;CAEpC,MAAM,QAAQ,eACX,KAAK,QAAQ,gCAAgC,oBAAoB,GAAG,EAAE,GAAG,CAAC,CAC1E,KAAK,EAAE;CAEV,OAAO,GAAG,KAAK,MAAM,GAAG,gBAAgB,IAAI,QAAQ,KAAK,MAAM,gBAAgB;AACjF;;;;;;;;;;;;AAaA,SAAgB,uBAAuB,SAAoD;CACzF,MAAM,EACJ,MACA,MACA,SACA,UACA,YACA,YACA,0BACA,gBACA,qBACA,WACA,wBACE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+ {"version":3,"file":"create-page-route-handler.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/create-page-route-handler.ts"],"sourcesContent":["/**\r\n * The page handler, as a named seam.\r\n *\r\n * This is the request handler `installPageRoutes` used to inline into its\r\n * `router.get(...)` call (`install-page-routes.ts:236-275` before this\r\n * extraction; the pre-extraction copy is `scratchpad/install-page-routes.ts.orig`).\r\n * The behaviour is unchanged, byte for byte — what changes is that it is now\r\n * a named, exported, independently constructible function instead of a closure\r\n * over eight ambient bindings of `installPageRoutes`.\r\n *\r\n * WHY IT TAKES `loadModule` AND NOT A `ViteDevServer`: loading a module is the\r\n * only capability the handler ever needed, and the two runtimes answer it\r\n * differently — dev goes through Vite's SSR graph\r\n * (`vite.ssrLoadModule`, `install-page-routes.ts:207`), production reads the\r\n * already-built page manifest (`page-manifest.ts`). Taking \"how to load a\r\n * module\" as an INPUT is what lets the same handler serve both, and what lets\r\n * a test construct it with a plain async function — no Vite, no dev server, no\r\n * `app/` directory on disk.\r\n *\r\n * Scope: this file creates a seam and nothing else. It does not implement\r\n * `type: \"page\"` routing, HTML error pages, or any other new capability.\r\n */\r\nimport { Response, type HttpContext } from \"@warlock.js/core\";\r\n\r\nimport {\r\n DATA_RESPONSE_CONTENT_TYPE,\r\n isDataRequest,\r\n WARLOCK_DATA_REQUEST_HEADER,\r\n} from \"../routing/data-request\";\r\nimport {\r\n registerModules,\r\n type RegisterableModuleNamespace,\r\n} from \"../runtime/register-modules\";\r\nimport { buildHydrationPayload } from \"./build-hydration-payload\";\r\nimport type { BufferedCookie, PageRouteEntry, PageTripleModule } from \"./execute-page-request\";\r\nimport { isNonHydrating } from \"./page-render-bundle\";\r\nimport { renderPageFailure, renderPageRequest, type RenderedPage } from \"./render-page\";\r\nimport type { ErrorPageModuleLoader } from \"./error-page\";\r\n\r\n/**\r\n * Replay ONE committed cookie through core's own `Response.cookie()` — the\r\n * same serializer every ordinary controller's cookie goes through, so there\r\n * is nothing here for a second implementation to drift from. The one-liner\r\n * `dev-server.ts` wires as the production default; passed in (`applyBufferedCookie`\r\n * option, below) rather than imported so this file stays free of anything\r\n * Vite-shaped.\r\n */\r\nfunction defaultApplyBufferedCookie(response: Response, cookie: BufferedCookie): void {\r\n response.cookie(cookie.name, cookie.value as never, cookie.options ?? {});\r\n}\r\n\r\n/**\r\n * Stage 10a — apply the stage 7 commit (headers, then cookies) to the LIVE\r\n * response, once, before either terminal write (10b: `html()` or `send()`).\r\n * Both the document and data representations of a page route go through this\r\n * so a client navigation never drops a `Set-Cookie` a full load would have\r\n * kept (`create-page-route-handler.spec.ts` — \"applies committed cookies and\r\n * headers exactly as the document path does\").\r\n */\r\nfunction applyCommit(\r\n response: Response,\r\n rendered: Pick<RenderedPage, \"headers\" | \"cookies\">,\r\n applyBufferedCookie: (response: Response, cookie: BufferedCookie) => void,\r\n): void {\r\n response.headers(rendered.headers ?? {});\r\n\r\n for (const cookie of rendered.cookies ?? []) {\r\n applyBufferedCookie(response, cookie);\r\n }\r\n}\r\n\r\n/**\r\n * How the handler obtains a page/layout/app module, by the same id\r\n * (`appFile`/`layoutFile`/`pageFile`) the caller registered it under. In dev\r\n * this is `moduleId => vite.ssrLoadModule(moduleId)`; the connector already\r\n * owns the dev/prod split, so the handler never learns which one it got.\r\n */\r\nexport type PageModuleLoader = (moduleId: string) => Promise<unknown>;\r\n\r\nexport type PageRouteHandlerOptions = {\r\n /** The composed, registered route path — `composeRoutePath`'s output. */\r\n path: string;\r\n /** The resolved route name; shared namespace with API routes. */\r\n name: string;\r\n /** The single global app-root file, e.g. `<appSrcRoot>/web/root.tsx`. */\r\n appFile: string;\r\n /** The page module's id. */\r\n pageFile: string;\r\n /** The page's own-directory `layout.tsx`, when it has one. */\r\n layoutFile?: string | undefined;\r\n loadModule: PageModuleLoader;\r\n /** Optional lazy application `error.page.tsx` loader. Never called on success. */\r\n loadErrorPage?: ErrorPageModuleLoader;\r\n /**\r\n * Load the REAL layout module namespaces, outermost first, for universal\r\n * registration. This stays separate from `loadModule(layoutFile)` because\r\n * dev may answer that id with a synthetic wrapper whose middleware is the\r\n * composition of several layouts. That wrapper is a render-pipeline detail,\r\n * not a module identity, and must never enter `registerModules`' WeakSet.\r\n */\r\n loadRegistrationLayouts?: () => Promise<readonly RegisterableModuleNamespace[]>;\r\n /** Browser module appended after the server-rendered document. */\r\n hydrationClientModuleUrl?: string;\r\n /**\r\n * Stylesheet URLs for this page, emitted into `<head>` so the FIRST paint is\r\n * styled. Absent or empty means the application has no CSS — it never means\r\n * a stylesheet failed to resolve, which is the build's job to report.\r\n */\r\n stylesheetUrls?: readonly string[];\r\n /** Same helper `dev-server.ts` exports — passed in, never imported. */\r\n /**\r\n * The pattern stage 1 matches `request.path` against, when it differs from\r\n * the REGISTERED path. Defaults to `path`, which is right for every route\r\n * whose URL is its own.\r\n *\r\n * Exactly one route needs it: the not-found page, registered on the catch-all\r\n * `*`. `matchRoute` compares segment by segment (`./match-page-route.ts`) and\r\n * has no wildcard token, so a route registered as `*` matches NOTHING — the\r\n * pipeline reports no match and `renderPageRequest` answers `{ html: \"\",\r\n * status: 404 }`. Correct status, empty document: a 404 page that never\r\n * renders its own body. Handing it `requestPath => requestPath` makes the\r\n * requested URL the route's pattern for that one request, so the match is\r\n * trivially true and the page renders for the URL the visitor actually asked\r\n * for.\r\n */\r\n matchPath?: (requestPath: string) => string;\r\n /**\r\n * The status this route answers with when the pipeline settles on a plain\r\n * `200` — the not-found route's `404`, and nothing else uses it.\r\n *\r\n * Applied ONLY to `200`, never as a blanket override: a `200` from this\r\n * pipeline means \"the document rendered and nobody objected\", which for this\r\n * route is precisely the not-found case. Any other settled status is a real\r\n * outcome that the page or the boundary decided — a 500 from a failed render,\r\n * a redirect — and overwriting it would report a broken page as a missing one.\r\n */\r\n statusForRenderedOk?: number;\n /**\n * Exclude the page module's loader from the request triple while preserving\n * the real namespace for `register()` and rendering. Used only by the\n * catch-all 404 page: a missing URL must not run application data work or\n * turn a simple miss into a second failure path.\n */\n skipPageLoader?: boolean;\n /**\r\n * Replays one committed cookie through core's `Response.cookie()`. Defaults\r\n * to doing exactly that (`defaultApplyBufferedCookie`, above); injectable so\r\n * a caller with a different `Response` shape (or a test) can observe/replace\r\n * the call.\r\n */\r\n applyBufferedCookie?: (response: Response, cookie: BufferedCookie) => void;\r\n};\r\n\r\nexport type PageRouteHandler = (context: HttpContext) => Promise<void | Response>;\r\n\r\nfunction escapeHtmlAttribute(value: string): string {\r\n return value.replace(/[&<>\"']/g, (character) => {\r\n switch (character) {\r\n case \"&\":\r\n return \"&amp;\";\r\n case \"<\":\r\n return \"&lt;\";\r\n case \">\":\r\n return \"&gt;\";\r\n case '\"':\r\n return \"&quot;\";\r\n default:\r\n return \"&#39;\";\r\n }\r\n });\r\n}\r\n\r\nfunction installHydrationClientModule(\r\n html: string,\r\n moduleUrl: string | undefined,\r\n nonce: string | undefined,\r\n): string {\r\n if (moduleUrl === undefined || html === \"\") return html;\r\n\r\n const closingBodyIndex = html.lastIndexOf(\"</body>\");\r\n if (closingBodyIndex === -1) {\r\n throw new Error(\r\n \"installPageRoutes: cannot install the hydration client module because the rendered document has no closing </body> tag.\",\r\n );\r\n }\r\n\r\n const nonceAttribute = nonce === undefined ? \"\" : ` nonce=\"${escapeHtmlAttribute(nonce)}\"`;\r\n const script = `<script type=\"module\"${nonceAttribute} src=\"${escapeHtmlAttribute(moduleUrl)}\"></script>`;\r\n return `${html.slice(0, closingBodyIndex)}${script}${html.slice(closingBodyIndex)}`;\r\n}\r\n\r\n/**\r\n * Put the page's stylesheets in `<head>`, so the first paint is styled.\r\n *\r\n * Without this the document carries no CSS at all. The stylesheet reaches the\r\n * browser only because the CLIENT bundle imports it, which means it is applied\r\n * by JavaScript after the module graph loads — the page renders unstyled first\r\n * and restyles a moment later. Correct markup, wrong-looking page, and nothing\r\n * in the console to explain it.\r\n *\r\n * A `<link>` in `<head>` is render-blocking, which is exactly what is wanted\r\n * here: the browser holds the first paint until the CSS is in, so there is no\r\n * flash rather than a faster ugly one.\r\n *\r\n * Inserted before `</head>` rather than after `<head>` so an application's own\r\n * `<link>`/`<style>` in the root document still comes FIRST and can be\r\n * overridden by these — matching how the framework's tags are documented to\r\n * behave, and keeping cascade order predictable.\r\n */\r\nfunction installStylesheets(html: string, stylesheetUrls: readonly string[]): string {\r\n if (stylesheetUrls.length === 0 || html === \"\") return html;\r\n\r\n const closingHeadIndex = html.lastIndexOf(\"</head>\");\r\n\r\n // No `<head>` is not an error the way a missing `</body>` is: a root that\r\n // renders no head is unusual but legal, and losing the stylesheet is a\r\n // cosmetic failure where losing hydration is a broken page. Silently\r\n // dropping it would be the wrong trade the other way, though — so the\r\n // document is left exactly as rendered and the caller's own missing-`</body>`\r\n // check remains the loud one.\r\n if (closingHeadIndex === -1) return html;\r\n\r\n const links = stylesheetUrls\r\n .map((url) => `<link rel=\"stylesheet\" href=\"${escapeHtmlAttribute(url)}\">`)\r\n .join(\"\");\r\n\r\n return `${html.slice(0, closingHeadIndex)}${links}${html.slice(closingHeadIndex)}`;\r\n}\r\n\r\n/**\r\n * Build the handler for ONE page route. Per request it loads the App + layout\r\n * + page triple (concurrently, in that order), renders the URL through\r\n * `renderPageRequest`, splices in the hydration module, and flushes the\r\n * document.\r\n *\r\n * No try/catch, deliberately: loader/render throws are already absorbed by the\r\n * pipeline's boundary machinery inside `renderPageRequest`, and anything that\r\n * escapes (a module-load or register failure, the missing-`</body>` throw\r\n * above) belongs to the router's error path — which is exactly where it went\r\n * before.\r\n */\r\nexport function createPageRouteHandler(options: PageRouteHandlerOptions): PageRouteHandler {\r\n const {\r\n path,\r\n name,\r\n appFile,\r\n pageFile,\r\n layoutFile,\r\n loadModule,\r\n loadErrorPage,\r\n loadRegistrationLayouts,\r\n hydrationClientModuleUrl,\r\n stylesheetUrls,\r\n matchPath,\n statusForRenderedOk,\n skipPageLoader = false,\n applyBufferedCookie = defaultApplyBufferedCookie,\n } = options;\n\r\n return async ({ request, response }: HttpContext) => {\r\n const wantsData = isDataRequest(request.header(WARLOCK_DATA_REQUEST_HEADER, undefined));\r\n\r\n try {\r\n const [appModule, layoutModule, ownPageModule, registrationLayouts] = await Promise.all([\r\n loadModule(appFile),\r\n layoutFile ? loadModule(layoutFile) : Promise.resolve({}),\r\n loadModule(pageFile),\r\n loadRegistrationLayouts?.() ?? Promise.resolve([]),\r\n ]);\r\n\r\n // Registration is the first lifecycle action after all module namespaces\r\n // have loaded and before `renderPageRequest` can run middleware, loaders or\r\n // render. App/page are already their real namespaces. Layouts deliberately\r\n // come from the separate raw chain above, never from `layoutModule`, which\r\n // may be the synthetic composed middleware wrapper used by dev.\r\n registerModules([\r\n appModule as RegisterableModuleNamespace,\r\n ...registrationLayouts,\r\n ownPageModule as RegisterableModuleNamespace,\r\n ]);\r\n\r\n const pageModule = ownPageModule as PageTripleModule;\n const triple: PageRouteEntry[\"triple\"] = {\n app: appModule as PageTripleModule,\n layout: layoutModule as PageTripleModule,\n // Registration above deliberately receives the REAL namespace. Only the\n // pipeline view is projected: spreading preserves the component,\n // metadata, middleware and boundary exports while making a custom 404's\n // loader uncallable.\n page: skipPageLoader\n ? {\n ...pageModule,\n // Vite and native ESM loaders hand us module namespace objects,\n // whose export descriptors are not an object-spread contract.\n // Keep the rendering export explicitly while hiding only loader.\n default: pageModule.default,\n loader: undefined,\n }\n : pageModule,\n };\n\r\n const requestUrl = request.path;\n const [requestPathname] = requestUrl.split(\"?\");\n const routes: PageRouteEntry[] = [\n { path: matchPath === undefined ? path : matchPath(requestPathname), name, triple },\n ];\n\r\n // A DATA request runs everything above and below this line identically —\r\n // it is the same route, the same match and the same pipeline — and differs\r\n // only in what gets written at the end. Decided here, before the render, so\r\n // the branch is visibly about REPRESENTATION and not about behaviour.\r\n const rendered = await renderPageRequest(requestUrl, {\n routes,\r\n createHttp: () => ({ request, response }),\r\n loadErrorPage,\r\n });\r\n\r\n if (rendered instanceof Response) return rendered;\r\n\r\n // See `statusForRenderedOk`: a settled 200 is the only status this route is\r\n // allowed to restate, and both the document and the data branch below must\r\n // restate it the same way — a client navigation that received 200 with a\r\n // not-found payload would push the URL into history as a real page.\r\n const status =\r\n rendered.status === 200 && statusForRenderedOk !== undefined\r\n ? statusForRenderedOk\r\n : rendered.status;\r\n\r\n // Stage 10a: the stage 7 commit (headers, then cookies), applied ONCE,\r\n // identically for the document and the data representation — see\r\n // `applyCommit`.\r\n applyCommit(response, rendered, applyBufferedCookie);\r\n\r\n if (wantsData) {\r\n // So a shared cache can never serve a document to a client that asked for\r\n // JSON, or the reverse. See `data-request.ts` on why this stays even\r\n // while page responses are `no-store`.\r\n response.header(\"Vary\", WARLOCK_DATA_REQUEST_HEADER);\r\n\r\n // `bundle` is absent on exactly one path: nothing matched, so no pipeline\r\n // ran and there is no payload to build. Fastify already matched this\r\n // route to get here, so reaching it means `request.path` did not satisfy\r\n // the entry's own pattern — answered as the 404 it is, rather than\r\n // synthesising an empty payload the client would try to render as a page.\r\n if (rendered.bundle === undefined) {\r\n response.setContentType(DATA_RESPONSE_CONTENT_TYPE);\r\n await response.send(JSON.stringify({ error: \"not_found\" }), status);\r\n\r\n return;\r\n }\r\n\r\n // SERIALIZED HERE, and handed over as a STRING on purpose.\r\n //\r\n // `response.send(object)` runs the body through core's `Response.parse`,\r\n // which recurses the object, calls `toJSON()` on anything that has one\r\n // (assigning `request` onto it as it goes) and rebuilds arrays. That is\r\n // the right behaviour for a controller returning Resources; it is the\r\n // wrong behaviour here, because the DOCUMENT path serializes this exact\r\n // object with a plain `JSON.stringify` into `#__WARLOCK_DATA__`. Routing\r\n // one path through a transformer and not the other is precisely the\r\n // drift `build-hydration-payload.ts` exists to prevent — the browser\r\n // would build one tree on a page load and a different one on a\r\n // navigation to the same URL.\r\n //\r\n // A string body also bypasses `parseBody()` entirely, so the content type\r\n // has to be declared rather than inferred from an object body.\r\n response.setContentType(DATA_RESPONSE_CONTENT_TYPE);\r\n await response.send(JSON.stringify(buildHydrationPayload(rendered.bundle)), status);\r\n\r\n return;\r\n }\r\n\r\n // Stylesheets first: they go in `<head>`, the hydration module goes before\r\n // `</body>`, and doing the head work on the already-rendered string keeps\r\n // both splices in one place rather than threading CSS through the React\r\n // render just to reach the same bytes.\r\n const styled = installStylesheets(rendered.html, stylesheetUrls ?? []);\r\n\r\n const html = installHydrationClientModule(\r\n styled,\r\n hydrationClientModuleUrl,\r\n hydrationClientModuleUrl === undefined ? undefined : request.nonce,\r\n );\r\n\r\n await response.html(html, status);\r\n } catch (thrown) {\r\n // This is outside the page pipeline: loading/registering a module can\r\n // fail before a triple exists for its authored boundaries to handle.\r\n // Reuse this request/response pair so headers, nonce and response\r\n // ownership remain exactly the same as the ordinary path.\r\n //\r\n // Nested try/catch, deliberately: this block's own job is to render a\r\n // NICER answer for `thrown` — it must never let a failure IN THAT\r\n // ATTEMPT (`renderPageFailure` itself throwing, or misbehaving) replace\r\n // `thrown` with a less useful error. If rendering the failure page\r\n // fails too, the original throw escapes exactly as it would have with\r\n // no try/catch at all (the file header's stated contract) — the\r\n // router's own error path is still the answer, just one throw later.\r\n try {\r\n const rendered = await renderPageFailure({\r\n name,\r\n path: request.path,\r\n request,\r\n response,\r\n thrown,\r\n loadErrorPage,\r\n });\r\n\r\n applyCommit(response, rendered, applyBufferedCookie);\r\n\r\n if (wantsData) {\r\n response.header(\"Vary\", WARLOCK_DATA_REQUEST_HEADER);\r\n response.setContentType(DATA_RESPONSE_CONTENT_TYPE);\r\n await response.send(JSON.stringify(buildHydrationPayload(rendered.bundle!)), 500);\r\n return;\r\n }\r\n\r\n const styled = installStylesheets(rendered.html, stylesheetUrls ?? []);\r\n\r\n // `renderPageFailure` marks its bundle non-hydrating (page-render-bundle.ts):\r\n // there is no triple, so there is nothing on the client the hydration\r\n // module could attach to. Injecting it anyway would ship a script that\r\n // hydrates against a composition the server never trusted.\r\n const html = isNonHydrating(rendered.bundle)\r\n ? styled\r\n : installHydrationClientModule(\r\n styled,\r\n hydrationClientModuleUrl,\r\n hydrationClientModuleUrl === undefined ? undefined : request.nonce,\r\n );\r\n await response.html(html,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AAU,EAAE,OAAO,YAAY,CAAC,GAAG,MAAM;KAElE;IACF;IAiBA,SAAS,eAAe,0BAA0B;IAClD,MAAM,SAAS,KAAK,KAAK,UAAU,sBAAsB,SAAS,MAAM,CAAC,GAAG,MAAM;IAElF;GACF;GAQA,MAAM,OAAO,6BAFE,mBAAmB,SAAS,MAAM,kBAAkB,CAAC,CAG7D,GACL,0BACA,6BAA6B,SAAY,SAAY,QAAQ,KAC/D;GAEA,MAAM,SAAS,KAAK,MAAM,MAAM;EAChC,SAAS,QAAQ;GAaf,IAAI;IACJ,MAAM,WAAW,MAAM,kBAAkB;KACvC;KACA,MAAM,QAAQ;KACd;KACA;KACA;KACA;IACF,CAAC;IAED,YAAY,UAAU,UAAU,mBAAmB;IAEnD,IAAI,WAAW;KACb,SAAS,OAAO,QAAQ,2BAA2B;KACnD,SAAS,eAAe,0BAA0B;KAClD,MAAM,SAAS,KAAK,KAAK,UAAU,sBAAsB,SAAS,MAAO,CAAC,GAAG,GAAG;KAChF;IACF;IAEA,MAAM,SAAS,mBAAmB,SAAS,MAAM,kBAAkB,CAAC,CAAC;IAMrE,MAAM,OAAO,eAAe,SAAS,MAAM,IACvC,SACA,6BACE,QACA,0BACA,6BAA6B,SAAY,SAAY,QAAQ,KAC/D;IACJ,MAAM,SAAS,KAAK,MAAM,GAAG;GAC7B,QAAQ;IACN,MAAM;GACR;EACF;CACF;AACF"}
@@ -1,17 +1,6 @@
1
1
  import { stripVTControlCharacters } from "node:util";
2
2
 
3
- //#region ../web/src/server/dev-server.ts
4
- /**
5
- * Replay a buffered cookie onto the response that will actually be sent.
6
- *
7
- * `BufferedCookie.options` is a loosely-typed bag (`Record<string, unknown>`)
8
- * because the buffer is written by loader code before any response exists; the
9
- * cast hands it to `Response.cookie()`, which is where the option shape is
10
- * defined and enforced for every other caller in the framework.
11
- */
12
- function applyBufferedCookie(response, cookie) {
13
- response.cookie(cookie.name, cookie.value, cookie.options ?? {});
14
- }
3
+ //#region web/src/server/dev-server.ts
15
4
  /**
16
5
  * Where a captured transform/resolve failure rides from Vite's connect stack to
17
6
  * the Fastify hook that mounted it.
@@ -163,5 +152,5 @@ function sendCapturedDevError(request, response) {
163
152
  }
164
153
 
165
154
  //#endregion
166
- export { applyBufferedCookie, devErrorTransportPlugin, sendCapturedDevError };
155
+ export { devErrorTransportPlugin, sendCapturedDevError };
167
156
  //# sourceMappingURL=dev-server.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"dev-server.mjs","names":[],"sources":["../../../../../../../web/src/server/dev-server.ts"],"sourcesContent":["/**\n * Two small pieces of the dev/SSR page plumbing that `./web-connector.ts` wires\n * but deliberately does not own: the buffered-cookie commit, and the DEV-ONLY\n * error transport that stops a refused module from reaching the browser as a\n * bare 404 (see {@link devErrorTransportPlugin}).\n *\n * ---\n *\n * Commits one buffered cookie (`BufferedCookie`, from `./buffered-response.ts`)\n * onto the live Warlock `Response` — the single place in the SSR page pipeline\n * where a cookie the loader buffered turns into a real `Set-Cookie` header.\n *\n * It delegates to core's `Response.cookie()` rather than talking to fastify.\n * That method already owns everything this file used to reimplement: it takes\n * core's own `CookieOptions`, JSON-stringifies the value unless `{ raw: true }`,\n * strips the core-only `raw` flag, and layers the framework's secure-cookie\n * defaults and the `http.cookies.options` config under the per-call options.\n * Going through it means the SSR page path and every ordinary controller emit\n * cookies by the exact same code, so the two cannot drift apart.\n *\n * The helper is passed INTO `installPageRoutes`/`createPageRouteHandler` as an\n * option rather than imported by them, which is what keeps this module out of a\n * cycle with the page-route installer.\n */\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport type { Connect, Plugin } from \"vite\";\nimport type { Response } from \"@warlock.js/core\";\nimport type { BufferedCookie } from \"./buffered-response\";\n\n/**\n * Replay a buffered cookie onto the response that will actually be sent.\n *\n * `BufferedCookie.options` is a loosely-typed bag (`Record<string, unknown>`)\n * because the buffer is written by loader code before any response exists; the\n * cast hands it to `Response.cookie()`, which is where the option shape is\n * defined and enforced for every other caller in the framework.\n */\nexport function applyBufferedCookie(response: Response, cookie: BufferedCookie): void {\n response.cookie(cookie.name, cookie.value as never, (cookie.options ?? {}) as never);\n}\n\n/**\n * Where a captured transform/resolve failure rides from Vite's connect stack to\n * the Fastify hook that mounted it.\n *\n * A `Symbol.for` key on the raw `IncomingMessage` rather than a `WeakMap`\n * because the two halves live in different modules and are wired at different\n * times; the request object is the only thing they provably share, and the\n * symbol cannot collide with a Vite/Fastify/user property.\n *\n * Exported so a test can stage a captured failure without booting a vite\n * server, and so the two halves cannot drift onto two different keys.\n */\nexport const DEV_TRANSFORM_ERROR_BODY = Symbol.for(\"warlock.web.devTransformErrorBody\");\n\ntype DevTransformErrorCarrier = { [DEV_TRANSFORM_ERROR_BODY]?: string };\n\n/**\n * The status a refused module now answers with.\n *\n * NOT the 404 this replaces. That 404 was never a decision about the module —\n * it is what an unmatched URL gets once vite has declined it, and which of the\n * two framework answers you see depends only on whether the app declares a\n * catch-all page: with one (v5/app does — `path: \"*\"`) the request lands in the\n * page pipeline, matches no route, and `./render-page.ts:604` returns\n * `{ html: \"\", status: 404 }` for `./create-page-route-handler.ts:147` to write\n * as an empty `text/html` body; without one it is `core/src/router/router.ts:879`.\n * Either way \"the module does not exist\" is precisely the wrong thing to tell a\n * developer whose module exists and was refused. 500 is the status VITE ITSELF writes for\n * this exact condition when it is not in middleware mode\n * (`node_modules/vite/dist/node/chunks/config.js:9528`), so this adopts that\n * convention rather than inventing a third one.\n */\nexport const DEV_TRANSFORM_ERROR_STATUS = 500;\n\n/**\n * `buildErrorMessage` as vite exports it. Declared structurally so this module\n * needs no value import of vite — vite is an optional, dev-only peer and a\n * production install does not carry it.\n */\nexport type BuildErrorMessage = (\n error: Error,\n args?: string[],\n includeStack?: boolean,\n) => string;\n\n/**\n * The dev error transport was constructed while the process is hosting a\n * PRODUCTION build. Refused by name at construction rather than degraded,\n * because everything this transport does — file paths, source frames, plugin\n * names — is exactly what a production response must never carry.\n */\nexport class DevErrorTransportInProductionError extends Error {\n public constructor() {\n super(\n \"The dev error transport was constructed with `Application.runtimeStrategy === \" +\n '\"production\"`. It exists only to put a Vite transform failure in front of a ' +\n \"developer and its response body carries absolute file paths and source frames, \" +\n \"so it must never be mounted on a production-hosted server.\",\n );\n this.name = \"DevErrorTransportInProductionError\";\n }\n}\n\n/**\n * Render a refused module's failure as the plain-text body the browser gets.\n *\n * Formatting is DELEGATED to vite's own exported `buildErrorMessage`, not\n * reimplemented: it is the same function vite uses to print the failure to the\n * terminal, so the text a developer reads in the network panel and the text\n * they read in the terminal cannot drift. Two things are added around it —\n * `error.name`, which vite's terminal path replaces with a fixed\n * \"Internal server error:\" prefix and which is the single most useful token for\n * a named gate refusal (`ProjectionAmbiguityError`), and the `cause` chain,\n * which vite does not walk.\n *\n * `stripVTControlCharacters` is not optional: `buildErrorMessage` colours its\n * output with picocolors, which is ON whenever the dev server owns a TTY, and\n * raw ANSI escapes in an HTTP body are noise. Vite strips them the same way for\n * the overlay payload (`config.js:9490-9497`).\n *\n * The stack is deliberately omitted (`includeStack: false`). A gate refusal's\n * stack points into the gate, not into the developer's code; the fields that\n * locate the problem — plugin, file, line, source frame — are what\n * `buildErrorMessage` puts there without it.\n */\nexport function formatDevTransformError(\n error: unknown,\n buildErrorMessage: BuildErrorMessage,\n): string {\n const failure =\n error instanceof Error ? error : new Error(typeof error === \"string\" ? error : String(error));\n\n const lines = [\n stripVTControlCharacters(\n buildErrorMessage(failure, [`${failure.name}: ${failure.message}`], false),\n ),\n ];\n\n // Walk the `cause` chain. A gate may wrap a parser failure, and the wrapped\n // message is usually the one naming the actual syntax that was refused.\n let cause = (failure as { cause?: unknown }).cause;\n\n while (cause instanceof Error) {\n lines.push(` Caused by: ${cause.name}: ${stripVTControlCharacters(cause.message)}`);\n cause = (cause as { cause?: unknown }).cause;\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\n/**\n * DEV-ONLY. Capture the transform/resolve failure that vite is about to throw\n * away, so the request that caused it can answer with it.\n *\n * WHY THIS IS A PLUGIN AND NOT A `middlewares.use(...)` CALL — this is the\n * whole defect, and it is an ordering fact, not a style choice:\n *\n * - Vite mounts its own error handler LAST, built as\n * `errorMiddleware(server, !!middlewareMode)`\n * (`node_modules/vite/dist/node/chunks/config.js:25705`).\n * - In middleware mode that `allowNext` flag is `true`, and the handler then\n * logs the error to the TERMINAL and calls `next()` — with no error\n * (`config.js:9525-9527`).\n * - connect only routes an error to a 4-arity handler while an error is in\n * flight (`config.js:10611-10626`), so `next()` clears it: every layer after\n * that point, INCLUDING the `done` callback `./web-connector.ts` hands the\n * stack, is called as if the request had simply gone unhandled. The\n * framework then answers the only way it can for a URL it does not know — a\n * 404, empty (see {@link DEV_TRANSFORM_ERROR_STATUS} for which of the two\n * produces it).\n * - Anything registered with `vite.middlewares.use(...)` after `createServer()`\n * resolves lands AFTER that handler and is therefore unreachable. A\n * `configureServer` POST hook does not: vite runs post hooks at\n * `config.js:25700`, five lines BEFORE it mounts its error handler.\n *\n * So this sits between the failure and vite's logger. It captures, then calls\n * `next(error)` and lets vite's own handler run exactly as before — the\n * terminal message and the `hot.send({ type: \"error\" })` overlay push\n * (`config.js:9511-9521`) are unchanged. This transport ADDS a reader; it\n * replaces nothing.\n *\n * @param isProductionRuntime the connector's own hosting-mode signal\n * (`./web-connector.ts:122`) — passed in rather than re-derived so there\n * is one definition of \"this process is Vite-hosted\", not two.\n */\nexport function devErrorTransportPlugin(options: {\n isProductionRuntime: () => boolean;\n buildErrorMessage: BuildErrorMessage;\n}): Plugin {\n const { isProductionRuntime, buildErrorMessage } = options;\n\n if (isProductionRuntime()) {\n throw new DevErrorTransportInProductionError();\n }\n\n const capture: Connect.ErrorHandleFunction = (error, request, _response, next) => {\n // Re-asserted per request, not just at construction: `runtimeStrategy` is\n // process state and a transport that leaks source frames is not something\n // to hold open on a boot-time reading alone. In production this layer is a\n // pass-through and vite's handler behaves exactly as it does today.\n if (isProductionRuntime()) return next(error);\n\n (request as DevTransformErrorCarrier)[DEV_TRANSFORM_ERROR_BODY] = formatDevTransformError(\n error,\n buildErrorMessage,\n );\n\n next(error);\n };\n\n return {\n name: \"warlock:dev-error-transport\",\n // Belt to the `isProductionRuntime` braces: this plugin has no business in\n // a `vite build` graph either.\n apply: \"serve\",\n configureServer(server) {\n // RETURNING a function is what makes this a POST hook — the ordering the\n // note above depends on. Mounting inline here would land the layer BEFORE\n // vite's transform middleware, where no error has been thrown yet.\n return () => {\n server.middlewares.use(capture);\n };\n },\n };\n}\n\n/**\n * Answer the request with the failure {@link devErrorTransportPlugin} captured,\n * if there was one. Returns `false` when there was not, which is the normal\n * case and means \"carry on down the framework's own path\".\n *\n * Called from the Fastify `onRequest` hook that mounts vite\n * (`./web-connector.ts:321`), in the `done` callback — i.e. at the one moment\n * where connect has finished, vite has declined to answer, and the framework is\n * about to 404. Writing to the raw `ServerResponse` rather than through Fastify\n * is what the mount already does for every response vite serves, so this stays\n * on the same side of the seam.\n */\nexport function sendCapturedDevError(request: IncomingMessage, response: ServerResponse): boolean {\n const body = (request as DevTransformErrorCarrier)[DEV_TRANSFORM_ERROR_BODY];\n\n if (typeof body !== \"string\") return false;\n\n // A middleware further down may have answered already (vite serves plenty of\n // requests itself). Never write twice; the captured body is then just dropped.\n if (response.headersSent || response.writableEnded) return false;\n\n response.statusCode = DEV_TRANSFORM_ERROR_STATUS;\n response.setHeader(\"content-type\", \"text/plain; charset=utf-8\");\n // A refusal is a fact about the CURRENT source. Caching it would survive the\n // edit that fixes it.\n response.setHeader(\"cache-control\", \"no-store\");\n response.end(body);\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;AAsCA,SAAgB,oBAAoB,UAAoB,QAA8B;CACpF,SAAS,OAAO,OAAO,MAAM,OAAO,OAAiB,OAAO,WAAW,CAAC,CAAW;AACrF;;;;;;;;;;;;;AAcA,MAAa,2BAA2B,OAAO,IAAI,mCAAmC;;;;;;;;;;;;;;;;;AAoBtF,MAAa,6BAA6B;;;;;;;AAmB1C,IA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C,SAAS,IAAI,IAAI;CAEjB,OAAO;AACT"}
1
+ {"version":3,"file":"dev-server.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/dev-server.ts"],"sourcesContent":["/** Development-only transport for Vite transform failures. */\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { stripVTControlCharacters } from \"node:util\";\nimport type { Connect, Plugin } from \"vite\";\n\n/**\n * Where a captured transform/resolve failure rides from Vite's connect stack to\n * the Fastify hook that mounted it.\n *\n * A `Symbol.for` key on the raw `IncomingMessage` rather than a `WeakMap`\n * because the two halves live in different modules and are wired at different\n * times; the request object is the only thing they provably share, and the\n * symbol cannot collide with a Vite/Fastify/user property.\n *\n * Exported so a test can stage a captured failure without booting a vite\n * server, and so the two halves cannot drift onto two different keys.\n */\nexport const DEV_TRANSFORM_ERROR_BODY = Symbol.for(\"warlock.web.devTransformErrorBody\");\n\n/**\n * Re-exported so a dev-only caller can reach the cookie commit seam through\n * this module without a second import path into `./buffered-response`, which\n * is where the implementation actually lives.\n */\nexport { applyBufferedCookie, type BufferedCookie } from \"./buffered-response\";\n\ntype DevTransformErrorCarrier = { [DEV_TRANSFORM_ERROR_BODY]?: string };\n\n/**\n * The status a refused module now answers with.\n *\n * NOT the 404 this replaces. That 404 was never a decision about the module —\n * it is what an unmatched URL gets once vite has declined it, and which of the\n * two framework answers you see depends only on whether the app declares a\n * catch-all page: with one (v5/app does — `path: \"*\"`) the request lands in the\n * page pipeline, matches no route, and `./render-page.ts:604` returns\n * `{ html: \"\", status: 404 }` for `./create-page-route-handler.ts:147` to write\n * as an empty `text/html` body; without one it is `core/src/router/router.ts:879`.\n * Either way \"the module does not exist\" is precisely the wrong thing to tell a\n * developer whose module exists and was refused. 500 is the status VITE ITSELF writes for\n * this exact condition when it is not in middleware mode\n * (`node_modules/vite/dist/node/chunks/config.js:9528`), so this adopts that\n * convention rather than inventing a third one.\n */\nexport const DEV_TRANSFORM_ERROR_STATUS = 500;\n\n/**\n * `buildErrorMessage` as vite exports it. Declared structurally so this module\n * needs no value import of vite — vite is an optional, dev-only peer and a\n * production install does not carry it.\n */\nexport type BuildErrorMessage = (\n error: Error,\n args?: string[],\n includeStack?: boolean,\n) => string;\n\n/**\n * The dev error transport was constructed while the process is hosting a\n * PRODUCTION build. Refused by name at construction rather than degraded,\n * because everything this transport does — file paths, source frames, plugin\n * names — is exactly what a production response must never carry.\n */\nexport class DevErrorTransportInProductionError extends Error {\n public constructor() {\n super(\n \"The dev error transport was constructed with `Application.runtimeStrategy === \" +\n '\"production\"`. It exists only to put a Vite transform failure in front of a ' +\n \"developer and its response body carries absolute file paths and source frames, \" +\n \"so it must never be mounted on a production-hosted server.\",\n );\n this.name = \"DevErrorTransportInProductionError\";\n }\n}\n\n/**\n * Render a refused module's failure as the plain-text body the browser gets.\n *\n * Formatting is DELEGATED to vite's own exported `buildErrorMessage`, not\n * reimplemented: it is the same function vite uses to print the failure to the\n * terminal, so the text a developer reads in the network panel and the text\n * they read in the terminal cannot drift. Two things are added around it —\n * `error.name`, which vite's terminal path replaces with a fixed\n * \"Internal server error:\" prefix and which is the single most useful token for\n * a named gate refusal (`ProjectionAmbiguityError`), and the `cause` chain,\n * which vite does not walk.\n *\n * `stripVTControlCharacters` is not optional: `buildErrorMessage` colours its\n * output with picocolors, which is ON whenever the dev server owns a TTY, and\n * raw ANSI escapes in an HTTP body are noise. Vite strips them the same way for\n * the overlay payload (`config.js:9490-9497`).\n *\n * The stack is deliberately omitted (`includeStack: false`). A gate refusal's\n * stack points into the gate, not into the developer's code; the fields that\n * locate the problem — plugin, file, line, source frame — are what\n * `buildErrorMessage` puts there without it.\n */\nexport function formatDevTransformError(\n error: unknown,\n buildErrorMessage: BuildErrorMessage,\n): string {\n const failure =\n error instanceof Error ? error : new Error(typeof error === \"string\" ? error : String(error));\n\n const lines = [\n stripVTControlCharacters(\n buildErrorMessage(failure, [`${failure.name}: ${failure.message}`], false),\n ),\n ];\n\n // Walk the `cause` chain. A gate may wrap a parser failure, and the wrapped\n // message is usually the one naming the actual syntax that was refused.\n let cause = (failure as { cause?: unknown }).cause;\n\n while (cause instanceof Error) {\n lines.push(` Caused by: ${cause.name}: ${stripVTControlCharacters(cause.message)}`);\n cause = (cause as { cause?: unknown }).cause;\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n\n/**\n * DEV-ONLY. Capture the transform/resolve failure that vite is about to throw\n * away, so the request that caused it can answer with it.\n *\n * WHY THIS IS A PLUGIN AND NOT A `middlewares.use(...)` CALL — this is the\n * whole defect, and it is an ordering fact, not a style choice:\n *\n * - Vite mounts its own error handler LAST, built as\n * `errorMiddleware(server, !!middlewareMode)`\n * (`node_modules/vite/dist/node/chunks/config.js:25705`).\n * - In middleware mode that `allowNext` flag is `true`, and the handler then\n * logs the error to the TERMINAL and calls `next()` — with no error\n * (`config.js:9525-9527`).\n * - connect only routes an error to a 4-arity handler while an error is in\n * flight (`config.js:10611-10626`), so `next()` clears it: every layer after\n * that point, INCLUDING the `done` callback `./web-connector.ts` hands the\n * stack, is called as if the request had simply gone unhandled. The\n * framework then answers the only way it can for a URL it does not know — a\n * 404, empty (see {@link DEV_TRANSFORM_ERROR_STATUS} for which of the two\n * produces it).\n * - Anything registered with `vite.middlewares.use(...)` after `createServer()`\n * resolves lands AFTER that handler and is therefore unreachable. A\n * `configureServer` POST hook does not: vite runs post hooks at\n * `config.js:25700`, five lines BEFORE it mounts its error handler.\n *\n * So this sits between the failure and vite's logger. It captures, then calls\n * `next(error)` and lets vite's own handler run exactly as before — the\n * terminal message and the `hot.send({ type: \"error\" })` overlay push\n * (`config.js:9511-9521`) are unchanged. This transport ADDS a reader; it\n * replaces nothing.\n *\n * @param isProductionRuntime the connector's own hosting-mode signal\n * (`./web-connector.ts:122`) — passed in rather than re-derived so there\n * is one definition of \"this process is Vite-hosted\", not two.\n */\nexport function devErrorTransportPlugin(options: {\n isProductionRuntime: () => boolean;\n buildErrorMessage: BuildErrorMessage;\n}): Plugin {\n const { isProductionRuntime, buildErrorMessage } = options;\n\n if (isProductionRuntime()) {\n throw new DevErrorTransportInProductionError();\n }\n\n const capture: Connect.ErrorHandleFunction = (error, request, _response, next) => {\n // Re-asserted per request, not just at construction: `runtimeStrategy` is\n // process state and a transport that leaks source frames is not something\n // to hold open on a boot-time reading alone. In production this layer is a\n // pass-through and vite's handler behaves exactly as it does today.\n if (isProductionRuntime()) return next(error);\n\n (request as DevTransformErrorCarrier)[DEV_TRANSFORM_ERROR_BODY] = formatDevTransformError(\n error,\n buildErrorMessage,\n );\n\n next(error);\n };\n\n return {\n name: \"warlock:dev-error-transport\",\n // Belt to the `isProductionRuntime` braces: this plugin has no business in\n // a `vite build` graph either.\n apply: \"serve\",\n configureServer(server) {\n // RETURNING a function is what makes this a POST hook — the ordering the\n // note above depends on. Mounting inline here would land the layer BEFORE\n // vite's transform middleware, where no error has been thrown yet.\n return () => {\n server.middlewares.use(capture);\n };\n },\n };\n}\n\n/**\n * Answer the request with the failure {@link devErrorTransportPlugin} captured,\n * if there was one. Returns `false` when there was not, which is the normal\n * case and means \"carry on down the framework's own path\".\n *\n * Called from the Fastify `onRequest` hook that mounts vite\n * (`./web-connector.ts:321`), in the `done` callback — i.e. at the one moment\n * where connect has finished, vite has declined to answer, and the framework is\n * about to 404. Writing to the raw `ServerResponse` rather than through Fastify\n * is what the mount already does for every response vite serves, so this stays\n * on the same side of the seam.\n */\nexport function sendCapturedDevError(request: IncomingMessage, response: ServerResponse): boolean {\n const body = (request as DevTransformErrorCarrier)[DEV_TRANSFORM_ERROR_BODY];\n\n if (typeof body !== \"string\") return false;\n\n // A middleware further down may have answered already (vite serves plenty of\n // requests itself). Never write twice; the captured body is then just dropped.\n if (response.headersSent || response.writableEnded) return false;\n\n response.statusCode = DEV_TRANSFORM_ERROR_STATUS;\n response.setHeader(\"content-type\", \"text/plain; charset=utf-8\");\n // A refusal is a fact about the CURRENT source. Caching it would survive the\n // edit that fixes it.\n response.setHeader(\"cache-control\", \"no-store\");\n response.end(body);\n\n return true;\n}\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;CAIrC,IAAI,SAAS,eAAe,SAAS,eAAe,OAAO;CAE3D,SAAS;CACT,SAAS,UAAU,gBAAgB,2BAA2B;CAG9D,SAAS,UAAU,iBAAiB,UAAU;CAC9C,SAAS,IAAI,IAAI;CAEjB,OAAO;AACT"}
@@ -0,0 +1,14 @@
1
+ import { ServerErrorPageProps } from "../props.mjs";
2
+ import { MetadataOutput } from "../metadata.mjs";
3
+ //#region web/src/server/error-page.d.ts
4
+ /** Server-only shape of an application-owned `error.page.tsx` namespace. */
5
+ type ErrorPageModule = {
6
+ register?: () => unknown;
7
+ default?: unknown;
8
+ metadata?: MetadataOutput | ((props: ServerErrorPageProps) => MetadataOutput);
9
+ };
10
+ /** Deliberately lazy: normal requests never even load error.page.tsx. */
11
+ type ErrorPageModuleLoader = () => Promise<ErrorPageModule>;
12
+ //#endregion
13
+ export { ErrorPageModuleLoader };
14
+ //# sourceMappingURL=error-page.d.mts.map
@@ -0,0 +1,39 @@
1
+ import { ERROR_PAGE_METADATA } from "./resolve-page-metadata.mjs";
2
+
3
+ //#region web/src/server/error-page.ts
4
+ function serializePageError(thrown) {
5
+ if (thrown instanceof Error) return {
6
+ name: thrown.name || "Error",
7
+ message: thrown.message,
8
+ ...process.env.NODE_ENV !== "production" && typeof thrown.stack === "string" ? { stack: thrown.stack } : {}
9
+ };
10
+ let message;
11
+ try {
12
+ message = typeof thrown === "string" ? thrown : String(thrown);
13
+ } catch {
14
+ message = "An unexpected error occurred.";
15
+ }
16
+ return {
17
+ name: "Error",
18
+ message
19
+ };
20
+ }
21
+ /** Error-page metadata improves the safe framework default; it cannot remove noindex. */
22
+ function resolveErrorPageMetadata(module, props) {
23
+ const own = typeof module.metadata === "function" ? module.metadata(props) : module.metadata;
24
+ return {
25
+ ...ERROR_PAGE_METADATA,
26
+ ...own,
27
+ robots: own?.robots ?? ERROR_PAGE_METADATA.robots
28
+ };
29
+ }
30
+ function hydrationErrorPageProps(props, serializableError = props.error) {
31
+ return {
32
+ error: serializePageError(serializableError),
33
+ status: props.status
34
+ };
35
+ }
36
+
37
+ //#endregion
38
+ export { hydrationErrorPageProps, resolveErrorPageMetadata };
39
+ //# sourceMappingURL=error-page.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-page.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/server/error-page.ts"],"sourcesContent":["import type { SerializedErrorPageProps, SerializedPageError } from \"../components/document-context\";\nimport { ERROR_PAGE_METADATA } from \"./resolve-page-metadata\";\nimport type { MetadataOutput } from \"../metadata\";\nimport type { ServerErrorPageProps } from \"../props\";\n\n/** Server-only shape of an application-owned `error.page.tsx` namespace. */\nexport type ErrorPageModule = {\n register?: () => unknown;\n default?: unknown;\n metadata?: MetadataOutput | ((props: ServerErrorPageProps) => MetadataOutput);\n};\n\n/** Deliberately lazy: normal requests never even load error.page.tsx. */\nexport type ErrorPageModuleLoader = () => Promise<ErrorPageModule>;\n\nexport function serializePageError(thrown: unknown): SerializedPageError {\n if (thrown instanceof Error) {\n return {\n name: thrown.name || \"Error\",\n message: thrown.message,\n ...(process.env.NODE_ENV !== \"production\" && typeof thrown.stack === \"string\"\n ? { stack: thrown.stack }\n : {}),\n };\n }\n\n let message: string;\n try {\n message = typeof thrown === \"string\" ? thrown : String(thrown);\n } catch {\n message = \"An unexpected error occurred.\";\n }\n\n return {\n name: \"Error\",\n message,\n };\n}\n\n/** Error-page metadata improves the safe framework default; it cannot remove noindex. */\nexport function resolveErrorPageMetadata(\n module: ErrorPageModule,\n props: ServerErrorPageProps,\n): MetadataOutput {\n const own = typeof module.metadata === \"function\" ? module.metadata(props) : module.metadata;\n\n return { ...ERROR_PAGE_METADATA, ...own, robots: own?.robots ?? ERROR_PAGE_METADATA.robots };\n}\n\nexport function hydrationErrorPageProps(\n props: ServerErrorPageProps,\n serializableError: unknown = props.error,\n): SerializedErrorPageProps {\n return { error: serializePageError(serializableError), status: props.status };\n}\n"],"mappings":";;;AAeA,SAAgB,mBAAmB,QAAsC;CACvE,IAAI,kBAAkB,OACpB,OAAO;EACL,MAAM,OAAO,QAAQ;EACrB,SAAS,OAAO;EAChB,GAAI,QAAQ,IAAI,aAAa,gBAAgB,OAAO,OAAO,UAAU,WACjE,EAAE,OAAO,OAAO,MAAM,IACtB,CAAC;CACP;CAGF,IAAI;CACJ,IAAI;EACF,UAAU,OAAO,WAAW,WAAW,SAAS,OAAO,MAAM;CAC/D,QAAQ;EACN,UAAU;CACZ;CAEA,OAAO;EACL,MAAM;EACN;CACF;AACF;;AAGA,SAAgB,yBACd,QACA,OACgB;CAChB,MAAM,MAAM,OAAO,OAAO,aAAa,aAAa,OAAO,SAAS,KAAK,IAAI,OAAO;CAEpF,OAAO;EAAE,GAAG;EAAqB,GAAG;EAAK,QAAQ,KAAK,UAAU,oBAAoB;CAAO;AAC7F;AAEA,SAAgB,wBACd,OACA,oBAA6B,MAAM,OACT;CAC1B,OAAO;EAAE,OAAO,mBAAmB,iBAAiB;EAAG,QAAQ,MAAM;CAAO;AAC9E"}
@@ -1,7 +1,10 @@
1
- import { ExecutePageRequestOptions, PageBoundaryDesignation, PageContextRunner, PageDataBundle, PageErrorRecord, PageLevelName, PageResponseCommit, PageRouteEntry, PageRouteMatch, PageShortCircuit, PageTripleModule, PipelineLoader, PipelineMiddleware, PipelineRequest, PipelineResponse, PipelineStore } from "./execute-page-request.types.mjs";
2
- import { connectPageContext, connectPageSharedScope } from "./page-context.mjs";
3
- //#region ../web/src/server/execute-page-request.d.ts
4
- declare function executePageRequest<TResult = PageDataBundle>(options: ExecutePageRequestOptions<TResult>): Promise<TResult | undefined>;
1
+ import { BufferedCookie, BufferedHeader, LoaderShortCircuitKind, PageResponseCommit } from "./settle-page-response.mjs";
2
+ import { ExecutePageRequestOptions, PageBoundaryDesignation, PageContextRunner, PageDataBundle, PageErrorRecord, PageLevelName, PageRouteEntry, PageRouteMatch, PageShortCircuit, PageTripleModule, PipelineLoader, PipelineLoaderContext, PipelineMiddleware, PipelineStore } from "./execute-page-request.types.mjs";
3
+ import { connectPageContext } from "./page-context.mjs";
4
+ import { Response } from "@warlock.js/core";
5
+
6
+ //#region web/src/server/execute-page-request.d.ts
7
+ declare function executePageRequest<TResult = PageDataBundle>(options: ExecutePageRequestOptions<TResult>): Promise<TResult | Response | undefined>;
5
8
  //#endregion
6
9
  export { executePageRequest };
7
10
  //# sourceMappingURL=execute-page-request.d.mts.map