@warlock.js/web 5.0.2 → 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 +250 -0
  2. package/README.md +126 -12
  3. package/esm/build/contribution.d.mts +11 -4
  4. package/esm/build/contribution.mjs +46 -22
  5. package/esm/build/contribution.mjs.map +1 -1
  6. package/esm/build/discover-pages.mjs +318 -44
  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 +44 -7
  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 +26 -0
  37. package/esm/client/navigation/scroll-to-fragment.mjs.map +1 -0
  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 +15 -1
  73. package/esm/metadata.mjs +45 -0
  74. package/esm/metadata.mjs.map +1 -0
  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 +120 -0
  100. package/esm/routing/url-fragment.mjs.map +1 -0
  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 +58 -6
  113. package/esm/server/create-page-route-handler.mjs +127 -40
  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 +6 -5
  128. package/esm/server/index.mjs +4 -4
  129. package/esm/server/install-page-routes-from-manifest.d.mts +17 -7
  130. package/esm/server/install-page-routes-from-manifest.mjs +91 -8
  131. package/esm/server/install-page-routes-from-manifest.mjs.map +1 -1
  132. package/esm/server/install-page-routes.d.mts +32 -13
  133. package/esm/server/install-page-routes.mjs +112 -32
  134. package/esm/server/install-page-routes.mjs.map +1 -1
  135. package/esm/server/install-production-page-routes.mjs +3 -31
  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 +126 -0
  140. package/esm/server/not-found-page.mjs +157 -0
  141. package/esm/server/not-found-page.mjs.map +1 -0
  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 +6 -4
  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 +233 -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 +10 -6
  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 +247 -2
  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 +241 -49
  208. package/llms.txt +6 -2
  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 +130 -7
  212. package/skills/load-page-data/SKILL.md +92 -12
  213. package/skills/navigate-on-the-client/SKILL.md +3 -1
  214. package/skills/serve-styles/SKILL.md +13 -12
  215. package/skills/use-layouts/SKILL.md +20 -8
  216. package/skills/write-the-root/SKILL.md +5 -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 +1 @@
1
- {"version":3,"file":"navigation-root.mjs","names":[],"sources":["../../../../../../../../web/src/client/navigation/navigation-root.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type ReactNode } from \"react\";\nimport { DocumentContext } from \"../../components/document-context\";\nimport type { HydrationDocumentPayloadSource } from \"../../hydration-payload\";\nimport type { MetadataOutput } from \"../../metadata\";\nimport { connectNavigator } from \"../../routing/navigator\";\nimport { hydrateShared } from \"../../shared\";\nimport type { ClientPageEntry } from \"../runtime\";\nimport { recordCurrentRoute } from \"./current-route\";\nimport { fetchPageData } from \"./fetch-page-data\";\nimport { takePrefetchedPageData } from \"./prefetch\";\nimport { connectRefresher, createRefresher, type RefreshablePage } from \"./refresh\";\n\n/**\n * The component that makes a page REPLACEABLE.\n *\n * Hydration mounts a fixed tree — correct, because the first render must match\n * the server's markup byte for byte. Client navigation needs that same position\n * in the tree to be able to hold a *different* page later, which means state,\n * which means a component. This is that component and nothing more.\n *\n * ## Why the layout stays mounted\n *\n * The new tree is built by the same `buildHydratedTree` the server's payload\n * went through, so a navigation within one layout produces an element whose\n * layout components are the same types in the same positions. React reconciles\n * them rather than remounting, so layout state — an open menu, a scroll\n * container, a video — survives. That is the entire user-visible benefit of\n * client navigation, and it is a consequence of reusing the builder rather than\n * anything this file does.\n */\n\n/**\n * ONE tag `<head>` may hold at most one of, addressed the way the browser\n * already addresses it. No marker attribute: the tags this replaces were\n * rendered by `<Head/>` on the server and carry none, and a marker would make\n * the applier ignore exactly the tags it exists to correct — the first\n * navigation's.\n */\ntype ManagedTag = {\n /** Finds the existing tag, server-rendered or applied by a previous swap. */\n selector: string;\n create: (documentNode: Document) => Element;\n write: (element: Element, value: string) => void;\n};\n\nfunction metaTag(attribute: \"name\" | \"property\", key: string): ManagedTag {\n return {\n selector: `meta[${attribute}=\"${key}\"]`,\n create: documentNode => {\n const element = documentNode.createElement(\"meta\");\n\n element.setAttribute(attribute, key);\n\n return element;\n },\n write: (element, value) => element.setAttribute(\"content\", value),\n };\n}\n\nconst TITLE_TAG: ManagedTag = {\n selector: \"title\",\n create: documentNode => documentNode.createElement(\"title\"),\n write: (element, value) => {\n element.textContent = value;\n },\n};\n\nconst CANONICAL_TAG: ManagedTag = {\n selector: 'link[rel=\"canonical\"]',\n create: documentNode => {\n const element = documentNode.createElement(\"link\");\n\n element.setAttribute(\"rel\", \"canonical\");\n\n return element;\n },\n write: (element, value) => element.setAttribute(\"href\", value),\n};\n\n/**\n * The metadata, resolved into (tag, value) pairs in `<Head/>`'s ORDER and by\n * `<Head/>`'s RULES — including the og fallbacks and the fact that they apply\n * only when `openGraph` is present (`components/head.ts:21-24,43-48`).\n *\n * The duplication is deliberate and it is the known cost here. `<Head/>` is a\n * React component that renders elements into a tree; this writes elements into\n * a live `<head>` that no client tree owns. They cannot be one function today,\n * but they MUST agree: the head after navigating to a URL has to equal the head\n * after landing on it, or a share preview depends on how the visitor arrived.\n * The fix is a shared descriptor list both consume — see the report's followup.\n */\nfunction resolveManagedTags(\n metadata: MetadataOutput | undefined,\n): readonly (readonly [ManagedTag, string | undefined])[] {\n const keywords =\n metadata?.keywords === undefined\n ? undefined\n : Array.isArray(metadata.keywords)\n ? metadata.keywords.join(\", \")\n : (metadata.keywords as string);\n\n const openGraph = metadata?.openGraph;\n const twitter = metadata?.twitter;\n\n return [\n [TITLE_TAG, metadata?.title],\n [metaTag(\"name\", \"description\"), metadata?.description],\n [metaTag(\"name\", \"keywords\"), keywords],\n [CANONICAL_TAG, metadata?.canonical],\n [metaTag(\"name\", \"robots\"), metadata?.robots],\n [metaTag(\"property\", \"og:title\"), openGraph && (openGraph.title ?? metadata?.title)],\n [\n metaTag(\"property\", \"og:description\"),\n openGraph && (openGraph.description ?? metadata?.description),\n ],\n [metaTag(\"property\", \"og:image\"), openGraph?.image],\n [metaTag(\"property\", \"og:url\"), openGraph?.url],\n [metaTag(\"property\", \"og:type\"), openGraph?.type],\n [metaTag(\"name\", \"twitter:card\"), twitter?.card],\n [metaTag(\"name\", \"twitter:title\"), twitter?.title],\n [metaTag(\"name\", \"twitter:description\"), twitter?.description],\n [metaTag(\"name\", \"twitter:image\"), twitter?.image],\n ];\n}\n\n/**\n * Make `<head>` describe the page now on screen.\n *\n * ## Why this is imperative, and why that is not a shortcut\n *\n * `<Head/>` renders inside the App level, and the App level is deliberately NOT\n * in the hydrated tree — the client mounts at `#root`, which App contains\n * (`client/build-hydrated-tree.ts`'s header). So no client render can reach\n * `<head>`, and a swap either writes it directly or leaves the previous page's\n * title in the tab. It leaves it today; that is the bug.\n *\n * ## ABSENT MEANS REMOVED\n *\n * Every managed tag the new metadata does not set is REMOVED, not left alone.\n * `/` sets a description and `/contact-us` does not: keeping it would describe\n * the contact page with the home page's words to every crawler, share preview\n * and assistive reader that looks — a wrong answer, where an absent one is\n * merely absent. A title the new page does not set goes too, and the tab falls\n * back to the URL, which is the honest rendering of \"this page did not name\n * itself\".\n *\n * Only the tags `<Head/>` renders FROM METADATA are touched. The charset meta\n * is rendered unconditionally and belongs to the document, so it is left alone.\n *\n * Takes the document as an argument rather than reaching for the global, which\n * is what makes it provable in a suite with no DOM.\n */\nexport function applyDocumentMetadata(\n documentNode: Document,\n metadata: MetadataOutput | undefined,\n): void {\n for (const [tag, value] of resolveManagedTags(metadata)) {\n const existing = documentNode.querySelector(tag.selector);\n\n if (value === undefined) {\n existing?.remove();\n continue;\n }\n\n if (existing !== null) {\n tag.write(existing, value);\n continue;\n }\n\n const created = tag.create(documentNode);\n\n tag.write(created, value);\n documentNode.head.appendChild(created);\n }\n}\n\nexport type NavigationRootProps = {\n pages: readonly ClientPageEntry[];\n /** The payload the document was rendered from — the hydration one. */\n initialPayload: HydrationDocumentPayloadSource;\n /** The tree already built from {@link initialPayload}, rendered as-is first. */\n initialTree: ReactNode;\n /**\n * How a payload becomes a tree. Injected rather than imported so this\n * component is testable without the page registry or a bundler — the same\n * reason `hydratePage` takes its builder as an argument.\n */\n buildTree: (\n pages: readonly ClientPageEntry[],\n payload: HydrationDocumentPayloadSource,\n ) => Promise<ReactNode>;\n};\n\n/**\n * The page on screen. Defined in `refresh.ts` because the third field is that\n * file's decision: `routeSource` is the payload object `current-route.ts`\n * identifies the route by, which is `payload` after a navigation but the\n * PREVIOUS page's object after a refresh — a refresh must not shift\n * `previousRoute()` onto the page the user is already looking at.\n */\ntype Current = RefreshablePage;\n\nexport function NavigationRoot({\n pages,\n initialPayload,\n initialTree,\n buildTree,\n}: NavigationRootProps) {\n const [current, setCurrent] = useState<Current>({\n payload: initialPayload,\n tree: initialTree,\n routeSource: initialPayload,\n });\n\n /*\n The latest state, readable from the effect below — which closes over the\n render that created it and would otherwise see the page the user was on\n when the runtime connected. A ref rather than an effect dependency because\n re-running the effect on every swap would disconnect and reconnect the\n navigator mid-navigation.\n */\n const currentRef = useRef(current);\n\n currentRef.current = current;\n\n useEffect(() => {\n /*\n THE RACE THIS COUNTER EXISTS FOR. Two clicks in quick succession start two\n fetches; the second can easily answer first (a cached page beating an\n uncached one is the common case, not the exotic one). Without a token the\n slower FIRST response lands last and the user ends up on the page they\n navigated away from, with the address bar showing the other one.\n\n Every navigation takes a token; a result is applied only if its token is\n still the newest. Superseded responses are dropped silently — they are not\n errors, they are answers to a question the user stopped asking.\n */\n let token = 0;\n let disposed = false;\n\n const apply = async (url: string, replace: boolean): Promise<void> => {\n const ticket = ++token;\n /*\n A prefetched response is CONSUMED, never merely read — `take` removes it,\n so the same speculative fetch can satisfy exactly one navigation and a\n second click on the same link goes to the network. That matters because\n the HTTP cache cannot stand in for this: dev responses are `no-store`\n (`server/dev-server.ts:254`) and production is `private` with no\n `max-age` (`server/render-page.ts:432`), so the browser will not reliably\n replay the speculative response on the real click.\n\n The race guard below still holds on a cache hit: `??` short-circuits the\n await, and the synchronous path reaches the same `ticket !== token` check.\n */\n const result = takePrefetchedPageData(url) ?? (await fetchPageData(url));\n\n if (disposed || ticket !== token) return;\n\n if (result.type === \"hard-navigate\") {\n // The documented degradation: hand the URL back to the browser. The\n // user still gets the page — see `fetch-page-data.ts`.\n console.warn(`Warlock navigation fell back to a full load (${result.reason}):`, url);\n window.location.assign(url);\n\n return;\n }\n\n let tree: ReactNode;\n\n try {\n tree = await buildTree(pages, result.payload);\n } catch (error) {\n // The payload was fine but its page chunk would not load or compose —\n // a stale bundle after a deploy is the realistic cause. A full load\n // fetches the current bundle, which is also the fix.\n console.warn(\"Warlock navigation could not build the page tree:\", error);\n window.location.assign(url);\n\n return;\n }\n\n if (disposed || ticket !== token) return;\n\n /*\n Shared state BEFORE the render that consumes it. `hydrateShared`\n installs the snapshot `useShared()` reads; swapping the tree first would\n render one frame of the new page against the previous page's shared\n state — locale, permissions, the current user.\n */\n hydrateShared(result.payload.shared);\n\n // History AFTER the fetch succeeded, never before. Pushing optimistically\n // would leave the address bar pointing at a page that then failed to\n // load, and a Back press would return to a URL the user never saw.\n if (replace) {\n window.history.replaceState(null, \"\", result.url);\n } else {\n window.history.pushState(null, \"\", result.url);\n }\n\n // A navigation IS the route moving, so the fetched payload is both the\n // page and the route's identity.\n setCurrent({ payload: result.payload, tree, routeSource: result.payload });\n };\n\n /*\n The same counter `apply` above takes its tickets from, handed to\n `refresh()` as a predicate. ONE mechanism, not two: a refresh and a\n navigation can overtake each other in either direction, and separate\n counters would leave each blind to the other.\n */\n const claimTicket = (): (() => boolean) => {\n const ticket = ++token;\n\n return () => !disposed && ticket === token;\n };\n\n const previousRefresher = connectRefresher(\n createRefresher({\n readCurrent: () => currentRef.current,\n writeCurrent: setCurrent,\n buildTree: payload => buildTree(pages, payload),\n claimTicket,\n }),\n );\n\n const previousNavigator = connectNavigator((url, options) => {\n void apply(url, options?.replace === true);\n\n // Accepted: the caller suppresses the browser's default. Returning `true`\n // before the fetch resolves is deliberate — the decision to handle a link\n // cannot wait on the network without the browser having already followed\n // it.\n return true;\n });\n\n /*\n Back/Forward. The entry is already in history and the URL has already\n changed by the time this fires, so the page is fetched and swapped with\n `replace` — pushing here would append a duplicate entry and make Back\n require two presses.\n */\n const onPopState = (): void => {\n void apply(window.location.href, true);\n };\n\n window.addEventListener(\"popstate\", onPopState);\n\n return () => {\n disposed = true;\n window.removeEventListener(\"popstate\", onPopState);\n connectNavigator(previousNavigator);\n connectRefresher(previousRefresher);\n };\n }, [pages, buildTree]);\n\n /*\n The payload whose metadata `<head>` currently reflects. Seeded with the\n HYDRATION payload, which is the point: on the initial mount the head is the\n server's own render of this very metadata, so there is nothing to correct —\n and re-applying would be a chance to get it wrong, since a payload from a\n build with no `metadata` key would wipe a head the server filled in\n correctly. The head is applied on SWAPS only.\n */\n const appliedMetadataSource = useRef(current.payload);\n\n useEffect(() => {\n if (appliedMetadataSource.current === current.payload) return;\n\n appliedMetadataSource.current = current.payload;\n\n /*\n Keyed on the payload's identity, so this covers a refresh as well as a\n navigation: `refresh()` produces a NEW payload for the page already on\n screen, and a page whose metadata is a function of its loader data can\n legitimately re-title itself when that data changes. One applier at the\n one place the page changes, rather than a call in each pathway that could\n be forgotten in the next one.\n */\n applyDocumentMetadata(document, current.payload.metadata);\n }, [current.payload]);\n\n /*\n DURING RENDER, not in an effect, and that placement is the requirement\n rather than a shortcut. A page component calling `currentRoute()` does it\n while IT is rendering, and child effects run before a parent's, so anything\n recorded from an effect here would be recorded too late to answer the first\n render of the page it describes — which on the initial mount is the only\n render there has been, and the server's match is all there is.\n\n Recording is keyed on the payload's identity (`current-route.ts`), so the\n extra passes render gives us for free — StrictMode's double invoke, a parent\n re-render — are recognised as the same page rather than counted as\n navigations.\n\n `routeSource`, NOT `payload`: they are the same object for every navigation,\n and differ only after a refresh, which produces a new payload for the page\n already on screen and must not be counted as a move (see `refresh.ts`).\n */\n recordCurrentRoute(current.routeSource);\n\n /*\n An INNER DocumentContext provider, nested inside the one `hydratePage`\n mounted. That outer provider is created once with the hydration payload and\n never changes, so anything reading the document context after a navigation\n would see the payload of the page the user has left. The nearest provider\n wins, so this one keeps it current.\n */\n /*\n `metadata` from the PAYLOAD, not `undefined`. The document context is the\n universal shape — the server provides the resolved metadata around the same\n tree — so handing the client's readers `undefined` was a lie the payload can\n now correct. It also removes a latent mismatch: a `<Head/>` rendered inside\n a Layout (not the App level) renders its tags into `#root` server-side, and\n hydrating that markup against `metadata: undefined` produced a tree the\n server never rendered.\n */\n return (\n <DocumentContext.Provider\n value={{ metadata: current.payload.metadata, payload: current.payload }}\n >\n {current.tree}\n </DocumentContext.Provider>\n );\n}\n"],"mappings":";;;;;;;;;;;AA6CA,SAAS,QAAQ,WAAgC,KAAyB;CACxE,OAAO;EACL,UAAU,QAAQ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mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/client/navigation/navigation-root.tsx"],"sourcesContent":["import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from \"react\";\r\nimport { DocumentContext } from \"../../components/document-context\";\r\nimport type { HydrationDocumentPayloadSource } from \"../../hydration-payload\";\r\nimport type { MetadataOutput } from \"../../metadata\";\r\nimport { connectNavigator } from \"../../routing/navigator\";\r\nimport {\r\n fragmentOf,\r\n samePageFragment,\r\n withFragmentFrom,\r\n withoutFragment,\r\n} from \"../../routing/url-fragment\";\r\nimport { hydrateShared } from \"../../shared\";\r\nimport type { ClientPageEntry } from \"../runtime\";\r\nimport { recordCurrentRoute } from \"./current-route\";\r\nimport { fetchPageData } from \"./fetch-page-data\";\r\nimport { takePrefetchedPageData } from \"./prefetch\";\r\nimport { connectRefresher, createRefresher, type RefreshablePage } from \"./refresh\";\r\nimport { scrollToFragment } from \"./scroll-to-fragment\";\r\n\r\n/**\r\n * The component that makes a page REPLACEABLE.\r\n *\r\n * Hydration mounts a fixed tree — correct, because the first render must match\r\n * the server's markup byte for byte. Client navigation needs that same position\r\n * in the tree to be able to hold a *different* page later, which means state,\r\n * which means a component. This is that component and nothing more.\r\n *\r\n * ## Why the layout stays mounted\r\n *\r\n * The new tree is built by the same `buildHydratedTree` the server's payload\r\n * went through, so a navigation within one layout produces an element whose\r\n * layout components are the same types in the same positions. React reconciles\r\n * them rather than remounting, so layout state — an open menu, a scroll\r\n * container, a video — survives. That is the entire user-visible benefit of\r\n * client navigation, and it is a consequence of reusing the builder rather than\r\n * anything this file does.\r\n */\r\n\r\n/**\r\n * ONE tag `<head>` may hold at most one of, addressed the way the browser\r\n * already addresses it. No marker attribute: the tags this replaces were\r\n * rendered by `<Head/>` on the server and carry none, and a marker would make\r\n * the applier ignore exactly the tags it exists to correct — the first\r\n * navigation's.\r\n */\r\ntype ManagedTag = {\r\n /** Finds the existing tag, server-rendered or applied by a previous swap. */\r\n selector: string;\r\n create: (documentNode: Document) => Element;\r\n write: (element: Element, value: string) => void;\r\n};\r\n\r\nfunction metaTag(attribute: \"name\" | \"property\", key: string): ManagedTag {\r\n return {\r\n selector: `meta[${attribute}=\"${key}\"]`,\r\n create: documentNode => {\r\n const element = documentNode.createElement(\"meta\");\r\n\r\n element.setAttribute(attribute, key);\r\n\r\n return element;\r\n },\r\n write: (element, value) => element.setAttribute(\"content\", value),\r\n };\r\n}\r\n\r\nconst TITLE_TAG: ManagedTag = {\r\n selector: \"title\",\r\n create: documentNode => documentNode.createElement(\"title\"),\r\n write: (element, value) => {\r\n element.textContent = value;\r\n },\r\n};\r\n\r\nconst CANONICAL_TAG: ManagedTag = {\r\n selector: 'link[rel=\"canonical\"]',\r\n create: documentNode => {\r\n const element = documentNode.createElement(\"link\");\r\n\r\n element.setAttribute(\"rel\", \"canonical\");\r\n\r\n return element;\r\n },\r\n write: (element, value) => element.setAttribute(\"href\", value),\r\n};\r\n\r\n/**\r\n * The metadata, resolved into (tag, value) pairs in `<Head/>`'s ORDER and by\r\n * `<Head/>`'s RULES — including the og fallbacks and the fact that they apply\r\n * only when `openGraph` is present (`components/head.ts:21-24,43-48`).\r\n *\r\n * The duplication is deliberate and it is the known cost here. `<Head/>` is a\r\n * React component that renders elements into a tree; this writes elements into\r\n * a live `<head>` that no client tree owns. They cannot be one function today,\r\n * but they MUST agree: the head after navigating to a URL has to equal the head\r\n * after landing on it, or a share preview depends on how the visitor arrived.\r\n * The fix is a shared descriptor list both consume — see the report's followup.\r\n */\r\nfunction resolveManagedTags(\r\n metadata: MetadataOutput | undefined,\r\n): readonly (readonly [ManagedTag, string | undefined])[] {\r\n const keywords =\r\n metadata?.keywords === undefined\r\n ? undefined\r\n : Array.isArray(metadata.keywords)\r\n ? metadata.keywords.join(\", \")\r\n : (metadata.keywords as string);\r\n\r\n const openGraph = metadata?.openGraph;\r\n const twitter = metadata?.twitter;\r\n\r\n return [\r\n [TITLE_TAG, metadata?.title],\r\n [metaTag(\"name\", \"description\"), metadata?.description],\r\n [metaTag(\"name\", \"keywords\"), keywords],\r\n [CANONICAL_TAG, metadata?.canonical],\r\n [metaTag(\"name\", \"robots\"), metadata?.robots],\r\n [metaTag(\"property\", \"og:title\"), openGraph && (openGraph.title ?? metadata?.title)],\r\n [\r\n metaTag(\"property\", \"og:description\"),\r\n openGraph && (openGraph.description ?? metadata?.description),\r\n ],\r\n [metaTag(\"property\", \"og:image\"), openGraph?.image],\r\n [metaTag(\"property\", \"og:url\"), openGraph?.url],\r\n [metaTag(\"property\", \"og:type\"), openGraph?.type],\r\n [metaTag(\"name\", \"twitter:card\"), twitter?.card],\r\n [metaTag(\"name\", \"twitter:title\"), twitter?.title],\r\n [metaTag(\"name\", \"twitter:description\"), twitter?.description],\r\n [metaTag(\"name\", \"twitter:image\"), twitter?.image],\r\n ];\r\n}\r\n\r\n/**\r\n * Make `<head>` describe the page now on screen.\r\n *\r\n * ## Why this is imperative, and why that is not a shortcut\r\n *\r\n * `<Head/>` renders inside the App level, and the App level is deliberately NOT\r\n * in the hydrated tree — the client mounts at `#root`, which App contains\r\n * (`client/build-hydrated-tree.ts`'s header). So no client render can reach\r\n * `<head>`, and a swap either writes it directly or leaves the previous page's\r\n * title in the tab. It leaves it today; that is the bug.\r\n *\r\n * ## ABSENT MEANS REMOVED\r\n *\r\n * Every managed tag the new metadata does not set is REMOVED, not left alone.\r\n * `/` sets a description and `/contact-us` does not: keeping it would describe\r\n * the contact page with the home page's words to every crawler, share preview\r\n * and assistive reader that looks — a wrong answer, where an absent one is\r\n * merely absent. A title the new page does not set goes too, and the tab falls\r\n * back to the URL, which is the honest rendering of \"this page did not name\r\n * itself\".\r\n *\r\n * Only the tags `<Head/>` renders FROM METADATA are touched. The charset meta\r\n * is rendered unconditionally and belongs to the document, so it is left alone.\r\n *\r\n * Takes the document as an argument rather than reaching for the global, which\r\n * is what makes it provable in a suite with no DOM.\r\n */\r\nexport function applyDocumentMetadata(\r\n documentNode: Document,\r\n metadata: MetadataOutput | undefined,\r\n): void {\r\n for (const [tag, value] of resolveManagedTags(metadata)) {\r\n const existing = documentNode.querySelector(tag.selector);\r\n\r\n if (value === undefined) {\r\n existing?.remove();\r\n continue;\r\n }\r\n\r\n if (existing !== null) {\r\n tag.write(existing, value);\r\n continue;\r\n }\r\n\r\n const created = tag.create(documentNode);\r\n\r\n tag.write(created, value);\r\n documentNode.head.appendChild(created);\r\n }\r\n}\r\n\r\nexport type NavigationRootProps = {\r\n pages: readonly ClientPageEntry[];\r\n /** The payload the document was rendered from — the hydration one. */\r\n initialPayload: HydrationDocumentPayloadSource;\r\n /** The tree already built from {@link initialPayload}, rendered as-is first. */\r\n initialTree: ReactNode;\r\n /**\r\n * How a payload becomes a tree. Injected rather than imported so this\r\n * component is testable without the page registry or a bundler — the same\r\n * reason `hydratePage` takes its builder as an argument.\r\n */\r\n buildTree: (\r\n pages: readonly ClientPageEntry[],\r\n payload: HydrationDocumentPayloadSource,\r\n ) => Promise<ReactNode>;\r\n};\r\n\r\n/**\r\n * The page on screen. Defined in `refresh.ts` because the third field is that\r\n * file's decision: `routeSource` is the payload object `current-route.ts`\r\n * identifies the route by, which is `payload` after a navigation but the\r\n * PREVIOUS page's object after a refresh — a refresh must not shift\r\n * `previousRoute()` onto the page the user is already looking at.\r\n */\r\ntype Current = RefreshablePage;\r\n\r\nexport function NavigationRoot({\r\n pages,\r\n initialPayload,\r\n initialTree,\r\n buildTree,\r\n}: NavigationRootProps) {\r\n const [current, setCurrent] = useState<Current>({\r\n payload: initialPayload,\r\n tree: initialTree,\r\n routeSource: initialPayload,\r\n });\r\n\r\n /*\r\n The latest state, readable from the effect below — which closes over the\r\n render that created it and would otherwise see the page the user was on\r\n when the runtime connected. A ref rather than an effect dependency because\r\n re-running the effect on every swap would disconnect and reconnect the\r\n navigator mid-navigation.\r\n */\r\n const currentRef = useRef(current);\r\n\r\n currentRef.current = current;\r\n\r\n /*\r\n THE ORDERING PROBLEM, and this ref is half of the answer to it.\r\n\r\n The element a fragment names lives in the tree that has not been built yet:\r\n at the moment `apply` finishes fetching, the DOM still holds the page the\r\n user is LEAVING. Scrolling there finds nothing, and finding nothing is\r\n silent — indistinguishable from the fragment bug itself.\r\n\r\n So the fragment is not scrolled to; it is HANDED OVER. `apply` parks it here\r\n immediately before the `setCurrent` that swaps the tree, and the layout\r\n effect below — which React runs after it has committed that tree to the DOM\r\n and before the browser paints — spends it. Read the two together; neither\r\n half means anything alone.\r\n */\r\n const pendingFragment = useRef<string | undefined>(undefined);\r\n\r\n useEffect(() => {\r\n /*\r\n THE RACE THIS COUNTER EXISTS FOR. Two clicks in quick succession start two\r\n fetches; the second can easily answer first (a cached page beating an\r\n uncached one is the common case, not the exotic one). Without a token the\r\n slower FIRST response lands last and the user ends up on the page they\r\n navigated away from, with the address bar showing the other one.\r\n\r\n Every navigation takes a token; a result is applied only if its token is\r\n still the newest. Superseded responses are dropped silently — they are not\r\n errors, they are answers to a question the user stopped asking.\r\n */\r\n let token = 0;\r\n let disposed = false;\r\n /*\r\n The URL this runtime last put in the address bar, so `popstate` can tell a\r\n move BETWEEN pages from a move between two fragments of one page. Seeded\r\n with the URL the document was loaded at, which is the entry the first Back\r\n would come from.\r\n */\r\n let committedUrl = window.location.href;\r\n\r\n /**\r\n * @param honourFragment whether the URL's fragment should be SCROLLED to\r\n * once the new page is on screen. True for a navigation the app asked for\r\n * — a `<Link>` click, `navigateTo` — and false for Back/Forward, where the\r\n * browser has already restored the scroll position of the entry being\r\n * returned to and moving the page again would overwrite the user's own\r\n * position with the anchor they had scrolled away from. (Restoration is\r\n * the browser's, deliberately: canon `0342c0d4`.)\r\n *\r\n * The fragment is still PRESERVED in the URL in both cases — see below.\r\n */\r\n const apply = async (\r\n url: string,\r\n replace: boolean,\r\n honourFragment: boolean,\r\n ): Promise<void> => {\r\n const ticket = ++token;\r\n /*\r\n A prefetched response is CONSUMED, never merely read — `take` removes it,\r\n so the same speculative fetch can satisfy exactly one navigation and a\r\n second click on the same link goes to the network. That matters because\r\n the HTTP cache cannot stand in for this: dev responses are `no-store`\r\n (`server/dev-server.ts:254`) and production is `private` with no\r\n `max-age` (`server/render-page.ts:432`), so the browser will not reliably\r\n replay the speculative response on the real click.\r\n\r\n The race guard below still holds on a cache hit: `??` short-circuits the\r\n await, and the synchronous path reaches the same `ticket !== token` check.\r\n */\r\n const result = takePrefetchedPageData(url) ?? (await fetchPageData(url));\r\n\r\n if (disposed || ticket !== token) return;\r\n\r\n if (result.type === \"hard-navigate\") {\r\n // The documented degradation: hand the URL back to the browser. The\r\n // user still gets the page — see `fetch-page-data.ts`.\r\n console.warn(`Warlock navigation fell back to a full load (${result.reason}):`, url);\r\n window.location.assign(url);\r\n\r\n return;\r\n }\r\n\r\n let tree: ReactNode;\r\n\r\n try {\r\n tree = await buildTree(pages, result.payload);\r\n } catch (error) {\r\n // The payload was fine but its page chunk would not load or compose —\r\n // a stale bundle after a deploy is the realistic cause. A full load\r\n // fetches the current bundle, which is also the fix.\r\n console.warn(\"Warlock navigation could not build the page tree:\", error);\r\n window.location.assign(url);\r\n\r\n return;\r\n }\r\n\r\n if (disposed || ticket !== token) return;\r\n\r\n /*\r\n Shared state BEFORE the render that consumes it. `hydrateShared`\r\n installs the snapshot `useShared()` reads; swapping the tree first would\r\n render one frame of the new page against the previous page's shared\r\n state — locale, permissions, the current user.\r\n */\r\n hydrateShared(result.payload.shared);\r\n\r\n /*\r\n The fragment PUT BACK. `result.url` comes from `response.url`, and a\r\n fragment is never sent to a server, so the URL a navigation would\r\n otherwise be written to history from has had it stripped — which is how\r\n `<Link href=\"/docs#install\">` used to land on `/docs` with the author's\r\n fragment gone from the address bar for good.\r\n\r\n Applied on EVERY path, Back included: a popstate re-fetch that wrote\r\n `result.url` back would delete the fragment from an entry the user is\r\n merely returning to.\r\n */\r\n const finalUrl = withFragmentFrom(result.url, url);\r\n\r\n // History AFTER the fetch succeeded, never before. Pushing optimistically\r\n // would leave the address bar pointing at a page that then failed to\r\n // load, and a Back press would return to a URL the user never saw.\r\n if (replace) {\r\n window.history.replaceState(null, \"\", finalUrl);\r\n } else {\r\n window.history.pushState(null, \"\", finalUrl);\r\n }\r\n\r\n committedUrl = finalUrl;\r\n\r\n // Handed to the layout effect, which runs once React has committed the\r\n // tree below to the DOM — the first moment the target can exist. Set\r\n // unconditionally so a navigation with no fragment CLEARS a fragment left\r\n // pending by one that was superseded.\r\n pendingFragment.current = honourFragment ? fragmentOf(finalUrl) : undefined;\r\n\r\n // A navigation IS the route moving, so the fetched payload is both the\r\n // page and the route's identity.\r\n setCurrent({ payload: result.payload, tree, routeSource: result.payload });\r\n };\r\n\r\n /*\r\n The same counter `apply` above takes its tickets from, handed to\r\n `refresh()` as a predicate. ONE mechanism, not two: a refresh and a\r\n navigation can overtake each other in either direction, and separate\r\n counters would leave each blind to the other.\r\n */\r\n const claimTicket = (): (() => boolean) => {\r\n const ticket = ++token;\r\n\r\n return () => !disposed && ticket === token;\r\n };\r\n\r\n const previousRefresher = connectRefresher(\r\n createRefresher({\r\n readCurrent: () => currentRef.current,\r\n writeCurrent: setCurrent,\r\n buildTree: payload => buildTree(pages, payload),\r\n claimTicket,\r\n }),\r\n );\r\n\r\n const previousNavigator = connectNavigator((url, options) => {\r\n const replace = options?.replace === true;\r\n\r\n /*\r\n THIS page with a fragment on it — `#reviews`, or the current path spelled\r\n out with one appended. No fetch, no tree swap: the page is already here,\r\n and re-fetching it would discard its DOM and everything live in it to\r\n arrive back where we started, one round trip later. Address bar first,\r\n then the jump, which is the order the browser uses for a plain anchor.\r\n */\r\n const fragment = samePageFragment(url, window.location.href);\r\n\r\n if (fragment !== undefined) {\r\n if (replace) {\r\n window.history.replaceState(null, \"\", url);\r\n } else {\r\n window.history.pushState(null, \"\", url);\r\n }\r\n\r\n committedUrl = window.location.href;\r\n\r\n // The target is in the DOM already, so there is nothing to wait for —\r\n // and nothing to hand to the layout effect, which no swap would fire.\r\n scrollToFragment(document, fragment);\r\n\r\n return true;\r\n }\r\n\r\n void apply(url, replace, true);\r\n\r\n // Accepted: the caller suppresses the browser's default. Returning `true`\r\n // before the fetch resolves is deliberate — the decision to handle a link\r\n // cannot wait on the network without the browser having already followed\r\n // it.\r\n return true;\r\n });\r\n\r\n /*\r\n Back/Forward. The entry is already in history and the URL has already\r\n changed by the time this fires, so the page is fetched and swapped with\r\n `replace` — pushing here would append a duplicate entry and make Back\r\n require two presses.\r\n */\r\n const onPopState = (): void => {\r\n const target = window.location.href;\r\n /*\r\n A hash-only move within one page — Back off a `#section` click, or\r\n Forward onto one. The document is the same document and the tree on\r\n screen is already the right tree, so there is nothing to fetch: the\r\n browser has changed the URL and restored the position for that entry\r\n itself, and re-fetching would throw away a live page to rebuild the one\r\n already showing. Scroll restoration stays the browser's (canon\r\n `0342c0d4`), which is exactly what leaving this alone means.\r\n */\r\n const hashOnlyMove = withoutFragment(target) === withoutFragment(committedUrl);\r\n\r\n committedUrl = target;\r\n\r\n if (hashOnlyMove) return;\r\n\r\n void apply(target, true, false);\r\n };\r\n\r\n window.addEventListener(\"popstate\", onPopState);\r\n\r\n return () => {\r\n disposed = true;\r\n window.removeEventListener(\"popstate\", onPopState);\r\n connectNavigator(previousNavigator);\r\n connectRefresher(previousRefresher);\r\n };\r\n }, [pages, buildTree]);\r\n\r\n /*\r\n THE OTHER HALF OF THE ORDERING PROBLEM (see `pendingFragment` above).\r\n\r\n `useLayoutEffect`, not `useEffect`, and the difference is the whole point:\r\n React runs a layout effect after it has COMMITTED this render to the DOM and\r\n BEFORE the browser paints. That is the earliest instant the new page's\r\n elements exist — a scroll any sooner finds nothing — and the last instant\r\n before the user sees anything, so the page is never painted at the top and\r\n then jumped. `useEffect` would satisfy the first requirement and not the\r\n second: it runs after paint, which is a visible flash of the wrong position.\r\n\r\n Keyed on `current` rather than reaching for a fresh render: the effect fires\r\n on the swap that put the target in the DOM, so no polling, no rAF, no\r\n timeout. What it CANNOT wait for is content that arrives later still — an\r\n image without dimensions above the target, a component that suspends — which\r\n moves the target after we have scrolled to where it was. That is the known\r\n limit of this mechanism and it is the same one a browser has.\r\n\r\n Consumed once: the fragment is cleared as it is read, so a later re-render\r\n (a refresh, a parent's state change) does not yank the page back to an\r\n anchor the user has since scrolled away from.\r\n */\r\n useLayoutEffect(() => {\r\n const fragment = pendingFragment.current;\r\n\r\n if (fragment === undefined) return;\r\n\r\n pendingFragment.current = undefined;\r\n\r\n scrollToFragment(document, fragment);\r\n }, [current]);\r\n\r\n /*\r\n The payload whose metadata `<head>` currently reflects. Seeded with the\r\n HYDRATION payload, which is the point: on the initial mount the head is the\r\n server's own render of this very metadata, so there is nothing to correct —\r\n and re-applying would be a chance to get it wrong, since a payload from a\r\n build with no `metadata` key would wipe a head the server filled in\r\n correctly. The head is applied on SWAPS only.\r\n */\r\n const appliedMetadataSource = useRef(current.payload);\r\n\r\n useEffect(() => {\r\n if (appliedMetadataSource.current === current.payload) return;\r\n\r\n appliedMetadataSource.current = current.payload;\r\n\r\n /*\r\n Keyed on the payload's identity, so this covers a refresh as well as a\r\n navigation: `refresh()` produces a NEW payload for the page already on\r\n screen, and a page whose metadata is a function of its loader data can\r\n legitimately re-title itself when that data changes. One applier at the\r\n one place the page changes, rather than a call in each pathway that could\r\n be forgotten in the next one.\r\n */\r\n applyDocumentMetadata(document, current.payload.metadata);\r\n }, [current.payload]);\r\n\r\n /*\r\n DURING RENDER, not in an effect, and that placement is the requirement\r\n rather than a shortcut. A page component calling `currentRoute()` does it\r\n while IT is rendering, and child effects run before a parent's, so anything\r\n recorded from an effect here would be recorded too late to answer the first\r\n render of the page it describes — which on the initial mount is the only\r\n render there has been, and the server's match is all there is.\r\n\r\n Recording is keyed on the payload's identity (`current-route.ts`), so the\r\n extra passes render gives us for free — StrictMode's double invoke, a parent\r\n re-render — are recognised as the same page rather than counted as\r\n navigations.\r\n\r\n `routeSource`, NOT `payload`: they are the same object for every navigation,\r\n and differ only after a refresh, which produces a new payload for the page\r\n already on screen and must not be counted as a move (see `refresh.ts`).\r\n */\r\n recordCurrentRoute(current.routeSource);\r\n\r\n /*\r\n An INNER DocumentContext provider, nested inside the one `hydratePage`\r\n mounted. That outer provider is created once with the hydration payload and\r\n never changes, so anything reading the document context after a navigation\r\n would see the payload of the page the user has left. The nearest provider\r\n wins, so this one keeps it current.\r\n */\r\n /*\r\n `metadata` from the PAYLOAD, not `undefined`. The document context is the\r\n universal shape — the server provides the resolved metadata around the same\r\n tree — so handing the client's readers `undefined` was a lie the payload can\r\n now correct. It also removes a latent mismatch: a `<Head/>` rendered inside\r\n a Layout (not the App level) renders its tags into `#root` server-side, and\r\n hydrating that markup against `metadata: undefined` produced a tree the\r\n server never rendered.\r\n */\r\n return (\r\n <DocumentContext.Provider\r\n value={{ metadata: current.payload.metadata, payload: current.payload }}\r\n >\r\n {current.tree}\r\n </DocumentContext.Provider>\r\n );\r\n}\r\n"],"mappings":";;;;;;;;;;;;;AAoDA,SAAS,QAAQ,WAAgC,KAAyB;CACxE,OAAO;EACL,UAAU,QAAQ,UAAU,IAAI,IAAI;EACpC,SAAQ,iBAAgB;GACtB,MAAM,UAAU,aAAa,cAAc,MAAM;GAEjD,QAAQ,aAAa,WAAW,GAAG;GAEnC,OAAO;EACT;EACA,QAAQ,SAAS,UAAU,QAAQ,aAAa,WAAW,KAAK;CAClE;AACF;AAEA,MAAM,YAAwB;CAC5B,UAAU;CACV,SAAQ,iBAAgB,aAAa,cAAc,OAAO;CAC1D,QAAQ,SAAS,UAAU;EACzB,QAAQ,cAAc;CACxB;AACF;AAEA,MAAM,gBAA4B;CAChC,UAAU;CACV,SAAQ,iBAAgB;EACtB,MAAM,UAAU,aAAa,cAAc,MAAM;EAEjD,QAAQ,aAAa,OAAO,WAAW;EAEvC,OAAO;CACT;CACA,QAAQ,SAAS,UAAU,QAAQ,aAAa,QAAQ,KAAK;AAC/D;;;;;;;;;;;;;AAcA,SAAS,mBACP,UACwD;CACxD,MAAM,WACJ,UAAU,aAAa,SACnB,SACA,MAAM,QAAQ,SAAS,QAAQ,IAC7B,SAAS,SAAS,KAAK,IAAI,IAC1B,SAAS;CA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QAAQ;CACe;AAE9B"}
@@ -1,6 +1,6 @@
1
1
  import { fetchPageData } from "./fetch-page-data.mjs";
2
2
 
3
- //#region ../web/src/client/navigation/prefetch.ts
3
+ //#region web/src/client/navigation/prefetch.ts
4
4
  /**
5
5
  * How many pages may be held at once.
6
6
  *
@@ -1 +1 @@
1
- {"version":3,"file":"prefetch.mjs","names":[],"sources":["../../../../../../../../web/src/client/navigation/prefetch.ts"],"sourcesContent":["/**\n * Speculative page data, fetched on hover and spent on the click that follows.\n *\n * A prefetch is a GUESS. The user pointed at a link; they may never click it.\n * Everything about this module follows from that one fact:\n *\n * - it never reports a failure — nobody asked for this request, so nobody may\n * be told it failed. A failed prefetch leaves the cache empty and the click\n * fetches for real, which is the behaviour we had before this file existed.\n * - it never delays a click. `prefetchPageData` is fire-and-forget; the\n * navigation path reads the cache synchronously and does not wait on it.\n * - it is BOUNDED and it EXPIRES. A cached payload is a copy of a page that\n * may already have changed, so it may only be served while it is very\n * probably still true.\n *\n * ## The read side is deliberately separate from the write side\n *\n * `<Link>` writes (on hover); the navigation runtime reads (on click). Neither\n * knows about the other — they share a URL, and this module is the only thing\n * between them. That is what lets prefetch be added without touching the\n * navigation state machine.\n */\nimport type { PageDataResult } from \"./fetch-page-data\";\nimport { fetchPageData } from \"./fetch-page-data\";\n\n/** A prefetch result worth keeping — only ever a successful payload. */\nexport type PrefetchedPageData = Extract<PageDataResult, { type: \"payload\" }>;\n\n/**\n * How many pages may be held at once.\n *\n * Ten, because the working set this serves is \"links the pointer has crossed in\n * the last few seconds\", which is small by construction — a nav bar, a card\n * grid the user is scanning. A page payload is loader data, not markup, but it\n * is still measured in tens of kilobytes, so an unbounded map on a long-lived\n * SPA session is a slow leak with no upper edge. Ten covers scanning a menu and\n * costs at most a few hundred kilobytes in the worst case.\n *\n * Eviction is by INSERTION ORDER, not by recency: an entry here is written once\n * and read at most once, so there is no recency to track — the oldest guess is\n * always the one least likely to be spent.\n */\nexport const PREFETCH_CACHE_LIMIT = 10;\n\n/**\n * How long a cached payload may be served, in milliseconds.\n *\n * Thirty seconds. This is a SAFETY bound and not a performance knob: the\n * interval this feature exists to cover is hover-to-click, which is well under\n * a second, and every millisecond beyond that is pure staleness risk. A payload\n * served after the user has changed the data behind it renders a wrong page —\n * silently, and with no way for them to tell. Thirty seconds is long enough\n * that a hesitant click still hits, and short enough that no realistic\n * \"navigate away, mutate something, come back\" flow can complete inside it.\n */\nexport const PREFETCH_TTL_MS = 30_000;\n\ntype CacheEntry = {\n result: PrefetchedPageData;\n /** `Date.now()` at which this entry stops being servable. */\n expiresAt: number;\n};\n\n/**\n * Insertion-ordered by `Map` contract, which is what makes eviction a `keys()\n * .next()` and not a bookkeeping structure.\n */\nconst cache = new Map<string, CacheEntry>();\n\n/**\n * URLs with a request already in the air. Repeated `mouseenter` events on the\n * same anchor are the norm, not the exception — a pointer crossing a link fires\n * as the user's hand settles — and without this each one would be its own\n * request for the same page.\n */\nconst inFlight = new Set<string>();\n\n/**\n * Whether there is a browser to prefetch from.\n *\n * Called rather than assumed because `<Link>` is universal: the same module\n * graph is evaluated during a server render, where a speculative request would\n * be a request the server makes to itself for a page nobody is looking at.\n */\nfunction isBrowser(): boolean {\n return typeof window !== \"undefined\";\n}\n\nfunction evictOldest(): void {\n const oldest = cache.keys().next();\n\n if (oldest.done !== true) cache.delete(oldest.value);\n}\n\n/**\n * Fetch a URL's page data ahead of the click, and cache it.\n *\n * NEVER REJECTS and never reports. The returned promise exists so a test can\n * await the speculative work; callers in the component tree discard it\n * (`void prefetchPageData(url)`) and must not await it — a click that waited on\n * a guess would be slower than one that never made it.\n *\n * The caller decides WHETHER a URL may be prefetched. This function does not\n * re-derive that: it has a URL and no way to tell an in-app path from a\n * cross-origin one it must never touch. `<Link>` gates on `isInApp`.\n */\nexport async function prefetchPageData(url: string): Promise<void> {\n if (!isBrowser()) return;\n\n if (inFlight.has(url)) return;\n\n // A fresh entry means the answer is already here; an expired one is dropped\n // now so the fetch below can replace it.\n const cached = cache.get(url);\n\n if (cached !== undefined) {\n if (cached.expiresAt > Date.now()) return;\n\n cache.delete(url);\n }\n\n inFlight.add(url);\n\n try {\n const result = await fetchPageData(url);\n\n /*\n `hard-navigate` is NOT cached. It is the signal that this URL needs a full\n page load — a 404, a redirect to an interstitial, a proxy that stripped\n the marker header. Caching it would mean the click either replays a\n failure or, worse, consults an entry that cannot be rendered. The click\n re-asks and gets the same answer, correctly, through the navigation path\n that already knows how to degrade.\n */\n if (result.type !== \"payload\") return;\n\n if (cache.size >= PREFETCH_CACHE_LIMIT) evictOldest();\n\n cache.set(url, { result, expiresAt: Date.now() + PREFETCH_TTL_MS });\n } catch {\n /*\n `fetchPageData` already converts every network failure into a\n `hard-navigate`, so reaching here means something unforeseen. It is\n swallowed anyway, deliberately and without a log: this request was\n speculative, the user never asked for it, and a console full of warnings\n about requests nobody made is how a helpful optimisation becomes noise\n that hides real errors.\n */\n } finally {\n // In `finally` so a failed attempt does not poison the URL for the rest of\n // the session — the next hover is allowed to try again.\n inFlight.delete(url);\n }\n}\n\n/**\n * Take the prefetched payload for a URL, if there is a live one.\n *\n * CONSUMING: the entry is removed whether or not the caller ends up using it.\n * One hover buys one saved round trip. Serving the same payload to a second\n * navigation would double the window in which it can be wrong, in exchange for\n * a saving the user did not notice the first time.\n *\n * @returns the cached result, or `undefined` — in which case the caller fetches\n * exactly as it did before this module existed.\n */\nexport function takePrefetchedPageData(url: string): PrefetchedPageData | undefined {\n const entry = cache.get(url);\n\n if (entry === undefined) return undefined;\n\n cache.delete(url);\n\n // Expiry is checked on READ, not on a timer: a timer would keep a\n // long-lived page waking up to clean a cache that is already bounded, and an\n // entry nobody reads costs nothing but the slot it is evicted from anyway.\n return entry.expiresAt > Date.now() ? entry.result : undefined;\n}\n\n/**\n * Drop everything. For tests, and for any caller that knows the cached pages\n * are now wrong — the module-level cache would otherwise outlive a suite and\n * leak into the next one.\n */\nexport function resetPrefetchCache(): void {\n cache.clear();\n inFlight.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0CA,MAAa,uBAAuB;;;;;;;;;;;;AAapC,MAAa,kBAAkB;;;;;AAY/B,MAAM,wBAAQ,IAAI,IAAwB;;;;;;;AAQ1C,MAAM,2BAAW,IAAI,IAAY;;;;;;;;AASjC,SAAS,YAAqB;CAC5B,OAAO,OAAO,WAAW;AAC3B;AAEA,SAAS,cAAoB;CAC3B,MAAM,SAAS,MAAM,KAAK,CAAC,CAAC,KAAK;CAEjC,IAAI,OAAO,SAAS,MAAM,MAAM,OAAO,OAAO,KAAK;AACrD;;;;;;;;;;;;;AAcA,eAAsB,iBAAiB,KAA4B;CACjE,IAAI,CAAC,UAAU,GAAG;CAElB,IAAI,SAAS,IAAI,GAAG,GAAG;CAIvB,MAAM,SAAS,MAAM,IAAI,GAAG;CAE5B,IAAI,WAAW,QAAW;EACxB,IAAI,OAAO,YAAY,KAAK,IAAI,GAAG;EAEnC,MAAM,OAAO,GAAG;CAClB;CAEA,SAAS,IAAI,GAAG;CAEhB,IAAI;EACF,MAAM,SAAS,MAAM,cAAc,GAAG;EAUtC,IAAI,OAAO,SAAS,WAAW;EAE/B,IAAI,MAAM,YAA8B,YAAY;EAEpD,MAAM,IAAI,KAAK;GAAE;GAAQ,WAAW,KAAK,IAAI,IAAI;EAAgB,CAAC;CACpE,QAAQ,CASR,UAAU;EAGR,SAAS,OAAO,GAAG;CACrB;AACF;;;;;;;;;;;;AAaA,SAAgB,uBAAuB,KAA6C;CAClF,MAAM,QAAQ,MAAM,IAAI,GAAG;CAE3B,IAAI,UAAU,QAAW,OAAO;CAEhC,MAAM,OAAO,GAAG;CAKhB,OAAO,MAAM,YAAY,KAAK,IAAI,IAAI,MAAM,SAAS;AACvD"}
1
+ {"version":3,"file":"prefetch.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/client/navigation/prefetch.ts"],"sourcesContent":["/**\n * Speculative page data, fetched on hover and spent on the click that follows.\n *\n * A prefetch is a GUESS. The user pointed at a link; they may never click it.\n * Everything about this module follows from that one fact:\n *\n * - it never reports a failure — nobody asked for this request, so nobody may\n * be told it failed. A failed prefetch leaves the cache empty and the click\n * fetches for real, which is the behaviour we had before this file existed.\n * - it never delays a click. `prefetchPageData` is fire-and-forget; the\n * navigation path reads the cache synchronously and does not wait on it.\n * - it is BOUNDED and it EXPIRES. A cached payload is a copy of a page that\n * may already have changed, so it may only be served while it is very\n * probably still true.\n *\n * ## The read side is deliberately separate from the write side\n *\n * `<Link>` writes (on hover); the navigation runtime reads (on click). Neither\n * knows about the other — they share a URL, and this module is the only thing\n * between them. That is what lets prefetch be added without touching the\n * navigation state machine.\n */\nimport type { PageDataResult } from \"./fetch-page-data\";\nimport { fetchPageData } from \"./fetch-page-data\";\n\n/** A prefetch result worth keeping — only ever a successful payload. */\nexport type PrefetchedPageData = Extract<PageDataResult, { type: \"payload\" }>;\n\n/**\n * How many pages may be held at once.\n *\n * Ten, because the working set this serves is \"links the pointer has crossed in\n * the last few seconds\", which is small by construction — a nav bar, a card\n * grid the user is scanning. A page payload is loader data, not markup, but it\n * is still measured in tens of kilobytes, so an unbounded map on a long-lived\n * SPA session is a slow leak with no upper edge. Ten covers scanning a menu and\n * costs at most a few hundred kilobytes in the worst case.\n *\n * Eviction is by INSERTION ORDER, not by recency: an entry here is written once\n * and read at most once, so there is no recency to track — the oldest guess is\n * always the one least likely to be spent.\n */\nexport const PREFETCH_CACHE_LIMIT = 10;\n\n/**\n * How long a cached payload may be served, in milliseconds.\n *\n * Thirty seconds. This is a SAFETY bound and not a performance knob: the\n * interval this feature exists to cover is hover-to-click, which is well under\n * a second, and every millisecond beyond that is pure staleness risk. A payload\n * served after the user has changed the data behind it renders a wrong page —\n * silently, and with no way for them to tell. Thirty seconds is long enough\n * that a hesitant click still hits, and short enough that no realistic\n * \"navigate away, mutate something, come back\" flow can complete inside it.\n */\nexport const PREFETCH_TTL_MS = 30_000;\n\ntype CacheEntry = {\n result: PrefetchedPageData;\n /** `Date.now()` at which this entry stops being servable. */\n expiresAt: number;\n};\n\n/**\n * Insertion-ordered by `Map` contract, which is what makes eviction a `keys()\n * .next()` and not a bookkeeping structure.\n */\nconst cache = new Map<string, CacheEntry>();\n\n/**\n * URLs with a request already in the air. Repeated `mouseenter` events on the\n * same anchor are the norm, not the exception — a pointer crossing a link fires\n * as the user's hand settles — and without this each one would be its own\n * request for the same page.\n */\nconst inFlight = new Set<string>();\n\n/**\n * Whether there is a browser to prefetch from.\n *\n * Called rather than assumed because `<Link>` is universal: the same module\n * graph is evaluated during a server render, where a speculative request would\n * be a request the server makes to itself for a page nobody is looking at.\n */\nfunction isBrowser(): boolean {\n return typeof window !== \"undefined\";\n}\n\nfunction evictOldest(): void {\n const oldest = cache.keys().next();\n\n if (oldest.done !== true) cache.delete(oldest.value);\n}\n\n/**\n * Fetch a URL's page data ahead of the click, and cache it.\n *\n * NEVER REJECTS and never reports. The returned promise exists so a test can\n * await the speculative work; callers in the component tree discard it\n * (`void prefetchPageData(url)`) and must not await it — a click that waited on\n * a guess would be slower than one that never made it.\n *\n * The caller decides WHETHER a URL may be prefetched. This function does not\n * re-derive that: it has a URL and no way to tell an in-app path from a\n * cross-origin one it must never touch. `<Link>` gates on `isInApp`.\n */\nexport async function prefetchPageData(url: string): Promise<void> {\n if (!isBrowser()) return;\n\n if (inFlight.has(url)) return;\n\n // A fresh entry means the answer is already here; an expired one is dropped\n // now so the fetch below can replace it.\n const cached = cache.get(url);\n\n if (cached !== undefined) {\n if (cached.expiresAt > Date.now()) return;\n\n cache.delete(url);\n }\n\n inFlight.add(url);\n\n try {\n const result = await fetchPageData(url);\n\n /*\n `hard-navigate` is NOT cached. It is the signal that this URL needs a full\n page load — a 404, a redirect to an interstitial, a proxy that stripped\n the marker header. Caching it would mean the click either replays a\n failure or, worse, consults an entry that cannot be rendered. The click\n re-asks and gets the same answer, correctly, through the navigation path\n that already knows how to degrade.\n */\n if (result.type !== \"payload\") return;\n\n if (cache.size >= PREFETCH_CACHE_LIMIT) evictOldest();\n\n cache.set(url, { result, expiresAt: Date.now() + PREFETCH_TTL_MS });\n } catch {\n /*\n `fetchPageData` already converts every network failure into a\n `hard-navigate`, so reaching here means something unforeseen. It is\n swallowed anyway, deliberately and without a log: this request was\n speculative, the user never asked for it, and a console full of warnings\n about requests nobody made is how a helpful optimisation becomes noise\n that hides real errors.\n */\n } finally {\n // In `finally` so a failed attempt does not poison the URL for the rest of\n // the session — the next hover is allowed to try again.\n inFlight.delete(url);\n }\n}\n\n/**\n * Take the prefetched payload for a URL, if there is a live one.\n *\n * CONSUMING: the entry is removed whether or not the caller ends up using it.\n * One hover buys one saved round trip. Serving the same payload to a second\n * navigation would double the window in which it can be wrong, in exchange for\n * a saving the user did not notice the first time.\n *\n * @returns the cached result, or `undefined` — in which case the caller fetches\n * exactly as it did before this module existed.\n */\nexport function takePrefetchedPageData(url: string): PrefetchedPageData | undefined {\n const entry = cache.get(url);\n\n if (entry === undefined) return undefined;\n\n cache.delete(url);\n\n // Expiry is checked on READ, not on a timer: a timer would keep a\n // long-lived page waking up to clean a cache that is already bounded, and an\n // entry nobody reads costs nothing but the slot it is evicted from anyway.\n return entry.expiresAt > Date.now() ? entry.result : undefined;\n}\n\n/**\n * Drop everything. For tests, and for any caller that knows the cached pages\n * are now wrong — the module-level cache would otherwise outlive a suite and\n * leak into the next one.\n */\nexport function resetPrefetchCache(): void {\n cache.clear();\n inFlight.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0CA,MAAa,uBAAuB;;;;;;;;;;;;AAapC,MAAa,kBAAkB;;;;;AAY/B,MAAM,wBAAQ,IAAI,IAAwB;;;;;;;AAQ1C,MAAM,2BAAW,IAAI,IAAY;;;;;;;;AASjC,SAAS,YAAqB;CAC5B,OAAO,OAAO,WAAW;AAC3B;AAEA,SAAS,cAAoB;CAC3B,MAAM,SAAS,MAAM,KAAK,EAAE,KAAK;CAEjC,IAAI,OAAO,SAAS,MAAM,MAAM,OAAO,OAAO,KAAK;AACrD;;;;;;;;;;;;;AAcA,eAAsB,iBAAiB,KAA4B;CACjE,IAAI,CAAC,UAAU,GAAG;CAElB,IAAI,SAAS,IAAI,GAAG,GAAG;CAIvB,MAAM,SAAS,MAAM,IAAI,GAAG;CAE5B,IAAI,WAAW,QAAW;EACxB,IAAI,OAAO,YAAY,KAAK,IAAI,GAAG;EAEnC,MAAM,OAAO,GAAG;CAClB;CAEA,SAAS,IAAI,GAAG;CAEhB,IAAI;EACF,MAAM,SAAS,MAAM,cAAc,GAAG;EAUtC,IAAI,OAAO,SAAS,WAAW;EAE/B,IAAI,MAAM,YAA8B,YAAY;EAEpD,MAAM,IAAI,KAAK;GAAE;GAAQ,WAAW,KAAK,IAAI,IAAI;EAAgB,CAAC;CACpE,QAAQ,CASR,UAAU;EAGR,SAAS,OAAO,GAAG;CACrB;AACF;;;;;;;;;;;;AAaA,SAAgB,uBAAuB,KAA6C;CAClF,MAAM,QAAQ,MAAM,IAAI,GAAG;CAE3B,IAAI,UAAU,QAAW,OAAO;CAEhC,MAAM,OAAO,GAAG;CAKhB,OAAO,MAAM,YAAY,KAAK,IAAI,IAAI,MAAM,SAAS;AACvD"}
@@ -1,6 +1,6 @@
1
1
  import { ReactNode } from "react";
2
2
 
3
- //#region ../web/src/client/navigation/refresh.d.ts
3
+ //#region web/src/client/navigation/refresh.d.ts
4
4
  /**
5
5
  * Re-fetch the current route's data and re-render the page with it.
6
6
  *
@@ -2,7 +2,7 @@ import { hydrateShared } from "../../shared.mjs";
2
2
  import { fetchPageData } from "./fetch-page-data.mjs";
3
3
  import { routerEvents } from "../../routing/router-events.mjs";
4
4
 
5
- //#region ../web/src/client/navigation/refresh.ts
5
+ //#region web/src/client/navigation/refresh.ts
6
6
  /**
7
7
  * A refresh is a "replace" as far as history and its listeners are concerned:
8
8
  * no entry is pushed, and one may be replaced when the server redirects.
@@ -1 +1 @@
1
- {"version":3,"file":"refresh.mjs","names":[],"sources":["../../../../../../../../web/src/client/navigation/refresh.ts"],"sourcesContent":["import type { ReactNode } from \"react\";\nimport type { HydrationDocumentPayloadSource } from \"../../hydration-payload\";\nimport { routerEvents } from \"../../routing/router-events\";\nimport { hydrateShared } from \"../../shared\";\nimport { fetchPageData } from \"./fetch-page-data\";\n\n/**\n * Re-run the current route's loaders and re-render it — under MRR's name.\n *\n * ## The name is MRR's; the behaviour is deliberately stronger\n *\n * `@mongez/react-router`'s `refresh()` re-RENDERS the current route: it is a\n * CSR router, all the data is already in the browser, and there is nothing to\n * go and get. Warlock's page data comes from the server, so re-rendering alone\n * would show the user exactly what they were already looking at. This\n * `refresh()` therefore re-FETCHES first — the same `x-warlock-data` request a\n * client navigation makes — and then swaps the page in. Strictly more than the\n * name promises elsewhere, never less, which is why the name could be kept.\n *\n * That difference is stated on {@link refresh} itself and not only here,\n * because the developer who needs to know it is the one hovering the symbol.\n *\n * ## Why the failure mode is the opposite of a navigation's\n *\n * `fetch-page-data.ts` degrades EVERY failure to a real browser load, and that\n * is right for a navigation: the user asked to go somewhere and must arrive.\n * A refresh is the opposite situation — the user is already where they want to\n * be. Handing the URL to `window.location.assign` would throw away their scroll\n * position, their open dialogs and the form they just posted from, in exchange\n * for data they only asked to update. So a failed refresh keeps the page\n * exactly as it is and announces the error; the screen the user has is never\n * the price of a network blip.\n *\n * ## Not server actions\n *\n * The mutation is an ordinary POST to the API, and this is what you call after\n * it. Nothing here writes; nothing here knows a mutation happened.\n */\n\n/**\n * The page on screen, as the navigation runtime holds it.\n *\n * `routeSource` is the reason this type is not simply `{ payload, tree }`. See\n * {@link createRefresher} for what it carries and why it is separate from\n * `payload`.\n */\nexport type RefreshablePage = {\n /** What the tree was built from — what the document context reports. */\n payload: HydrationDocumentPayloadSource;\n /** The rendered page. */\n tree: ReactNode;\n /**\n * The payload object `current-route.ts` identifies the current ROUTE by,\n * which is the same object as `payload` after a navigation but NOT after a\n * refresh.\n */\n routeSource: HydrationDocumentPayloadSource;\n};\n\n/**\n * Everything a refresh needs that only `NavigationRoot` can provide.\n *\n * Injected rather than reached for, and kept to four members: the page on\n * screen, the swap, the tree builder, and the race counter. Everything else a\n * refresh does — the request, the shared snapshot, the address bar, the\n * lifecycle events — is this module's own and is not injected, so a test\n * exercises the real ones.\n */\nexport type RefreshRuntime = {\n /** The page on screen at the moment it is asked for, never a captured copy. */\n readCurrent: () => RefreshablePage;\n /** Put a page on screen. */\n writeCurrent: (page: RefreshablePage) => void;\n /** How a payload becomes a tree, with the page registry already bound. */\n buildTree: (payload: HydrationDocumentPayloadSource) => Promise<ReactNode>;\n /**\n * Take a ticket from the navigation runtime's race counter.\n *\n * @returns a predicate that answers whether this operation is still the\n * newest one. THE SAME counter navigations take their tickets from — a\n * refresh and a navigation can overtake each other, so a second mechanism\n * would simply fail to notice.\n */\n claimTicket: () => () => boolean;\n};\n\n/**\n * What {@link refresh} delegates to once the runtime has connected itself.\n *\n * @returns `true` when fresh data is on screen. `false` covers every other\n * outcome — no runtime, no browser, the request failed, or a newer operation\n * overtook this one — and none of them left the page in a worse state than\n * they found it.\n */\nexport type Refresher = () => Promise<boolean>;\n\n/**\n * A refresh is a \"replace\" as far as history and its listeners are concerned:\n * no entry is pushed, and one may be replaced when the server redirects.\n */\nconst REFRESH_MODE = \"replace\" as const;\n\n/**\n * Build the runtime's refresher.\n *\n * Called by `NavigationRoot`, which connects the result with\n * {@link connectRefresher}. Not part of the public surface — a caller holding\n * its own refresher would be refreshing a page it does not own.\n *\n * ## The `routeSource` decision, which lives here\n *\n * `recordCurrentRoute` (`current-route.ts`) recognises a route by its payload\n * OBJECT IDENTITY: one swap is one payload object, which is what keeps a\n * StrictMode double render from counting as a navigation. A refresh breaks that\n * assumption on its own, because it produces a brand new payload object for the\n * page already on screen — so recording it would shift `previousRoute()` to the\n * page the user is currently looking at, and a \"back to where I came from\" link\n * would point at itself.\n *\n * So a refresh that came back as the SAME entry carries the previous\n * `routeSource` forward untouched: the fresh payload renders, and the route\n * does not move, because it did not. A refresh that came back as a DIFFERENT\n * entry — a session expiring into `/login` is the ordinary cause — is a real\n * move the server made, and is recorded as one; anything else would leave\n * `currentRoute()` naming a page that is no longer on screen.\n *\n * Comparing `name` here is not route matching (canon `9c8f878b`): both names\n * were decided by the server's router and merely travelled here. Nothing in\n * this file looks at a path.\n */\nexport function createRefresher(runtime: RefreshRuntime): Refresher {\n return async () => {\n // Not merely defensive: `refresh()` is importable from a universal module,\n // so a component can call it during the server render. There is no page on\n // screen to refresh there, and no address bar to read one from.\n if (typeof window === \"undefined\") return false;\n\n // The address bar IS the current route's URL — the runtime has already put\n // the resolved URL there — so there is no second copy to drift from it.\n const url = window.location.href;\n const isCurrent = runtime.claimTicket();\n\n routerEvents.emitNavigating({ url, mode: REFRESH_MODE });\n\n const result = await fetchPageData(url);\n\n // Superseded, and silently: this is the answer to a question the user\n // stopped asking. Not an error, and not an event — the operation that\n // overtook this one emits its own outcome.\n if (!isCurrent()) return false;\n\n if (result.type === \"hard-navigate\") {\n /*\n NO `window.location.assign` HERE, and this line is the whole point of\n the file. `fetchPageData` reports a hard navigation because that is the\n correct degradation for GOING somewhere; for STAYING somewhere it would\n destroy the screen the user already has in order to deliver data they\n asked to update. The page stays; the error is announced.\n */\n const error = new Error(`Warlock refresh failed: ${result.reason}`);\n\n console.warn(\"Warlock refresh could not re-fetch the current page:\", result.reason);\n routerEvents.emitNavigationError({ url, mode: REFRESH_MODE, error });\n\n return false;\n }\n\n let tree: ReactNode;\n\n try {\n tree = await runtime.buildTree(result.payload);\n } catch (error) {\n // A stale bundle after a deploy is the realistic cause. A navigation\n // reloads to fix it; a refresh cannot, for the same reason as above.\n console.warn(\"Warlock refresh could not build the page tree:\", error);\n routerEvents.emitNavigationError({ url, mode: REFRESH_MODE, error });\n\n return false;\n }\n\n if (!isCurrent()) return false;\n\n // Shared state BEFORE the render that consumes it, exactly as a navigation\n // does it — a refresh can carry a changed locale or a changed user too.\n hydrateShared(result.payload.shared);\n\n const previous = runtime.readCurrent();\n const sameEntry = result.payload.name === previous.payload.name;\n\n /*\n Only when the server actually moved us — `result.url` is the absolute URL\n the response came from and `url` came from the address bar, so they differ\n only when a redirect was followed. REPLACE even then: a refresh is not a\n destination, and pushing would make Back need two presses to leave a page\n the user never chose to visit twice.\n\n Keyed on the URL, not on `sameEntry`: the address bar's job is to name the\n URL on screen, and a redirect that stayed within one route entry\n (`?page=2` collapsing to `?page=1`) has still changed it.\n */\n if (result.url !== url) {\n window.history.replaceState(null, \"\", result.url);\n }\n\n runtime.writeCurrent({\n payload: result.payload,\n tree,\n routeSource: sameEntry ? previous.routeSource : result.payload,\n });\n\n routerEvents.emitNavigated({ url, resolvedUrl: result.url, mode: REFRESH_MODE });\n\n return true;\n };\n}\n\nlet connected: Refresher | undefined;\n\n/**\n * Installed by the navigation runtime at mount, and torn down with `undefined`.\n *\n * The same seam shape as `routing/navigator.ts`, and for the same reason:\n * {@link refresh} is universal and must not import the client runtime, so the\n * runtime registers itself instead.\n *\n * @returns the previous refresher, so a caller that installs one can restore\n * what was there.\n */\nexport function connectRefresher(next: Refresher | undefined): Refresher | undefined {\n const previous = connected;\n\n connected = next;\n\n return previous;\n}\n\n/**\n * Re-fetch the current route's data and re-render the page with it.\n *\n * What you call after a mutation — a normal POST to your API, then this — to\n * put the server's new truth on screen without a full reload. The layout stays\n * mounted, so scroll position, open menus and playing media survive.\n *\n * ## Stronger than the `refresh()` you may know\n *\n * `@mongez/react-router`'s `refresh()` only RE-RENDERS the current route. This\n * one RE-FETCHES the route's data first and then re-renders, because in Warlock\n * the data lives on the server and a re-render alone would show the user what\n * they are already looking at. Anywhere MRR's `refresh()` was correct, this is\n * too; it simply also picks up what changed.\n *\n * ## It cannot cost you the page\n *\n * If the request fails — offline, a 500, a proxy answering HTML — the page on\n * screen is left exactly as it was and `false` comes back. There is no reload\n * and no error screen. Subscribe to `routerEvents.onNavigationError` to show\n * the user something.\n *\n * ```ts\n * await api.post(\"/products\", form);\n *\n * if (!(await refresh())) toast.error(\"Could not reload the list.\");\n * ```\n *\n * @returns `true` when fresh data is on screen. `false` when nothing was\n * applied: no client runtime is connected (a server render, or before\n * hydration), the re-fetch failed, or a navigation overtook the refresh. Safe\n * to call in any of those — it never throws.\n */\nexport async function refresh(): Promise<boolean> {\n if (!connected) return false;\n\n return connected();\n}\n"],"mappings":";;;;;;;;;AAoGA,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BrB,SAAgB,gBAAgB,SAAoC;CAClE,OAAO,YAAY;EAIjB,IAAI,OAAO,WAAW,aAAa,OAAO;EAI1C,MAAM,MAAM,OAAO,SAAS;EAC5B,MAAM,YAAY,QAAQ,YAAY;EAEtC,aAAa,eAAe;GAAE;GAAK,MAAM;EAAa,CAAC;EAEvD,MAAM,SAAS,MAAM,cAAc,GAAG;EAKtC,IAAI,CAAC,UAAU,GAAG,OAAO;EAEzB,IAAI,OAAO,SAAS,iBAAiB;GAQnC,MAAM,wBAAQ,IAAI,MAAM,2BAA2B,OAAO,QAAQ;GAElE,QAAQ,KAAK,wDAAwD,OAAO,MAAM;GAClF,aAAa,oBAAoB;IAAE;IAAK,MAAM;IAAc;GAAM,CAAC;GAEnE,OAAO;EACT;EAEA,IAAI;EAEJ,IAAI;GACF,OAAO,MAAM,QAAQ,UAAU,OAAO,OAAO;EAC/C,SAAS,OAAO;GAGd,QAAQ,KAAK,kDAAkD,KAAK;GACpE,aAAa,oBAAoB;IAAE;IAAK,MAAM;IAAc;GAAM,CAAC;GAEnE,OAAO;EACT;EAEA,IAAI,CAAC,UAAU,GAAG,OAAO;EAIzB,cAAc,OAAO,QAAQ,MAAM;EAEnC,MAAM,WAAW,QAAQ,YAAY;EACrC,MAAM,YAAY,OAAO,QAAQ,SAAS,SAAS,QAAQ;EAa3D,IAAI,OAAO,QAAQ,KACjB,OAAO,QAAQ,aAAa,MAAM,IAAI,OAAO,GAAG;EAGlD,QAAQ,aAAa;GACnB,SAAS,OAAO;GAChB;GACA,aAAa,YAAY,SAAS,cAAc,OAAO;EACzD,CAAC;EAED,aAAa,cAAc;GAAE;GAAK,aAAa,OAAO;GAAK,MAAM;EAAa,CAAC;EAE/E,OAAO;CACT;AACF;AAEA,IAAI;;;;;;;;;;;AAYJ,SAAgB,iBAAiB,MAAoD;CACnF,MAAM,WAAW;CAEjB,YAAY;CAEZ,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,eAAsB,UAA4B;CAChD,IAAI,CAAC,WAAW,OAAO;CAEvB,OAAO,UAAU;AACnB"}
1
+ {"version":3,"file":"refresh.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/client/navigation/refresh.ts"],"sourcesContent":["import type { ReactNode } from \"react\";\nimport type { HydrationDocumentPayloadSource } from \"../../hydration-payload\";\nimport { routerEvents } from \"../../routing/router-events\";\nimport { hydrateShared } from \"../../shared\";\nimport { fetchPageData } from \"./fetch-page-data\";\n\n/**\n * Re-run the current route's loaders and re-render it — under MRR's name.\n *\n * ## The name is MRR's; the behaviour is deliberately stronger\n *\n * `@mongez/react-router`'s `refresh()` re-RENDERS the current route: it is a\n * CSR router, all the data is already in the browser, and there is nothing to\n * go and get. Warlock's page data comes from the server, so re-rendering alone\n * would show the user exactly what they were already looking at. This\n * `refresh()` therefore re-FETCHES first — the same `x-warlock-data` request a\n * client navigation makes — and then swaps the page in. Strictly more than the\n * name promises elsewhere, never less, which is why the name could be kept.\n *\n * That difference is stated on {@link refresh} itself and not only here,\n * because the developer who needs to know it is the one hovering the symbol.\n *\n * ## Why the failure mode is the opposite of a navigation's\n *\n * `fetch-page-data.ts` degrades EVERY failure to a real browser load, and that\n * is right for a navigation: the user asked to go somewhere and must arrive.\n * A refresh is the opposite situation — the user is already where they want to\n * be. Handing the URL to `window.location.assign` would throw away their scroll\n * position, their open dialogs and the form they just posted from, in exchange\n * for data they only asked to update. So a failed refresh keeps the page\n * exactly as it is and announces the error; the screen the user has is never\n * the price of a network blip.\n *\n * ## Not server actions\n *\n * The mutation is an ordinary POST to the API, and this is what you call after\n * it. Nothing here writes; nothing here knows a mutation happened.\n */\n\n/**\n * The page on screen, as the navigation runtime holds it.\n *\n * `routeSource` is the reason this type is not simply `{ payload, tree }`. See\n * {@link createRefresher} for what it carries and why it is separate from\n * `payload`.\n */\nexport type RefreshablePage = {\n /** What the tree was built from — what the document context reports. */\n payload: HydrationDocumentPayloadSource;\n /** The rendered page. */\n tree: ReactNode;\n /**\n * The payload object `current-route.ts` identifies the current ROUTE by,\n * which is the same object as `payload` after a navigation but NOT after a\n * refresh.\n */\n routeSource: HydrationDocumentPayloadSource;\n};\n\n/**\n * Everything a refresh needs that only `NavigationRoot` can provide.\n *\n * Injected rather than reached for, and kept to four members: the page on\n * screen, the swap, the tree builder, and the race counter. Everything else a\n * refresh does — the request, the shared snapshot, the address bar, the\n * lifecycle events — is this module's own and is not injected, so a test\n * exercises the real ones.\n */\nexport type RefreshRuntime = {\n /** The page on screen at the moment it is asked for, never a captured copy. */\n readCurrent: () => RefreshablePage;\n /** Put a page on screen. */\n writeCurrent: (page: RefreshablePage) => void;\n /** How a payload becomes a tree, with the page registry already bound. */\n buildTree: (payload: HydrationDocumentPayloadSource) => Promise<ReactNode>;\n /**\n * Take a ticket from the navigation runtime's race counter.\n *\n * @returns a predicate that answers whether this operation is still the\n * newest one. THE SAME counter navigations take their tickets from — a\n * refresh and a navigation can overtake each other, so a second mechanism\n * would simply fail to notice.\n */\n claimTicket: () => () => boolean;\n};\n\n/**\n * What {@link refresh} delegates to once the runtime has connected itself.\n *\n * @returns `true` when fresh data is on screen. `false` covers every other\n * outcome — no runtime, no browser, the request failed, or a newer operation\n * overtook this one — and none of them left the page in a worse state than\n * they found it.\n */\nexport type Refresher = () => Promise<boolean>;\n\n/**\n * A refresh is a \"replace\" as far as history and its listeners are concerned:\n * no entry is pushed, and one may be replaced when the server redirects.\n */\nconst REFRESH_MODE = \"replace\" as const;\n\n/**\n * Build the runtime's refresher.\n *\n * Called by `NavigationRoot`, which connects the result with\n * {@link connectRefresher}. Not part of the public surface — a caller holding\n * its own refresher would be refreshing a page it does not own.\n *\n * ## The `routeSource` decision, which lives here\n *\n * `recordCurrentRoute` (`current-route.ts`) recognises a route by its payload\n * OBJECT IDENTITY: one swap is one payload object, which is what keeps a\n * StrictMode double render from counting as a navigation. A refresh breaks that\n * assumption on its own, because it produces a brand new payload object for the\n * page already on screen — so recording it would shift `previousRoute()` to the\n * page the user is currently looking at, and a \"back to where I came from\" link\n * would point at itself.\n *\n * So a refresh that came back as the SAME entry carries the previous\n * `routeSource` forward untouched: the fresh payload renders, and the route\n * does not move, because it did not. A refresh that came back as a DIFFERENT\n * entry — a session expiring into `/login` is the ordinary cause — is a real\n * move the server made, and is recorded as one; anything else would leave\n * `currentRoute()` naming a page that is no longer on screen.\n *\n * Comparing `name` here is not route matching (canon `9c8f878b`): both names\n * were decided by the server's router and merely travelled here. Nothing in\n * this file looks at a path.\n */\nexport function createRefresher(runtime: RefreshRuntime): Refresher {\n return async () => {\n // Not merely defensive: `refresh()` is importable from a universal module,\n // so a component can call it during the server render. There is no page on\n // screen to refresh there, and no address bar to read one from.\n if (typeof window === \"undefined\") return false;\n\n // The address bar IS the current route's URL — the runtime has already put\n // the resolved URL there — so there is no second copy to drift from it.\n const url = window.location.href;\n const isCurrent = runtime.claimTicket();\n\n routerEvents.emitNavigating({ url, mode: REFRESH_MODE });\n\n const result = await fetchPageData(url);\n\n // Superseded, and silently: this is the answer to a question the user\n // stopped asking. Not an error, and not an event — the operation that\n // overtook this one emits its own outcome.\n if (!isCurrent()) return false;\n\n if (result.type === \"hard-navigate\") {\n /*\n NO `window.location.assign` HERE, and this line is the whole point of\n the file. `fetchPageData` reports a hard navigation because that is the\n correct degradation for GOING somewhere; for STAYING somewhere it would\n destroy the screen the user already has in order to deliver data they\n asked to update. The page stays; the error is announced.\n */\n const error = new Error(`Warlock refresh failed: ${result.reason}`);\n\n console.warn(\"Warlock refresh could not re-fetch the current page:\", result.reason);\n routerEvents.emitNavigationError({ url, mode: REFRESH_MODE, error });\n\n return false;\n }\n\n let tree: ReactNode;\n\n try {\n tree = await runtime.buildTree(result.payload);\n } catch (error) {\n // A stale bundle after a deploy is the realistic cause. A navigation\n // reloads to fix it; a refresh cannot, for the same reason as above.\n console.warn(\"Warlock refresh could not build the page tree:\", error);\n routerEvents.emitNavigationError({ url, mode: REFRESH_MODE, error });\n\n return false;\n }\n\n if (!isCurrent()) return false;\n\n // Shared state BEFORE the render that consumes it, exactly as a navigation\n // does it — a refresh can carry a changed locale or a changed user too.\n hydrateShared(result.payload.shared);\n\n const previous = runtime.readCurrent();\n const sameEntry = result.payload.name === previous.payload.name;\n\n /*\n Only when the server actually moved us — `result.url` is the absolute URL\n the response came from and `url` came from the address bar, so they differ\n only when a redirect was followed. REPLACE even then: a refresh is not a\n destination, and pushing would make Back need two presses to leave a page\n the user never chose to visit twice.\n\n Keyed on the URL, not on `sameEntry`: the address bar's job is to name the\n URL on screen, and a redirect that stayed within one route entry\n (`?page=2` collapsing to `?page=1`) has still changed it.\n */\n if (result.url !== url) {\n window.history.replaceState(null, \"\", result.url);\n }\n\n runtime.writeCurrent({\n payload: result.payload,\n tree,\n routeSource: sameEntry ? previous.routeSource : result.payload,\n });\n\n routerEvents.emitNavigated({ url, resolvedUrl: result.url, mode: REFRESH_MODE });\n\n return true;\n };\n}\n\nlet connected: Refresher | undefined;\n\n/**\n * Installed by the navigation runtime at mount, and torn down with `undefined`.\n *\n * The same seam shape as `routing/navigator.ts`, and for the same reason:\n * {@link refresh} is universal and must not import the client runtime, so the\n * runtime registers itself instead.\n *\n * @returns the previous refresher, so a caller that installs one can restore\n * what was there.\n */\nexport function connectRefresher(next: Refresher | undefined): Refresher | undefined {\n const previous = connected;\n\n connected = next;\n\n return previous;\n}\n\n/**\n * Re-fetch the current route's data and re-render the page with it.\n *\n * What you call after a mutation — a normal POST to your API, then this — to\n * put the server's new truth on screen without a full reload. The layout stays\n * mounted, so scroll position, open menus and playing media survive.\n *\n * ## Stronger than the `refresh()` you may know\n *\n * `@mongez/react-router`'s `refresh()` only RE-RENDERS the current route. This\n * one RE-FETCHES the route's data first and then re-renders, because in Warlock\n * the data lives on the server and a re-render alone would show the user what\n * they are already looking at. Anywhere MRR's `refresh()` was correct, this is\n * too; it simply also picks up what changed.\n *\n * ## It cannot cost you the page\n *\n * If the request fails — offline, a 500, a proxy answering HTML — the page on\n * screen is left exactly as it was and `false` comes back. There is no reload\n * and no error screen. Subscribe to `routerEvents.onNavigationError` to show\n * the user something.\n *\n * ```ts\n * await api.post(\"/products\", form);\n *\n * if (!(await refresh())) toast.error(\"Could not reload the list.\");\n * ```\n *\n * @returns `true` when fresh data is on screen. `false` when nothing was\n * applied: no client runtime is connected (a server render, or before\n * hydration), the re-fetch failed, or a navigation overtook the refresh. Safe\n * to call in any of those — it never throws.\n */\nexport async function refresh(): Promise<boolean> {\n if (!connected) return false;\n\n return connected();\n}\n"],"mappings":";;;;;;;;;AAoGA,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BrB,SAAgB,gBAAgB,SAAoC;CAClE,OAAO,YAAY;EAIjB,IAAI,OAAO,WAAW,aAAa,OAAO;EAI1C,MAAM,MAAM,OAAO,SAAS;EAC5B,MAAM,YAAY,QAAQ,YAAY;EAEtC,aAAa,eAAe;GAAE;GAAK,MAAM;EAAa,CAAC;EAEvD,MAAM,SAAS,MAAM,cAAc,GAAG;EAKtC,IAAI,CAAC,UAAU,GAAG,OAAO;EAEzB,IAAI,OAAO,SAAS,iBAAiB;GAQnC,MAAM,wBAAQ,IAAI,MAAM,2BAA2B,OAAO,QAAQ;GAElE,QAAQ,KAAK,wDAAwD,OAAO,MAAM;GAClF,aAAa,oBAAoB;IAAE;IAAK,MAAM;IAAc;GAAM,CAAC;GAEnE,OAAO;EACT;EAEA,IAAI;EAEJ,IAAI;GACF,OAAO,MAAM,QAAQ,UAAU,OAAO,OAAO;EAC/C,SAAS,OAAO;GAGd,QAAQ,KAAK,kDAAkD,KAAK;GACpE,aAAa,oBAAoB;IAAE;IAAK,MAAM;IAAc;GAAM,CAAC;GAEnE,OAAO;EACT;EAEA,IAAI,CAAC,UAAU,GAAG,OAAO;EAIzB,cAAc,OAAO,QAAQ,MAAM;EAEnC,MAAM,WAAW,QAAQ,YAAY;EACrC,MAAM,YAAY,OAAO,QAAQ,SAAS,SAAS,QAAQ;EAa3D,IAAI,OAAO,QAAQ,KACjB,OAAO,QAAQ,aAAa,MAAM,IAAI,OAAO,GAAG;EAGlD,QAAQ,aAAa;GACnB,SAAS,OAAO;GAChB;GACA,aAAa,YAAY,SAAS,cAAc,OAAO;EACzD,CAAC;EAED,aAAa,cAAc;GAAE;GAAK,aAAa,OAAO;GAAK,MAAM;EAAa,CAAC;EAE/E,OAAO;CACT;AACF;AAEA,IAAI;;;;;;;;;;;AAYJ,SAAgB,iBAAiB,MAAoD;CACnF,MAAM,WAAW;CAEjB,YAAY;CAEZ,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,eAAsB,UAA4B;CAChD,IAAI,CAAC,WAAW,OAAO;CAEvB,OAAO,UAAU;AACnB"}
@@ -0,0 +1,26 @@
1
+ import { fragmentTargetId } from "../../routing/url-fragment.mjs";
2
+
3
+ //#region web/src/client/navigation/scroll-to-fragment.ts
4
+ /**
5
+ * @param fragment the fragment WITHOUT its leading `#`, as
6
+ * `fragmentOf`/`samePageFragment` return it. Still percent-encoded — decoding
7
+ * is this function's job, via `fragmentTargetId`.
8
+ *
9
+ * @returns whether a target was found and scrolled to.
10
+ */
11
+ function scrollToFragment(documentNode, fragment) {
12
+ if (fragment === "") return false;
13
+ const id = fragmentTargetId(fragment);
14
+ const target = documentNode.getElementById(id) ?? namedAnchor(documentNode, id);
15
+ if (target === void 0 || target === null) return false;
16
+ target.scrollIntoView();
17
+ return true;
18
+ }
19
+ function namedAnchor(documentNode, name) {
20
+ const matches = documentNode.getElementsByName?.(name);
21
+ return matches === void 0 || matches.length === 0 ? void 0 : matches[0];
22
+ }
23
+
24
+ //#endregion
25
+ export { scrollToFragment };
26
+ //# sourceMappingURL=scroll-to-fragment.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scroll-to-fragment.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/client/navigation/scroll-to-fragment.ts"],"sourcesContent":["import { fragmentTargetId } from \"../../routing/url-fragment\";\n\n/**\n * Put the element a fragment names on screen — the browser's job, done by hand\n * because a client navigation never let the browser see the fragment.\n *\n * ## A fragment that matches nothing is NOT an error\n *\n * It does not throw, and — decided with it — it does not cause the fragment to\n * be dropped from the URL either. A browser loading `/docs#gone` shows\n * `#gone` in the address bar and leaves the page where it is; an id that has\n * not been added yet, or a page whose content moved, is an ordinary state of\n * the web and not something to report. So the return value says whether\n * anything was found, for a caller that wants to know, and every caller today\n * is free to ignore it.\n *\n * ## Why the document is an argument\n *\n * The suite runs with no DOM (`web/vitest.config.ts` — `environment: \"node\"`),\n * so a module that reached for the global `document` could only be proved in a\n * browser. The structural type below is satisfied by a real `Document` and by\n * three lines of test double, which is what makes the lookup rules provable at\n * all.\n */\n\n/** The two lookups, and nothing else this module needs from a `Document`. */\nexport type FragmentScrollDocument = {\n getElementById(id: string): { scrollIntoView(): void } | null;\n /**\n * The legacy anchor form, `<a name=\"install\">`, which browsers still honour\n * as a fragment target and older documentation pages are still full of.\n * Optional so a test double may leave it out.\n */\n getElementsByName?(name: string): ArrayLike<{ scrollIntoView(): void }>;\n};\n\n/**\n * @param fragment the fragment WITHOUT its leading `#`, as\n * `fragmentOf`/`samePageFragment` return it. Still percent-encoded — decoding\n * is this function's job, via `fragmentTargetId`.\n *\n * @returns whether a target was found and scrolled to.\n */\nexport function scrollToFragment(\n documentNode: FragmentScrollDocument,\n fragment: string,\n): boolean {\n // `/docs#` names no target. Nothing to look up, and nothing to move.\n if (fragment === \"\") return false;\n\n const id = fragmentTargetId(fragment);\n\n /*\n `getElementById`, never `querySelector(\"#\" + id)`. An id is allowed to\n contain characters that are not valid in a CSS selector — `#1`, `#a.b`,\n `#a b` — and `querySelector` THROWS on those rather than missing them, which\n would turn a link to a legal id into an exception in the middle of a\n navigation.\n */\n const target = documentNode.getElementById(id) ?? namedAnchor(documentNode, id);\n\n if (target === undefined || target === null) return false;\n\n target.scrollIntoView();\n\n return true;\n}\n\nfunction namedAnchor(\n documentNode: FragmentScrollDocument,\n name: string,\n): { scrollIntoView(): void } | undefined {\n const matches = documentNode.getElementsByName?.(name);\n\n return matches === undefined || matches.length === 0 ? undefined : matches[0];\n}\n"],"mappings":";;;;;;;;;;AA2CA,SAAgB,iBACd,cACA,UACS;CAET,IAAI,aAAa,IAAI,OAAO;CAE5B,MAAM,KAAK,iBAAiB,QAAQ;CASpC,MAAM,SAAS,aAAa,eAAe,EAAE,KAAK,YAAY,cAAc,EAAE;CAE9E,IAAI,WAAW,UAAa,WAAW,MAAM,OAAO;CAEpD,OAAO,eAAe;CAEtB,OAAO;AACT;AAEA,SAAS,YACP,cACA,MACwC;CACxC,MAAM,UAAU,aAAa,oBAAoB,IAAI;CAErD,OAAO,YAAY,UAAa,QAAQ,WAAW,IAAI,SAAY,QAAQ;AAC7E"}
@@ -1,4 +1,4 @@
1
- //#region ../web/src/client/navigation/verbs.d.ts
1
+ //#region web/src/client/navigation/verbs.d.ts
2
2
  /**
3
3
  * The history verbs, under the names MRR spells them
4
4
  * (`@mongez/react-router` — `src/utilities.tsx`).
@@ -1,6 +1,6 @@
1
1
  import { currentNavigator } from "../../routing/navigator.mjs";
2
2
 
3
- //#region ../web/src/client/navigation/verbs.ts
3
+ //#region web/src/client/navigation/verbs.ts
4
4
  /**
5
5
  * The history verbs, under the names MRR spells them
6
6
  * (`@mongez/react-router` — `src/utilities.tsx`).
@@ -1 +1 @@
1
- {"version":3,"file":"verbs.mjs","names":[],"sources":["../../../../../../../../web/src/client/navigation/verbs.ts"],"sourcesContent":["import { currentNavigator } from \"../../routing/navigator\";\n\n/**\n * The history verbs, under the names MRR spells them\n * (`@mongez/react-router` — `src/utilities.tsx`).\n *\n * A developer moving between a Mongez CSR app and a Warlock SSR app should not\n * relearn \"go there\" and \"go back\", so the names and call shapes are MRR's.\n * What is NOT MRR's is the mechanism: MRR's `navigateTo` reaches its router\n * singleton, and that singleton is the client-side matcher Warlock\n * deliberately does not have — the SERVER router is the only matcher\n * (canon `9c8f878b`). So `navigateTo` here delegates to the navigator the\n * client runtime registered, and knows nothing about paths beyond passing one\n * along.\n *\n * ## Why nothing in this file throws\n *\n * All three are importable from universal modules, which means all three can\n * be CALLED with no browser and no runtime: during the server render, and in\n * the gap between first paint and hydration. Each therefore has a defined\n * \"did nothing\" answer — `false`, a no-op, `\"\"` — instead of an exception.\n * Throwing here would cost the page rather than the navigation.\n */\n\n/**\n * Navigate to a path client-side.\n *\n * @param path where to go — passed through untouched; matching is the server's\n * job, so this is not parsed, resolved or prefixed here.\n * @param options `replace: true` swaps the current history entry instead of\n * pushing a new one, so Back skips it.\n * @returns `true` if the client runtime accepted the navigation. `false` means\n * nothing handled it — either no runtime is connected yet (server render, or\n * pre-hydration) or the runtime declined the URL. A `false` caller that needs\n * the user to arrive anyway should fall back to a real browser navigation.\n */\nexport function navigateTo(path: string, options?: { replace?: boolean }): boolean {\n const navigator = currentNavigator();\n\n if (!navigator) return false;\n\n return navigator(path, options);\n}\n\n/**\n * Go back one entry in browser history.\n *\n * This is the browser's own Back, not a re-navigation to a remembered URL, so\n * it restores scroll and forward history the way the button does. No-op\n * without a `window`.\n */\nexport function navigateBack(): void {\n if (typeof window === \"undefined\") return;\n\n window.history.back();\n}\n\n/**\n * @returns the current url's hash WITHOUT its leading `#` — MRR's shape, so\n * `getHash() === \"reviews\"` for `/products#reviews`. `\"\"` when there is no\n * hash, and `\"\"` rather than `undefined` when there is no `window`, so callers\n * can treat the result as a string unconditionally.\n */\nexport function getHash(): string {\n if (typeof window === \"undefined\") return \"\";\n\n return window.location.hash.replace(\"#\", \"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,WAAW,MAAc,SAA0C;CACjF,MAAM,YAAY,iBAAiB;CAEnC,IAAI,CAAC,WAAW,OAAO;CAEvB,OAAO,UAAU,MAAM,OAAO;AAChC;;;;;;;;AASA,SAAgB,eAAqB;CACnC,IAAI,OAAO,WAAW,aAAa;CAEnC,OAAO,QAAQ,KAAK;AACtB;;;;;;;AAQA,SAAgB,UAAkB;CAChC,IAAI,OAAO,WAAW,aAAa,OAAO;CAE1C,OAAO,OAAO,SAAS,KAAK,QAAQ,KAAK,EAAE;AAC7C"}
1
+ {"version":3,"file":"verbs.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/client/navigation/verbs.ts"],"sourcesContent":["import { currentNavigator } from \"../../routing/navigator\";\n\n/**\n * The history verbs, under the names MRR spells them\n * (`@mongez/react-router` — `src/utilities.tsx`).\n *\n * A developer moving between a Mongez CSR app and a Warlock SSR app should not\n * relearn \"go there\" and \"go back\", so the names and call shapes are MRR's.\n * What is NOT MRR's is the mechanism: MRR's `navigateTo` reaches its router\n * singleton, and that singleton is the client-side matcher Warlock\n * deliberately does not have — the SERVER router is the only matcher\n * (canon `9c8f878b`). So `navigateTo` here delegates to the navigator the\n * client runtime registered, and knows nothing about paths beyond passing one\n * along.\n *\n * ## Why nothing in this file throws\n *\n * All three are importable from universal modules, which means all three can\n * be CALLED with no browser and no runtime: during the server render, and in\n * the gap between first paint and hydration. Each therefore has a defined\n * \"did nothing\" answer — `false`, a no-op, `\"\"` — instead of an exception.\n * Throwing here would cost the page rather than the navigation.\n */\n\n/**\n * Navigate to a path client-side.\n *\n * @param path where to go — passed through untouched; matching is the server's\n * job, so this is not parsed, resolved or prefixed here.\n * @param options `replace: true` swaps the current history entry instead of\n * pushing a new one, so Back skips it.\n * @returns `true` if the client runtime accepted the navigation. `false` means\n * nothing handled it — either no runtime is connected yet (server render, or\n * pre-hydration) or the runtime declined the URL. A `false` caller that needs\n * the user to arrive anyway should fall back to a real browser navigation.\n */\nexport function navigateTo(path: string, options?: { replace?: boolean }): boolean {\n const navigator = currentNavigator();\n\n if (!navigator) return false;\n\n return navigator(path, options);\n}\n\n/**\n * Go back one entry in browser history.\n *\n * This is the browser's own Back, not a re-navigation to a remembered URL, so\n * it restores scroll and forward history the way the button does. No-op\n * without a `window`.\n */\nexport function navigateBack(): void {\n if (typeof window === \"undefined\") return;\n\n window.history.back();\n}\n\n/**\n * @returns the current url's hash WITHOUT its leading `#` — MRR's shape, so\n * `getHash() === \"reviews\"` for `/products#reviews`. `\"\"` when there is no\n * hash, and `\"\"` rather than `undefined` when there is no `window`, so callers\n * can treat the result as a string unconditionally.\n */\nexport function getHash(): string {\n if (typeof window === \"undefined\") return \"\";\n\n return window.location.hash.replace(\"#\", \"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,WAAW,MAAc,SAA0C;CACjF,MAAM,YAAY,iBAAiB;CAEnC,IAAI,CAAC,WAAW,OAAO;CAEvB,OAAO,UAAU,MAAM,OAAO;AAChC;;;;;;;;AASA,SAAgB,eAAqB;CACnC,IAAI,OAAO,WAAW,aAAa;CAEnC,OAAO,QAAQ,KAAK;AACtB;;;;;;;AAQA,SAAgB,UAAkB;CAChC,IAAI,OAAO,WAAW,aAAa,OAAO;CAE1C,OAAO,OAAO,SAAS,KAAK,QAAQ,KAAK,EAAE;AAC7C"}
@@ -1,4 +1,5 @@
1
+ import { registerModules } from "../../runtime/register-modules.mjs";
1
2
  import { ClientPageEntry, ClientProjectedModule, ClientRouteComposition, ClientRouteLoad, ClientRouteMatch, ClientRouteParams } from "./types.mjs";
2
3
  import { loadClientRouteComposition, validateClientRouteManifest } from "./manifest.mjs";
3
4
  import { matchClientRoute } from "./matcher.mjs";
4
- export { type ClientPageEntry, type ClientProjectedModule, type ClientRouteComposition, type ClientRouteLoad, type ClientRouteMatch, type ClientRouteParams, loadClientRouteComposition, matchClientRoute, validateClientRouteManifest };
5
+ export { type ClientPageEntry, type ClientProjectedModule, type ClientRouteComposition, type ClientRouteLoad, type ClientRouteMatch, type ClientRouteParams, loadClientRouteComposition, matchClientRoute, registerModules, validateClientRouteManifest };
@@ -1,4 +1,5 @@
1
+ import { registerModules } from "../../runtime/register-modules.mjs";
1
2
  import { loadClientRouteComposition, validateClientRouteManifest } from "./manifest.mjs";
2
3
  import { matchClientRoute } from "./matcher.mjs";
3
4
 
4
- export { loadClientRouteComposition, matchClientRoute, validateClientRouteManifest };
5
+ export { loadClientRouteComposition, matchClientRoute, registerModules, validateClientRouteManifest };
@@ -1,6 +1,6 @@
1
1
  import { ClientPageEntry, ClientRouteComposition } from "./types.mjs";
2
2
 
3
- //#region ../web/src/client/runtime/manifest.d.ts
3
+ //#region web/src/client/runtime/manifest.d.ts
4
4
  declare function validateClientRouteManifest(input: unknown): readonly ClientPageEntry[];
5
5
  declare function loadClientRouteComposition(entry: ClientPageEntry): Promise<ClientRouteComposition>;
6
6
  //#endregion
@@ -1,4 +1,4 @@
1
- //#region ../web/src/client/runtime/manifest.ts
1
+ //#region web/src/client/runtime/manifest.ts
2
2
  const ENTRY_KEYS = [
3
3
  "type",
4
4
  "name",
@@ -6,7 +6,7 @@ const ENTRY_KEYS = [
6
6
  "load"
7
7
  ];
8
8
  const COMPOSITION_REQUIRED_KEYS = ["Page", "layouts"];
9
- const COMPOSITION_OPTIONAL_KEYS = ["App"];
9
+ const COMPOSITION_OPTIONAL_KEYS = ["App", "ErrorPage"];
10
10
  function isNonArrayObject(value) {
11
11
  return typeof value === "object" && value !== null && !Array.isArray(value);
12
12
  }
@@ -53,6 +53,7 @@ function validateComposition(input) {
53
53
  validateProjectedModule(layout, `${label} layout at index ${index}`);
54
54
  });
55
55
  if (Object.prototype.hasOwnProperty.call(input, "App")) validateProjectedModule(input.App, `${label} App`);
56
+ if (Object.prototype.hasOwnProperty.call(input, "ErrorPage")) validateProjectedModule(input.ErrorPage, `${label} ErrorPage`);
56
57
  return input;
57
58
  }
58
59
  function validateClientRouteManifest(input) {
@@ -1 +1 @@
1
- {"version":3,"file":"manifest.mjs","names":[],"sources":["../../../../../../../../web/src/client/runtime/manifest.ts"],"sourcesContent":["import type {\n ClientPageEntry,\n ClientProjectedModule,\n ClientRouteComposition,\n} from \"./types\";\n\nconst ENTRY_KEYS = [\"type\", \"name\", \"path\", \"load\"] as const;\nconst COMPOSITION_REQUIRED_KEYS = [\"Page\", \"layouts\"] as const;\nconst COMPOSITION_OPTIONAL_KEYS = [\"App\"] as const;\n\ntype DataRecord = Record<PropertyKey, unknown>;\n\nfunction isNonArrayObject(value: unknown): value is DataRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction printableValue(value: unknown): string {\n if (typeof value === \"string\") return JSON.stringify(value);\n\n try {\n return String(value);\n } catch {\n return \"<unprintable>\";\n }\n}\n\nfunction assertExactDataKeys(\n value: DataRecord,\n requiredKeys: readonly string[],\n optionalKeys: readonly string[],\n label: string,\n): void {\n const allowedKeys = new Set([...requiredKeys, ...optionalKeys]);\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const ownKeys = Reflect.ownKeys(value);\n\n for (const key of ownKeys) {\n if (typeof key !== \"string\" || !allowedKeys.has(key)) {\n throw new TypeError(`${label} has unexpected own key ${JSON.stringify(String(key))}.`);\n }\n }\n\n for (const key of requiredKeys) {\n if (!Object.prototype.hasOwnProperty.call(descriptors, key)) {\n throw new TypeError(`${label} is missing own key ${JSON.stringify(key)}.`);\n }\n }\n\n for (const key of ownKeys) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor && !(\"value\" in descriptor)) {\n throw new TypeError(\n `${label} key ${JSON.stringify(String(key))} must be an own data property.`,\n );\n }\n }\n}\n\nfunction validateEntry(input: unknown, index: number): ClientPageEntry {\n const label = `Client route manifest entry at index ${index}`;\n\n if (!isNonArrayObject(input)) {\n throw new TypeError(`${label} must be a non-array object.`);\n }\n\n assertExactDataKeys(input, ENTRY_KEYS, [], label);\n\n if (input.type !== \"page\") {\n throw new TypeError(\n `${label} has unknown type ${printableValue(input.type)}; expected \"page\".`,\n );\n }\n\n if (typeof input.name !== \"string\" || input.name.trim().length === 0) {\n throw new TypeError(`${label} name must be a non-empty string.`);\n }\n\n if (typeof input.path !== \"string\" || input.path.trim().length === 0) {\n throw new TypeError(`${label} path must be a non-empty string.`);\n }\n\n if (typeof input.load !== \"function\") {\n throw new TypeError(`${label} load must be callable.`);\n }\n\n return input as ClientPageEntry;\n}\n\nfunction validateProjectedModule(input: unknown, label: string): ClientProjectedModule {\n if (!isNonArrayObject(input)) {\n throw new TypeError(`${label} must be a non-array module object.`);\n }\n\n return input;\n}\n\nfunction validateComposition(input: unknown): ClientRouteComposition {\n const label = \"Loaded client route composition\";\n\n if (!isNonArrayObject(input)) {\n throw new TypeError(`${label} must be a non-array object.`);\n }\n\n assertExactDataKeys(\n input,\n COMPOSITION_REQUIRED_KEYS,\n COMPOSITION_OPTIONAL_KEYS,\n label,\n );\n validateProjectedModule(input.Page, `${label} Page`);\n\n if (!Array.isArray(input.layouts)) {\n throw new TypeError(`${label} layouts must be an array.`);\n }\n\n input.layouts.forEach((layout, index) => {\n validateProjectedModule(layout, `${label} layout at index ${index}`);\n });\n\n if (Object.prototype.hasOwnProperty.call(input, \"App\")) {\n validateProjectedModule(input.App, `${label} App`);\n }\n\n return input as ClientRouteComposition;\n}\n\nexport function validateClientRouteManifest(input: unknown): readonly ClientPageEntry[] {\n if (!Array.isArray(input)) {\n throw new TypeError(\"Client route manifest must be an array.\");\n }\n\n const names = new Set<string>();\n const paths = new Set<string>();\n\n return input.map((candidate, index) => {\n const entry = validateEntry(candidate, index);\n\n if (names.has(entry.name)) {\n throw new TypeError(\n `Client route manifest has duplicate name ${JSON.stringify(entry.name)}.`,\n );\n }\n\n if (paths.has(entry.path)) {\n throw new TypeError(\n `Client route manifest has duplicate path ${JSON.stringify(entry.path)}.`,\n );\n }\n\n names.add(entry.name);\n paths.add(entry.path);\n return entry;\n });\n}\n\nexport async function loadClientRouteComposition(\n entry: ClientPageEntry,\n): Promise<ClientRouteComposition> {\n const loaded = await entry.load();\n return validateComposition(lo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wBAAQ,IAAI,IAAY;CAC9B,MAAM,wBAAQ,IAAI,IAAY;CAE9B,OAAO,MAAM,KAAK,WAAW,UAAU;EACrC,MAAM,QAAQ,cAAc,WAAW,KAAK;EAE5C,IAAI,MAAM,IAAI,MAAM,IAAI,GACtB,MAAM,IAAI,UACR,4CAA4C,KAAK,UAAU,MAAM,IAAI,EAAE,EACzE;EAGF,IAAI,MAAM,IAAI,MAAM,IAAI,GACtB,MAAM,IAAI,UACR,4CAA4C,KAAK,UAAU,MAAM,IAAI,EAAE,EACzE;EAGF,MAAM,IAAI,MAAM,IAAI;EACpB,MAAM,IAAI,MAAM,IAAI;EACpB,OAAO;CACT,CAAC;AACH;AAEA,eAAsB,2BACpB,OACiC;CAEjC,OAAO,oBAAoB,MADN,MAAM,KAAK,CACC;AACnC"}
1
+ {"version":3,"file":"manifest.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/client/runtime/manifest.ts"],"sourcesContent":["import type {\n ClientPageEntry,\n ClientProjectedModule,\n ClientRouteComposition,\n} from \"./types\";\n\nconst ENTRY_KEYS = [\"type\", \"name\", \"path\", \"load\"] as const;\nconst COMPOSITION_REQUIRED_KEYS = [\"Page\", \"layouts\"] as const;\nconst COMPOSITION_OPTIONAL_KEYS = [\"App\", \"ErrorPage\"] as const;\n\ntype DataRecord = Record<PropertyKey, unknown>;\n\nfunction isNonArrayObject(value: unknown): value is DataRecord {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction printableValue(value: unknown): string {\n if (typeof value === \"string\") return JSON.stringify(value);\n\n try {\n return String(value);\n } catch {\n return \"<unprintable>\";\n }\n}\n\nfunction assertExactDataKeys(\n value: DataRecord,\n requiredKeys: readonly string[],\n optionalKeys: readonly string[],\n label: string,\n): void {\n const allowedKeys = new Set([...requiredKeys, ...optionalKeys]);\n const descriptors = Object.getOwnPropertyDescriptors(value);\n const ownKeys = Reflect.ownKeys(value);\n\n for (const key of ownKeys) {\n if (typeof key !== \"string\" || !allowedKeys.has(key)) {\n throw new TypeError(`${label} has unexpected own key ${JSON.stringify(String(key))}.`);\n }\n }\n\n for (const key of requiredKeys) {\n if (!Object.prototype.hasOwnProperty.call(descriptors, key)) {\n throw new TypeError(`${label} is missing own key ${JSON.stringify(key)}.`);\n }\n }\n\n for (const key of ownKeys) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor && !(\"value\" in descriptor)) {\n throw new TypeError(\n `${label} key ${JSON.stringify(String(key))} must be an own data property.`,\n );\n }\n }\n}\n\nfunction validateEntry(input: unknown, index: number): ClientPageEntry {\n const label = `Client route manifest entry at index ${index}`;\n\n if (!isNonArrayObject(input)) {\n throw new TypeError(`${label} must be a non-array object.`);\n }\n\n assertExactDataKeys(input, ENTRY_KEYS, [], label);\n\n if (input.type !== \"page\") {\n throw new TypeError(\n `${label} has unknown type ${printableValue(input.type)}; expected \"page\".`,\n );\n }\n\n if (typeof input.name !== \"string\" || input.name.trim().length === 0) {\n throw new TypeError(`${label} name must be a non-empty string.`);\n }\n\n if (typeof input.path !== \"string\" || input.path.trim().length === 0) {\n throw new TypeError(`${label} path must be a non-empty string.`);\n }\n\n if (typeof input.load !== \"function\") {\n throw new TypeError(`${label} load must be callable.`);\n }\n\n return input as ClientPageEntry;\n}\n\nfunction validateProjectedModule(input: unknown, label: string): ClientProjectedModule {\n if (!isNonArrayObject(input)) {\n throw new TypeError(`${label} must be a non-array module object.`);\n }\n\n return input;\n}\n\nfunction validateComposition(input: unknown): ClientRouteComposition {\n const label = \"Loaded client route composition\";\n\n if (!isNonArrayObject(input)) {\n throw new TypeError(`${label} must be a non-array object.`);\n }\n\n assertExactDataKeys(\n input,\n COMPOSITION_REQUIRED_KEYS,\n COMPOSITION_OPTIONAL_KEYS,\n label,\n );\n validateProjectedModule(input.Page, `${label} Page`);\n\n if (!Array.isArray(input.layouts)) {\n throw new TypeError(`${label} layouts must be an array.`);\n }\n\n input.layouts.forEach((layout, index) => {\n validateProjectedModule(layout, `${label} layout at index ${index}`);\n });\n\n if (Object.prototype.hasOwnProperty.call(input, \"App\")) {\n validateProjectedModule(input.App, `${label} App`);\n }\n\n if (Object.prototype.hasOwnProperty.call(input, \"ErrorPage\")) {\n validateProjectedModule(input.ErrorPage, `${label} ErrorPage`);\n }\n\n return input as ClientRouteComposition;\n}\n\nexport function validateClientRouteManifest(input: unknown): readonly ClientPageEntry[] {\n if (!Array.isArray(input)) {\n throw new TypeError(\"Client route manifest must be an array.\");\n }\n\n const names = new Set<string>();\n const paths = new Set<string>();\n\n return input.map((candidate, index) => {\n const entry = validateEntry(candidate, index);\n\n if (names.has(entry.name)) {\n throw new TypeError(\n `Client route manifest has duplicate name ${JSON.stringify(entry.name)}.`,\n );\n }\n\n if (paths.has(entry.path)) {\n throw new TypeError(\n `Client route manifest has duplicate path ${JSON.stringify(entry.path)}.`,\n );\n }\n\n names.add(entry.name);\n paths.add(entry.path);\n return entry;\n });\n}\n\nexport async function loadClientRouteComposition(\n entry: ClientPageEntry,\n): Promise<ClientRouteComposition> {\n const loaded = await entry.load();\n return validateComposition(loaded);\n}\n"],"mappings":";AAMA,MAAM,aAAa;CAAC;CAAQ;CAAQ;CAAQ;AAAM;AAClD,MAAM,4BAA4B,CAAC,QAAQ,SAAS;AACpD,MAAM,4BAA4B,CAAC,OAAO,WAAW;AAIrD,SAAS,iBAAiB,OAAqC;CAC7D,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,eAAe,OAAwB;CAC9C,IAAI,OAAO,UAAU,UAAU,OAAO,KAAK,UAAU,KAAK;CAE1D,IAAI;EACF,OAAO,OAAO,KAAK;CACrB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,oBACP,OACA,cACA,cACA,OACM;CACN,MAAM,cAAc,IAAI,IAAI,CAAC,GAAG,cAAc,GAAG,YAAY,CAAC;CAC9D,MAAM,cAAc,OAAO,0BAA0B,KAAK;CAC1D,MAAM,UAAU,QAAQ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KAAK,CACC;AACnC"}
@@ -1,6 +1,18 @@
1
1
  import { ClientPageEntry, ClientRouteMatch } from "./types.mjs";
2
2
 
3
- //#region ../web/src/client/runtime/matcher.d.ts
3
+ //#region web/src/client/runtime/matcher.d.ts
4
+ /**
5
+ * @deprecated Do not adopt for new code. This client-side matcher duplicates the
6
+ * route grammar the server already evaluates, and divergence between the two is
7
+ * silent (wrong page, not an error). It is superseded by navigation consuming the
8
+ * server-returned page composition/page swap: the client requests loader data and
9
+ * the matched page's identity rides back on that same response.
10
+ *
11
+ * Delete only after the server-answered page swap is proven working in production
12
+ * use — not before. Deleting earlier leaves neither implementation in place.
13
+ * Removing this export (and the `@warlock.js/web/client/runtime` re-export) is a
14
+ * breaking change to a published subpath and must be announced as one.
15
+ */
4
16
  declare function matchClientRoute(entries: readonly ClientPageEntry[], pathname: string): ClientRouteMatch | null;
5
17
  //#endregion
6
18
  export { matchClientRoute };
@@ -1,4 +1,4 @@
1
- //#region ../web/src/client/runtime/matcher.ts
1
+ //#region web/src/client/runtime/matcher.ts
2
2
  const PARAMETER_NAME = /^[A-Za-z0-9_]+$/;
3
3
  const REGEXP_SPECIAL = /[.*+?^${}()|[\]\\]/g;
4
4
  function escapeRegExp(value) {
@@ -144,6 +144,18 @@ function compileRoutes(entries) {
144
144
  return route;
145
145
  }).sort(compareSpecificity);
146
146
  }
147
+ /**
148
+ * @deprecated Do not adopt for new code. This client-side matcher duplicates the
149
+ * route grammar the server already evaluates, and divergence between the two is
150
+ * silent (wrong page, not an error). It is superseded by navigation consuming the
151
+ * server-returned page composition/page swap: the client requests loader data and
152
+ * the matched page's identity rides back on that same response.
153
+ *
154
+ * Delete only after the server-answered page swap is proven working in production
155
+ * use — not before. Deleting earlier leaves neither implementation in place.
156
+ * Removing this export (and the `@warlock.js/web/client/runtime` re-export) is a
157
+ * breaking change to a published subpath and must be announced as one.
158
+ */
147
159
  function matchClientRoute(entries, pathname) {
148
160
  const routes = compileRoutes(entries);
149
161
  const sanitized = sanitizePathname(pathname);
@@ -1 +1 @@
1
- {"version":3,"file":"matcher.mjs","names":[],"sources":["../../../../../../../../web/src/client/runtime/matcher.ts"],"sourcesContent":["import type { ClientPageEntry, ClientRouteMatch } from \"./types\";\n\ntype RouteToken =\n | { readonly type: \"static\"; readonly value: string }\n | { readonly type: \"parameter\"; readonly name: string }\n | { readonly type: \"catch-all\" };\n\ntype CompiledRoute = {\n readonly entry: ClientPageEntry;\n readonly tokens: readonly RouteToken[];\n readonly parameterNames: readonly string[];\n readonly expression: RegExp;\n readonly collisionKey: string;\n};\n\ntype SanitizedPath = {\n readonly path: string;\n readonly shouldDecodeParameters: boolean;\n};\n\nconst PARAMETER_NAME = /^[A-Za-z0-9_]+$/;\nconst REGEXP_SPECIAL = /[.*+?^${}()|[\\]\\\\]/g;\n\nfunction escapeRegExp(value: string): string {\n return value.replace(REGEXP_SPECIAL, \"\\\\$&\");\n}\n\nfunction decodeReservedCharacter(high: string, low: string): string | null {\n const pair = `${high}${low}`.toUpperCase();\n const reserved: Readonly<Record<string, string>> = {\n \"23\": \"#\",\n \"24\": \"$\",\n \"25\": \"%\",\n \"26\": \"&\",\n \"2B\": \"+\",\n \"2C\": \",\",\n \"2F\": \"/\",\n \"3A\": \":\",\n \"3B\": \";\",\n \"3D\": \"=\",\n \"3F\": \"?\",\n \"40\": \"@\",\n };\n\n return reserved[pair] ?? null;\n}\n\nfunction sanitizePathname(pathname: string): SanitizedPath | null {\n if (typeof pathname !== \"string\" || !pathname.startsWith(\"/\")) {\n throw new Error(\"Client route pathname must start with '/'\");\n }\n\n let path = pathname;\n let shouldDecode = false;\n let shouldDecodeParameters = false;\n\n for (let index = 1; index < path.length; index++) {\n if (path[index] !== \"%\") continue;\n\n const high = path[index + 1] ?? \"\";\n const low = path[index + 2] ?? \"\";\n const reserved = decodeReservedCharacter(high, low);\n\n if (reserved === null) {\n shouldDecode = true;\n continue;\n }\n\n shouldDecodeParameters = true;\n if (reserved === \"%\") {\n path = `${path.slice(0, index + 1)}25${path.slice(index + 1)}`;\n shouldDecode = true;\n index += 2;\n }\n index += 2;\n }\n\n try {\n if (shouldDecode) path = decodeURI(path);\n } catch {\n return null;\n }\n\n if (path.length > 1 && path.endsWith(\"/\")) path = path.slice(0, -1);\n\n return { path, shouldDecodeParameters };\n}\n\nfunction decodeParameter(value: string): string {\n let decoded = \"\";\n\n for (let index = 0; index < value.length; index++) {\n if (value[index] !== \"%\") {\n decoded += value[index];\n continue;\n }\n\n const reserved = decodeReservedCharacter(value[index + 1] ?? \"\", value[index + 2] ?? \"\");\n if (reserved === null) return value;\n\n decoded += reserved;\n index += 2;\n }\n\n return decoded;\n}\n\nfunction parsePattern(entry: ClientPageEntry): CompiledRoute {\n const original = entry.path;\n const isExactRootCatchAll = original === \"*\";\n if (!isExactRootCatchAll && !original.startsWith(\"/\")) {\n throw new Error(`Client route pattern '${original}' must start with '/'`);\n }\n\n const pattern = original.length > 1 && original.endsWith(\"/\")\n ? original.slice(0, -1)\n : original;\n const segments = isExactRootCatchAll\n ? [\"*\"]\n : pattern === \"/\"\n ? []\n : pattern.slice(1).split(\"/\");\n const tokens: RouteToken[] = [];\n const parameterNames: string[] = [];\n\n for (let index = 0; index < segments.length; index++) {\n const segment = segments[index];\n if (!segment) {\n throw new Error(`Client route pattern '${original}' contains an empty segment`);\n }\n\n if (segment === \"*\") {\n if (index !== segments.length - 1) {\n throw new Error(`Client route pattern '${original}' has a non-terminal catch-all`);\n }\n tokens.push({ type: \"catch-all\" });\n parameterNames.push(\"*\");\n continue;\n }\n\n if (segment.startsWith(\":\")) {\n const name = segment.slice(1);\n if (!PARAMETER_NAME.test(name)) {\n throw new Error(`Client route pattern '${original}' has an unsupported parameter segment`);\n }\n if (parameterNames.includes(name)) {\n throw new Error(`Client route pattern '${original}' repeats parameter '${name}'`);\n }\n tokens.push({ type: \"parameter\", name });\n parameterNames.push(name);\n continue;\n }\n\n if (segment.includes(\":\") || segment.includes(\"*\") || segment.includes(\"?\") || segment.includes(\"%\")) {\n throw new Error(`Client route pattern '${original}' contains unsupported syntax`);\n }\n tokens.push({ type: \"static\", value: segment });\n }\n\n let source = \"^\";\n for (let index = 0; index < tokens.length; index++) {\n const token = tokens[index];\n if (token.type === \"static\") source += `/${escapeRegExp(token.value)}`;\n if (token.type === \"parameter\") source += \"/([^/]{1,100})\";\n if (token.type === \"catch-all\") {\n source += isExactRootCatchAll ? \"(.*)\" : index === 0 ? \"/(.*)\" : \"/(.+)\";\n }\n }\n if (tokens.length === 0) source += \"/\";\n source += \"$\";\n\n const collisionKey = tokens\n .map((token) => {\n if (token.type === \"static\") return `s:${token.value.toLowerCase()}`;\n if (token.type === \"parameter\") return \"p\";\n return \"w\";\n })\n .join(\"/\");\n\n return {\n entry,\n tokens,\n parameterNames,\n expression: new RegExp(source, \"i\"),\n collisionKey,\n };\n}\n\nfunction compareSpecificity(left: CompiledRoute, right: CompiledRoute): number {\n const rank = (token: RouteToken | undefined): number => {\n if (!token || token.type === \"static\") return 3;\n if (token.type === \"parameter\") return 2;\n return 1;\n };\n\n const length = Math.max(left.tokens.length, right.tokens.length);\n for (let index = 0; index < length; index++) {\n const difference = rank(right.tokens[index]) - rank(left.tokens[index]);\n if (difference !== 0) return difference;\n }\n return 0;\n}\n\nfunction compileRoutes(entries: readonly ClientPageEntry[]): readonly CompiledRoute[] {\n const collisions = new Map<string, ClientPageEntry>();\n const routes = entries.map((entry) => {\n const route = parsePattern(entry);\n const existing = collisions.get(route.collisionKey);\n if (existing) {\n throw new Error(\n `Client route patterns '${existing.path}' and '${entry.path}' collide under server matching`,\n );\n }\n collisions.set(route.collisionKey, entry);\n return route;\n });\n\n return routes.sort(compareSpecificity);\n}\n\nexport function matchClientRoute(\n entries: readonly ClientPageEntry[],\n pathname: string,\n): ClientRouteMatch | null {\n const routes = compileRoutes(entries);\n const sanitized = sanitizePathname(pathname);\n if (!sanitized) return null;\n\n for (const route of routes) {\n const match = route.expression.exec(sanitized.path);\n if (!match) continue;\n\n const params: Record<string, string> = {};\n for (let index = 0; index < route.parameterNames.length; index++) {\n const value = match[index + 1];\n params[route.parameterNames[index]] = sanitized.shouldDecodeParameters\n ? decodeParameter(value)\n : value;\n }\n return { entry: route.entry, params };\n }\n\n return null;\n}\n"],"mappings":";AAoBA,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AAEvB,SAAS,aAAa,OAAuB;CAC3C,OAAO,MAAM,QAAQ,gBAAgB,MAAM;AAC7C;AAEA,SAAS,wBAAwB,MAAc,KAA4B;CAiBzE,OAAO;EAdL,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;CAGM,EAhBD,GAAG,OAAO,MAAM,YAgBV,MAAM;AAC3B;AAEA,SAAS,iBAAiB,UAAwC;CAChE,IAAI,OAAO,aAAa,YAAY,CAAC,SAAS,WAAW,GAAG,GAC1D,MAAM,IAAI,MAAM,2CAA2C;CAG7D,IAAI,OAAO;CACX,IAAI,eAAe;CACnB,IAAI,yBAAyB;CAE7B,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS;EAChD,IAAI,KAAK,WAAW,KAAK;EAIzB,MAAM,WAAW,wBAFJ,KAAK,QAAQ,MAAM,IACpB,KAAK,QAAQ,MAAM,EACmB;EAElD,IAAI,aAAa,MAAM;GACrB,eAAe;GACf;EACF;EAEA,yBAAyB;EACzB,IAAI,aAAa,KAAK;GACpB,OAAO,GAAG,KAAK,MAAM,GAAG,QAAQ,CAAC,EAAE,IAAI,KAAK,MAAM,QAAQ,CAAC;GAC3D,eAAe;GACf,SAAS;EACX;EACA,SAAS;CACX;CAEA,IAAI;EACF,IAAI,cAAc,OAAO,UAAU,IAAI;CACzC,QAAQ;EACN,OAAO;CACT;CAEA,IAAI,KAAK,SAAS,KAAK,KAAK,SAAS,GAAG,GAAG,OAAO,KAAK,MAAM,GAAG,EAAE;CAElE,OAAO;EAA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AI,QAAQ,GAAG,QAAQ,QAAQ,SAAS;EAC3C,MAAM,aAAa,KAAK,MAAM,OAAO,MAAM,IAAI,KAAK,KAAK,OAAO,MAAM;EACtE,IAAI,eAAe,GAAG,OAAO;CAC/B;CACA,OAAO;AACT;AAEA,SAAS,cAAc,SAA+D;CACpF,MAAM,6BAAa,IAAI,IAA6B;CAapD,OAZe,QAAQ,KAAK,UAAU;EACpC,MAAM,QAAQ,aAAa,KAAK;EAChC,MAAM,WAAW,WAAW,IAAI,MAAM,YAAY;EAClD,IAAI,UACF,MAAM,IAAI,MACR,0BAA0B,SAAS,KAAK,SAAS,MAAM,KAAK,gCAC9D;EAEF,WAAW,IAAI,MAAM,cAAc,KAAK;EACxC,OAAO;CACT,CAEY,CAAC,CAAC,KAAK,kBAAkB;AACvC;AAEA,SAAgB,iBACd,SACA,UACyB;CACzB,MAAM,SAAS,cAAc,OAAO;CACpC,MAAM,YAAY,iBAAiB,QAAQ;CAC3C,IAAI,CAAC,WAAW,OAAO;CAEvB,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,QAAQ,MAAM,WAAW,KAAK,UAAU,IAAI;EAClD,IAAI,CAAC,OAAO;EAEZ,MAAM,SAAiC,CAAC;EACxC,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,eAAe,QAAQ,SAAS;GAChE,MAAM,QAAQ,MAAM,QAAQ;GAC5B,OAAO,MAAM,eAAe,UAAU,UAAU,yBAC5C,gBAAgB,KAAK,IACrB;EACN;EACA,OAAO;GAAE,OAAO,MAAM;GAAO;EAAO;CACtC;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"matcher.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/client/runtime/matcher.ts"],"sourcesContent":["import type { ClientPageEntry, ClientRouteMatch } from \"./types\";\n\ntype RouteToken =\n | { readonly type: \"static\"; readonly value: string }\n | { readonly type: \"parameter\"; readonly name: string }\n | { readonly type: \"catch-all\" };\n\ntype CompiledRoute = {\n readonly entry: ClientPageEntry;\n readonly tokens: readonly RouteToken[];\n readonly parameterNames: readonly string[];\n readonly expression: RegExp;\n readonly collisionKey: string;\n};\n\ntype SanitizedPath = {\n readonly path: string;\n readonly shouldDecodeParameters: boolean;\n};\n\nconst PARAMETER_NAME = /^[A-Za-z0-9_]+$/;\nconst REGEXP_SPECIAL = /[.*+?^${}()|[\\]\\\\]/g;\n\nfunction escapeRegExp(value: string): string {\n return value.replace(REGEXP_SPECIAL, \"\\\\$&\");\n}\n\nfunction decodeReservedCharacter(high: string, low: string): string | null {\n const pair = `${high}${low}`.toUpperCase();\n const reserved: Readonly<Record<string, string>> = {\n \"23\": \"#\",\n \"24\": \"$\",\n \"25\": \"%\",\n \"26\": \"&\",\n \"2B\": \"+\",\n \"2C\": \",\",\n \"2F\": \"/\",\n \"3A\": \":\",\n \"3B\": \";\",\n \"3D\": \"=\",\n \"3F\": \"?\",\n \"40\": \"@\",\n };\n\n return reserved[pair] ?? null;\n}\n\nfunction sanitizePathname(pathname: string): SanitizedPath | null {\n if (typeof pathname !== \"string\" || !pathname.startsWith(\"/\")) {\n throw new Error(\"Client route pathname must start with '/'\");\n }\n\n let path = pathname;\n let shouldDecode = false;\n let shouldDecodeParameters = false;\n\n for (let index = 1; index < path.length; index++) {\n if (path[index] !== \"%\") continue;\n\n const high = path[index + 1] ?? \"\";\n const low = path[index + 2] ?? \"\";\n const reserved = decodeReservedCharacter(high, low);\n\n if (reserved === null) {\n shouldDecode = true;\n continue;\n }\n\n shouldDecodeParameters = true;\n if (reserved === \"%\") {\n path = `${path.slice(0, index + 1)}25${path.slice(index + 1)}`;\n shouldDecode = true;\n index += 2;\n }\n index += 2;\n }\n\n try {\n if (shouldDecode) path = decodeURI(path);\n } catch {\n return null;\n }\n\n if (path.length > 1 && path.endsWith(\"/\")) path = path.slice(0, -1);\n\n return { path, shouldDecodeParameters };\n}\n\nfunction decodeParameter(value: string): string {\n let decoded = \"\";\n\n for (let index = 0; index < value.length; index++) {\n if (value[index] !== \"%\") {\n decoded += value[index];\n continue;\n }\n\n const reserved = decodeReservedCharacter(value[index + 1] ?? \"\", value[index + 2] ?? \"\");\n if (reserved === null) return value;\n\n decoded += reserved;\n index += 2;\n }\n\n return decoded;\n}\n\nfunction parsePattern(entry: ClientPageEntry): CompiledRoute {\n const original = entry.path;\n const isExactRootCatchAll = original === \"*\";\n if (!isExactRootCatchAll && !original.startsWith(\"/\")) {\n throw new Error(`Client route pattern '${original}' must start with '/'`);\n }\n\n const pattern = original.length > 1 && original.endsWith(\"/\")\n ? original.slice(0, -1)\n : original;\n const segments = isExactRootCatchAll\n ? [\"*\"]\n : pattern === \"/\"\n ? []\n : pattern.slice(1).split(\"/\");\n const tokens: RouteToken[] = [];\n const parameterNames: string[] = [];\n\n for (let index = 0; index < segments.length; index++) {\n const segment = segments[index];\n if (!segment) {\n throw new Error(`Client route pattern '${original}' contains an empty segment`);\n }\n\n if (segment === \"*\") {\n if (index !== segments.length - 1) {\n throw new Error(`Client route pattern '${original}' has a non-terminal catch-all`);\n }\n tokens.push({ type: \"catch-all\" });\n parameterNames.push(\"*\");\n continue;\n }\n\n if (segment.startsWith(\":\")) {\n const name = segment.slice(1);\n if (!PARAMETER_NAME.test(name)) {\n throw new Error(`Client route pattern '${original}' has an unsupported parameter segment`);\n }\n if (parameterNames.includes(name)) {\n throw new Error(`Client route pattern '${original}' repeats parameter '${name}'`);\n }\n tokens.push({ type: \"parameter\", name });\n parameterNames.push(name);\n continue;\n }\n\n if (segment.includes(\":\") || segment.includes(\"*\") || segment.includes(\"?\") || segment.includes(\"%\")) {\n throw new Error(`Client route pattern '${original}' contains unsupported syntax`);\n }\n tokens.push({ type: \"static\", value: segment });\n }\n\n let source = \"^\";\n for (let index = 0; index < tokens.length; index++) {\n const token = tokens[index];\n if (token.type === \"static\") source += `/${escapeRegExp(token.value)}`;\n if (token.type === \"parameter\") source += \"/([^/]{1,100})\";\n if (token.type === \"catch-all\") {\n source += isExactRootCatchAll ? \"(.*)\" : index === 0 ? \"/(.*)\" : \"/(.+)\";\n }\n }\n if (tokens.length === 0) source += \"/\";\n source += \"$\";\n\n const collisionKey = tokens\n .map((token) => {\n if (token.type === \"static\") return `s:${token.value.toLowerCase()}`;\n if (token.type === \"parameter\") return \"p\";\n return \"w\";\n })\n .join(\"/\");\n\n return {\n entry,\n tokens,\n parameterNames,\n expression: new RegExp(source, \"i\"),\n collisionKey,\n };\n}\n\nfunction compareSpecificity(left: CompiledRoute, right: CompiledRoute): number {\n const rank = (token: RouteToken | undefined): number => {\n if (!token || token.type === \"static\") return 3;\n if (token.type === \"parameter\") return 2;\n return 1;\n };\n\n const length = Math.max(left.tokens.length, right.tokens.length);\n for (let index = 0; index < length; index++) {\n const difference = rank(right.tokens[index]) - rank(left.tokens[index]);\n if (difference !== 0) return difference;\n }\n return 0;\n}\n\nfunction compileRoutes(entries: readonly ClientPageEntry[]): readonly CompiledRoute[] {\n const collisions = new Map<string, ClientPageEntry>();\n const routes = entries.map((entry) => {\n const route = parsePattern(entry);\n const existing = collisions.get(route.collisionKey);\n if (existing) {\n throw new Error(\n `Client route patterns '${existing.path}' and '${entry.path}' collide under server matching`,\n );\n }\n collisions.set(route.collisionKey, entry);\n return route;\n });\n\n return routes.sort(compareSpecificity);\n}\n\n/**\n * @deprecated Do not adopt for new code. This client-side matcher duplicates the\n * route grammar the server already evaluates, and divergence between the two is\n * silent (wrong page, not an error). It is superseded by navigation consuming the\n * server-returned page composition/page swap: the client requests loader data and\n * the matched page's identity rides back on that same response.\n *\n * Delete only after the server-answered page swap is proven working in production\n * use — not before. Deleting earlier leaves neither implementation in place.\n * Removing this export (and the `@warlock.js/web/client/runtime` re-export) is a\n * breaking change to a published subpath and must be announced as one.\n */\nexport function matchClientRoute(\n entries: readonly ClientPageEntry[],\n pathname: string,\n): ClientRouteMatch | null {\n const routes = compileRoutes(entries);\n const sanitized = sanitizePathname(pathname);\n if (!sanitized) return null;\n\n for (const route of routes) {\n const match = route.expression.exec(sanitized.path);\n if (!match) continue;\n\n const params: Record<string, string> = {};\n for (let index = 0; index < route.parameterNames.length; index++) {\n const value = match[index + 1];\n params[route.parameterNames[index]] = sanitized.shouldDecodeParameters\n ? decodeParameter(value)\n : value;\n }\n return { entry: route.entry, params };\n }\n\n return null;\n}\n"],"mappings":";AAoBA,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AAEvB,SAAS,aAAa,OAAuB;CAC3C,OAAO,MAAM,QAAQ,gBAAgB,MAAM;AAC7C;AAEA,SAAS,wBAAwB,MAAc,KAA4B;CAiBzE,OAAO;EAdL,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;CAGM,EAhBD,GAAG,OAAO,MAAM,YAgBV,MAAM;AAC3B;AAEA,SAAS,iBAAiB,UAAwC;CAChE,IAAI,OAAO,aAAa,YAAY,CAAC,SAAS,WAAW,GAAG,GAC1D,MAAM,IAAI,MAAM,2CAA2C;CAG7D,IAAI,OAAO;CACX,IAAI,eAAe;CACnB,IAAI,yBAAyB;CAE7B,KAAK,IAAI,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS;EAChD,IAAI,KAAK,WAAW,KAAK;EAIzB,MAAM,WAAW,wBAFJ,KAAK,QAAQ,MAAM,IACpB,KAAK,QAAQ,MAAM,EACmB;EAElD,IAAI,aAAa,MAAM;GACrB,eAAe;GACf;EACF;EAEA,yBAAyB;EACzB,IAAI,aAAa,KAAK;GACpB,OAAO,GAAG,KAAK,MAAM,GAAG,QAAQ,CAAC,EAAE,IAAI,KAAK,MAAM,QAAQ,CAAC;GAC3D,eAAe;GACf,SAAS;EACX;EACA,SAAS;CACX;CAEA,IAAI;EACF,IAAI,cAAc,OAAO,UAAU,IAAI;CACzC,QAAQ;EACN,OAAO;CACT;CAEA,IAAI,KAAK,SAAS,KAAK,KAAK,SAAS,GAAG,GAAG,OAAO,KAAK,MAAM,GAAG,EA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AAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,SAAS;EAC3C,MAAM,aAAa,KAAK,MAAM,OAAO,MAAM,IAAI,KAAK,KAAK,OAAO,MAAM;EACtE,IAAI,eAAe,GAAG,OAAO;CAC/B;CACA,OAAO;AACT;AAEA,SAAS,cAAc,SAA+D;CACpF,MAAM,6BAAa,IAAI,IAA6B;CAapD,OAZe,QAAQ,KAAK,UAAU;EACpC,MAAM,QAAQ,aAAa,KAAK;EAChC,MAAM,WAAW,WAAW,IAAI,MAAM,YAAY;EAClD,IAAI,UACF,MAAM,IAAI,MACR,0BAA0B,SAAS,KAAK,SAAS,MAAM,KAAK,gCAC9D;EAEF,WAAW,IAAI,MAAM,cAAc,KAAK;EACxC,OAAO;CACT,CAEY,EAAE,KAAK,kBAAkB;AACvC;;;;;;;;;;;;;AAcA,SAAgB,iBACd,SACA,UACyB;CACzB,MAAM,SAAS,cAAc,OAAO;CACpC,MAAM,YAAY,iBAAiB,QAAQ;CAC3C,IAAI,CAAC,WAAW,OAAO;CAEvB,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,QAAQ,MAAM,WAAW,KAAK,UAAU,IAAI;EAClD,IAAI,CAAC,OAAO;EAEZ,MAAM,SAAiC,CAAC;EACxC,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,eAAe,QAAQ,SAAS;GAChE,MAAM,QAAQ,MAAM,QAAQ;GAC5B,OAAO,MAAM,eAAe,UAAU,UAAU,yBAC5C,gBAAgB,KAAK,IACrB;EACN;EACA,OAAO;GAAE,OAAO,MAAM;GAAO;EAAO;CACtC;CAEA,OAAO;AACT"}
@@ -1,9 +1,22 @@
1
- //#region ../web/src/client/runtime/types.d.ts
2
- type ClientProjectedModule = Readonly<Record<string, unknown>>;
1
+ import { RegisterableModuleNamespace } from "../../runtime/register-modules.mjs";
2
+
3
+ //#region web/src/client/runtime/types.d.ts
4
+ /**
5
+ * A real ESM namespace returned by dynamic import(), retained so universal
6
+ * lifecycle exports and the default React component remain available together.
7
+ */
8
+ type ClientProjectedModule = Readonly<Record<string, unknown>> & RegisterableModuleNamespace;
3
9
  type ClientRouteComposition = {
4
10
  readonly Page: ClientProjectedModule;
5
11
  readonly layouts: readonly ClientProjectedModule[];
6
12
  readonly App?: ClientProjectedModule;
13
+ /**
14
+ * The app-owned error leaf projected for this route. Optional so registries
15
+ * produced before `error.page.tsx` support remain valid byte-for-shape.
16
+ * Presence does not create a route; the hydration payload decides whether
17
+ * the server rendered this module instead of `Page`.
18
+ */
19
+ readonly ErrorPage?: ClientProjectedModule;
7
20
  };
8
21
  type ClientRouteLoad = () => ClientRouteComposition | Promise<ClientRouteComposition>;
9
22
  type ClientPageEntry = {
@@ -3,7 +3,7 @@ import { Head } from "./head.mjs";
3
3
  import { Scripts } from "./scripts.mjs";
4
4
  import { jsx, jsxs } from "react/jsx-runtime";
5
5
 
6
- //#region ../web/src/components/default-app.tsx
6
+ //#region web/src/components/default-app.tsx
7
7
  /**
8
8
  * The framework's own root, used whenever an app defines no `root.tsx` (or
9
9
  * omits a default export). The framework's default App is ALSO a full
@@ -1 +1 @@
1
- {"version":3,"file":"default-app.mjs","names":[],"sources":["../../../../../../../web/src/components/default-app.tsx"],"sourcesContent":["import type { ReactElement, ReactNode } from \"react\";\nimport { useDocumentContext } from \"./document-context\";\nimport { Head } from \"./head\";\nimport { Scripts } from \"./scripts\";\n\nexport type DefaultAppProps = {\n children: ReactNode;\n};\n\n/**\n * The framework's own root, used whenever an app defines no `root.tsx` (or\n * omits a default export). The framework's default App is ALSO a full\n * document — so every page renders a complete `<html>` regardless of\n * whether the app customized its root. The app owns the document: when a\n * custom `root.tsx` exists (`v5/app/src/web/root.tsx` is that example), it is\n * fully responsible for `lang`/`dir`/`<Scripts nonce>`/providers/its own\n * `<head>` tags. Only when no custom App exists does this fallback supply\n * `lang`/`dir`/nonce itself, sourced from the framework's document-context\n * slots rather than any app-owned data.\n */\nexport default function DefaultApp({ children }: DefaultAppProps): ReactElement {\n const { lang, dir } = useDocumentContext(\"DefaultApp\");\n\n return (\n <html lang={lang} dir={dir}>\n <head>\n <Head />\n </head>\n <body>\n {/*\n The hydration mount point (documented previously as\n `render-page.ts`'s own hardcoded shell, now moved here since the\n root supplies the whole document itself). An app writing its own\n custom `root.tsx` is responsible for its own equivalent if it wants\n a stable hydration target — this default only covers the\n no-custom-root case.\n */}\n <div id=\"root\">{children}</div>\n {/* Prop-less: inherits the nonce slot via Scripts' own fallback\n (scripts.ts) rather than reading document-context twice here. */}\n <Scripts />\n </body>\n </html>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoBA,SAAwB,WAAW,EAAE,YAA2C;CAC9E,MAAM,EAAE,MAAM,QAAQ,mBAAmB,YAAY;CAErD,OACE,qBAAC,QAAD;EAAY;EAAW;YAAvB,CACE,oBAAC,QAAD,YACE,oBAAC,MAAD,CAAO,GACH,IACN,qBAAC,QAAD,aASE,oBAAC,OAAD;GAAK,IAAG;GAAQ;EAAc,IAG9B,oBAAC,SAAD,CAAU,EACN,IACF;;AAEV"}
1
+ {"version":3,"file":"default-app.mjs","names":[],"sources":["C:/Work/Warlock.js/web/src/components/default-app.tsx"],"sourcesContent":["import type { ReactElement, ReactNode } from \"react\";\nimport { useDocumentContext } from \"./document-context\";\nimport { Head } from \"./head\";\nimport { Scripts } from \"./scripts\";\n\nexport type DefaultAppProps = {\n children: ReactNode;\n};\n\n/**\n * The framework's own root, used whenever an app defines no `root.tsx` (or\n * omits a default export). The framework's default App is ALSO a full\n * document — so every page renders a complete `<html>` regardless of\n * whether the app customized its root. The app owns the document: when a\n * custom `root.tsx` exists (`v5/app/src/web/root.tsx` is that example), it is\n * fully responsible for `lang`/`dir`/`<Scripts nonce>`/providers/its own\n * `<head>` tags. Only when no custom App exists does this fallback supply\n * `lang`/`dir`/nonce itself, sourced from the framework's document-context\n * slots rather than any app-owned data.\n */\nexport default function DefaultApp({ children }: DefaultAppProps): ReactElement {\n const { lang, dir } = useDocumentContext(\"DefaultApp\");\n\n return (\n <html lang={lang} dir={dir}>\n <head>\n <Head />\n </head>\n <body>\n {/*\n The hydration mount point (documented previously as\n `render-page.ts`'s own hardcoded shell, now moved here since the\n root supplies the whole document itself). An app writing its own\n custom `root.tsx` is responsible for its own equivalent if it wants\n a stable hydration target — this default only covers the\n no-custom-root case.\n */}\n <div id=\"root\">{children}</div>\n {/* Prop-less: inherits the nonce slot via Scripts' own fallback\n (scripts.ts) rather than reading document-context twice here. */}\n <Scripts />\n </body>\n </html>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoBA,SAAwB,WAAW,EAAE,YAA2C;CAC9E,MAAM,EAAE,MAAM,QAAQ,mBAAmB,YAAY;CAErD,OACE,qBAAC,QAAD;EAAY;EAAW;YAAvB,CACE,oBAAC,QAAD,YACE,oBAAC,MAAD,CAAO,GACH,IACN,qBAAC,QAAD,aASE,oBAAC,OAAD;GAAK,IAAG;GAAQ;EAAc,IAG9B,oBAAC,SAAD,CAAU,EACN,IACF;;AAEV"}