@real-router/react 0.26.0 → 0.27.1

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 (80) hide show
  1. package/README.md +21 -2
  2. package/dist/cjs/{Await-whr-pcvo.d.ts → Await-D2oCO8nH.d.ts} +1 -1
  3. package/dist/cjs/{Await-whr-pcvo.d.ts.map → Await-D2oCO8nH.d.ts.map} +1 -1
  4. package/dist/cjs/{HttpStatusProvider-Dh6cMr95.d.ts → HttpStatusProvider-DfsVxZba.d.ts} +1 -1
  5. package/dist/cjs/{HttpStatusProvider-Dh6cMr95.d.ts.map → HttpStatusProvider-DfsVxZba.d.ts.map} +1 -1
  6. package/dist/cjs/{Link-tZAtICIG.js → Link-CyDwbrFA.js} +2 -2
  7. package/dist/cjs/{Link-tZAtICIG.js.map → Link-CyDwbrFA.js.map} +1 -1
  8. package/dist/cjs/{RouterErrorBoundary-BlJmaoyr.d.ts → RouterErrorBoundary-3UhUelqY.d.ts} +1 -1
  9. package/dist/cjs/{RouterErrorBoundary-BlJmaoyr.d.ts.map → RouterErrorBoundary-3UhUelqY.d.ts.map} +1 -1
  10. package/dist/cjs/RouterProvider-CPsCmrRw.js +2 -0
  11. package/dist/cjs/RouterProvider-CPsCmrRw.js.map +1 -0
  12. package/dist/cjs/RouterProvider-lgNarto1.d.ts +109 -0
  13. package/dist/cjs/RouterProvider-lgNarto1.d.ts.map +1 -0
  14. package/dist/cjs/{createHttpStatusSink-D_6IiR5E.js → createHttpStatusSink-ChfBL87y.js} +2 -2
  15. package/dist/cjs/{createHttpStatusSink-D_6IiR5E.js.map → createHttpStatusSink-ChfBL87y.js.map} +1 -1
  16. package/dist/cjs/index.d.ts +4 -4
  17. package/dist/cjs/index.js +1 -1
  18. package/dist/cjs/index.react-server.d.ts +2 -2
  19. package/dist/cjs/ink.d.ts +2 -2
  20. package/dist/cjs/ink.js +1 -1
  21. package/dist/cjs/legacy.d.ts +3 -3
  22. package/dist/cjs/legacy.js +1 -1
  23. package/dist/cjs/legacy.ssr.d.ts +2 -2
  24. package/dist/cjs/legacy.ssr.js +1 -1
  25. package/dist/cjs/ssr.d.ts +3 -3
  26. package/dist/cjs/ssr.js +1 -1
  27. package/dist/cjs/ssr.react-server.d.ts +2 -2
  28. package/dist/cjs/{useDeferred-DE5YUsfa.d.ts → useDeferred-2fAqMTwr.d.ts} +1 -1
  29. package/dist/cjs/{useDeferred-DE5YUsfa.d.ts.map → useDeferred-2fAqMTwr.d.ts.map} +1 -1
  30. package/dist/cjs/useRoute-D2vAzKWM.js +2 -0
  31. package/dist/cjs/{useRoute-Dudo2K_0.js.map → useRoute-D2vAzKWM.js.map} +1 -1
  32. package/dist/cjs/{useRouteEnter-gfy65W0D.d.ts → useRouteEnter-CqO9sPPD.d.ts} +1 -1
  33. package/dist/cjs/{useRouteEnter-gfy65W0D.d.ts.map → useRouteEnter-CqO9sPPD.d.ts.map} +1 -1
  34. package/dist/cjs/{useRouterTransition-BfayPs0h.d.ts → useRouterTransition-D5nwRENd.d.ts} +2 -2
  35. package/dist/cjs/{useRouterTransition-BfayPs0h.d.ts.map → useRouterTransition-D5nwRENd.d.ts.map} +1 -1
  36. package/dist/esm/{Await-qSmJ-ZuN.d.mts → Await-D2oCO8nH.d.mts} +1 -1
  37. package/dist/esm/{Await-qSmJ-ZuN.d.mts.map → Await-D2oCO8nH.d.mts.map} +1 -1
  38. package/dist/esm/{HttpStatusProvider-Cy9GSANm.d.mts → HttpStatusProvider-DfsVxZba.d.mts} +1 -1
  39. package/dist/esm/{HttpStatusProvider-Cy9GSANm.d.mts.map → HttpStatusProvider-DfsVxZba.d.mts.map} +1 -1
  40. package/dist/esm/{Link-wVA25zEV.mjs → Link-uERoM4yk.mjs} +2 -2
  41. package/dist/esm/{Link-wVA25zEV.mjs.map → Link-uERoM4yk.mjs.map} +1 -1
  42. package/dist/esm/{RouterErrorBoundary-C-MH_yrP.d.mts → RouterErrorBoundary-3UhUelqY.d.mts} +1 -1
  43. package/dist/esm/{RouterErrorBoundary-C-MH_yrP.d.mts.map → RouterErrorBoundary-3UhUelqY.d.mts.map} +1 -1
  44. package/dist/esm/RouterProvider-DCchvq4n.d.mts +109 -0
  45. package/dist/esm/RouterProvider-DCchvq4n.d.mts.map +1 -0
  46. package/dist/esm/RouterProvider-DgHypQTJ.mjs +2 -0
  47. package/dist/esm/RouterProvider-DgHypQTJ.mjs.map +1 -0
  48. package/dist/esm/{createHttpStatusSink-BXWVamHE.mjs → createHttpStatusSink-CCocjF4h.mjs} +2 -2
  49. package/dist/esm/{createHttpStatusSink-BXWVamHE.mjs.map → createHttpStatusSink-CCocjF4h.mjs.map} +1 -1
  50. package/dist/esm/index.d.mts +4 -4
  51. package/dist/esm/index.mjs +1 -1
  52. package/dist/esm/index.react-server.d.mts +2 -2
  53. package/dist/esm/ink.d.mts +2 -2
  54. package/dist/esm/ink.mjs +1 -1
  55. package/dist/esm/legacy.d.mts +3 -3
  56. package/dist/esm/legacy.mjs +1 -1
  57. package/dist/esm/legacy.ssr.d.mts +2 -2
  58. package/dist/esm/legacy.ssr.mjs +1 -1
  59. package/dist/esm/ssr.d.mts +3 -3
  60. package/dist/esm/ssr.mjs +1 -1
  61. package/dist/esm/ssr.react-server.d.mts +2 -2
  62. package/dist/esm/{useDeferred-B5Qy7ttQ.d.mts → useDeferred-2fAqMTwr.d.mts} +1 -1
  63. package/dist/esm/{useDeferred-B5Qy7ttQ.d.mts.map → useDeferred-2fAqMTwr.d.mts.map} +1 -1
  64. package/dist/esm/{useRoute-Bta1jyl2.mjs → useRoute-5MF3j-9P.mjs} +1 -1
  65. package/dist/esm/{useRoute-Bta1jyl2.mjs.map → useRoute-5MF3j-9P.mjs.map} +1 -1
  66. package/dist/esm/{useRouteEnter-CxjYofFa.d.mts → useRouteEnter-CqO9sPPD.d.mts} +1 -1
  67. package/dist/esm/{useRouteEnter-CxjYofFa.d.mts.map → useRouteEnter-CqO9sPPD.d.mts.map} +1 -1
  68. package/dist/esm/{useRouterTransition-CI1P95ZQ.d.mts → useRouterTransition-PCwA_qj1.d.mts} +2 -2
  69. package/dist/esm/{useRouterTransition-CI1P95ZQ.d.mts.map → useRouterTransition-PCwA_qj1.d.mts.map} +1 -1
  70. package/package.json +5 -5
  71. package/src/RouterProvider.tsx +29 -1
  72. package/dist/cjs/RouterProvider-DGrUfyLj.js +0 -2
  73. package/dist/cjs/RouterProvider-DGrUfyLj.js.map +0 -1
  74. package/dist/cjs/RouterProvider-DvC9mViF.d.ts +0 -48
  75. package/dist/cjs/RouterProvider-DvC9mViF.d.ts.map +0 -1
  76. package/dist/cjs/useRoute-Dudo2K_0.js +0 -2
  77. package/dist/esm/RouterProvider-D4B0f6wZ.mjs +0 -2
  78. package/dist/esm/RouterProvider-D4B0f6wZ.mjs.map +0 -1
  79. package/dist/esm/RouterProvider-D_ZlPVAC.d.mts +0 -48
  80. package/dist/esm/RouterProvider-D_ZlPVAC.d.mts.map +0 -1
package/README.md CHANGED
@@ -160,7 +160,7 @@ Navigation link with automatic active state detection. Re-renders only when its
160
160
  </nav>
161
161
  ```
162
162
 
163
- Tri-state: `undefined` preserves the current hash, `""` clears it, a value sets it. Active class is hash-aware — only the matching tab lights up. Live demo: [`examples/web/react/link-hash/`](../../examples/web/react/link-hash/). See the [Hash Fragment Support](https://github.com/greydragon888/real-router/wiki/Hash) wiki page for the full surface.
163
+ Tri-state: `undefined` preserves the current hash, `""` clears it, a value sets it. Active class is hash-aware — only the matching tab lights up. Live demo: [`examples/web/react/hash-examples/link-hash/`](../../examples/web/react/hash-examples/link-hash/). See the [Hash Fragment Support](https://github.com/greydragon888/real-router/wiki/Hash) wiki page for the full surface.
164
164
 
165
165
  ### `<RouteView>` (React 19.2+)
166
166
 
@@ -451,6 +451,25 @@ Opt-in preservation of scroll position across navigations:
451
451
 
452
452
  Restores scroll on back/forward, scrolls to top (or `#hash`) on push. Three modes: `"restore"` (default), `"top"`, `"native"`. Custom containers via `scrollContainer: () => HTMLElement | null`. Lifecycle tied to the provider — created on mount, destroyed on unmount. Under `@real-router/browser-plugin`, replace transitions now preserve scroll position and programmatic reloads restore from `sessionStorage` (portable via `state.transition.replace` / `state.transition.reload`). See [Scroll Restoration guide](https://github.com/greydragon888/real-router/wiki/Scroll-Restoration) for the full behaviour matrix.
453
453
 
454
+ ## Scroll Spy
455
+
456
+ Opt-in router-coordinated `IntersectionObserver` scroll spy — the URL hash tracks the topmost visible anchor as the user scrolls, syncing `state.context.url.hash` so sibling `<Link hash>` highlights stay current:
457
+
458
+ ```tsx
459
+ <RouterProvider
460
+ router={router}
461
+ scrollSpy={{ selector: "[id]:is(h2,h3)" }}
462
+ >
463
+ {/* Your app */}
464
+ </RouterProvider>
465
+ ```
466
+
467
+ Emits a forced same-route transition with `{ hash, replace: true, force: true, hashChange: true }` — the same write API as `<Link hash>` (#532), just with `replace: true` so the spy doesn't pollute history. Three anti-flicker gates: `isTransitioning` (skip emits during transitions), `coolingDown` (skip emits during smooth `scrollIntoView` after a `<Link hash>` click; cleared on `scrollend` or 500 ms timeout), and `selfEmitting` (the spy doesn't rate-limit itself). Hardcoded internals: `IntersectionObserver.threshold = 0`, rAF + 150 ms trailing debounce, MutationObserver re-observe debounced 250 ms.
468
+
469
+ Options: `{ selector: string, rootMargin?: string, scrollContainer?: () => HTMLElement | null }`. Default `rootMargin`: `"-20% 0px -60% 0px"` (anchor active when crossing the top 20% of the viewport). Empty `selector` / `undefined` = off. SSR / browsers without `IntersectionObserver` = NOOP. Requires `browser-plugin` or `navigation-plugin` (hash-plugin and memory-plugin → warn-once + NOOP — they don't claim `state.context.url`).
470
+
471
+ Live demo: [`examples/web/react/hash-examples/scroll-spy/`](../../examples/web/react/hash-examples/scroll-spy/) (12 sections, TOC sidebar, plugin & spy-mode switchers, 10 e2e scenarios). See [Scroll Spy guide](https://github.com/greydragon888/real-router/wiki/Scroll-Spy) for the full API surface and recipes.
472
+
454
473
  ## View Transitions
455
474
 
456
475
  Opt-in animated route transitions via the browser's [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API):
@@ -467,7 +486,7 @@ No-op on unsupported browsers (Firefox as of 2026-04, SSR). Customization is pur
467
486
 
468
487
  Full documentation: [Wiki](https://github.com/greydragon888/real-router/wiki)
469
488
 
470
- - [RouterProvider](https://github.com/greydragon888/real-router/wiki/RouterProvider) · [RouteView](https://github.com/greydragon888/real-router/wiki/RouteView) · [RouterErrorBoundary](https://github.com/greydragon888/real-router/wiki/RouterErrorBoundary) · [Link](https://github.com/greydragon888/real-router/wiki/Link) · [Scroll Restoration](https://github.com/greydragon888/real-router/wiki/Scroll-Restoration) · [View Transitions](https://github.com/greydragon888/real-router/wiki/View-Transitions)
489
+ - [RouterProvider](https://github.com/greydragon888/real-router/wiki/RouterProvider) · [RouteView](https://github.com/greydragon888/real-router/wiki/RouteView) · [RouterErrorBoundary](https://github.com/greydragon888/real-router/wiki/RouterErrorBoundary) · [Link](https://github.com/greydragon888/real-router/wiki/Link) · [Scroll Restoration](https://github.com/greydragon888/real-router/wiki/Scroll-Restoration) · [Scroll Spy](https://github.com/greydragon888/real-router/wiki/Scroll-Spy) · [View Transitions](https://github.com/greydragon888/real-router/wiki/View-Transitions)
471
490
  - [useRouter](https://github.com/greydragon888/real-router/wiki/useRouter) · [useRoute](https://github.com/greydragon888/real-router/wiki/useRoute) · [useRouteNode](https://github.com/greydragon888/real-router/wiki/useRouteNode) · [useNavigator](https://github.com/greydragon888/real-router/wiki/useNavigator) · [useRouteUtils](https://github.com/greydragon888/real-router/wiki/useRouteUtils) · [useRouterTransition](https://github.com/greydragon888/real-router/wiki/useRouterTransition) · [useRouteExit](https://github.com/greydragon888/real-router/wiki/useRouteExit) · [useRouteEnter](https://github.com/greydragon888/real-router/wiki/useRouteEnter)
472
491
 
473
492
  ## Examples
@@ -38,4 +38,4 @@ declare function Await<T = unknown>({
38
38
  }: AwaitProps<T>): ReactNode;
39
39
  //#endregion
40
40
  export { AwaitProps as n, Await as t };
41
- //# sourceMappingURL=Await-whr-pcvo.d.ts.map
41
+ //# sourceMappingURL=Await-D2oCO8nH.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Await-whr-pcvo.d.ts","names":[],"sources":["../../src/components/Await.tsx"],"mappings":";;;UAMiB,UAAA;;WAEN,IAAA;EAFgB;;EAAA,SAKhB,QAAA,GAAW,KAAA,EAAO,CAAA,KAAM,SAAS;AAAA;;;;;;;AAAA;AA2B5C;;;;;;;;;;;;;;;;;iBAAgB,KAAA,aAAA,CAAA;EACd,IAAA;EACA;AAAA,GACC,UAAA,CAAW,CAAA,IAAK,SAAA"}
1
+ {"version":3,"file":"Await-D2oCO8nH.d.ts","names":[],"sources":["../../src/components/Await.tsx"],"mappings":";;;UAMiB,UAAA;;WAEN,IAAA;EAFgB;;EAAA,SAKhB,QAAA,GAAW,KAAA,EAAO,CAAA,KAAM,SAAS;AAAA;;;;;;;AAAA;AA2B5C;;;;;;;;;;;;;;;;;iBAAgB,KAAA,aAAA,CAAA;EACd,IAAA;EACA;AAAA,GACC,UAAA,CAAW,CAAA,IAAK,SAAA"}
@@ -140,4 +140,4 @@ declare function HttpStatusProvider({
140
140
  }: HttpStatusProviderProps): ReactNode;
141
141
  //#endregion
142
142
  export { HttpStatusCode as a, StreamedProps as c, ClientOnly as d, ClientOnlyProps as f, createHttpStatusSink as i, ServerOnly as l, HttpStatusProviderProps as n, HttpStatusCodeProps as o, HttpStatusSink as r, Streamed as s, HttpStatusProvider as t, ServerOnlyProps as u };
143
- //# sourceMappingURL=HttpStatusProvider-Dh6cMr95.d.ts.map
143
+ //# sourceMappingURL=HttpStatusProvider-DfsVxZba.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"HttpStatusProvider-Dh6cMr95.d.ts","names":[],"sources":["../../src/components/ClientOnly.tsx","../../src/components/ServerOnly.tsx","../../src/components/Streamed.tsx","../../src/components/HttpStatusCode.tsx","../../src/utils/createHttpStatusSink.ts","../../src/components/HttpStatusProvider.tsx"],"mappings":";;;UAIiB,eAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,GAAW,SAAS;AAAA;AAAA,iBAGf,UAAA,CAAA;EACd,QAAA;EACA;AAAA,GACC,eAAA,GAAkB,SAAA;;;UCRJ,eAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,GAAW,SAAS;AAAA;AAAA,iBAGf,UAAA,CAAA;EACd,QAAA;EACA;AAAA,GACC,eAAA,GAAkB,SAAA;;;UCRJ,aAAA;;WAEN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,EAAU,SAAS;AAAA;;;;;;;AFDC;AAG/B;;;;;;;;;;iBEkBgB,QAAA,CAAA;EAAW,QAAA;EAAU;AAAA,GAAY,aAAA,GAAgB,SAAA;;;UCrBhD,mBAAA;;WAEN,IAAI;AAAA;;;;;;;;AHFgB;AAG/B;;;;;;;;;;;;;;;;AAG8B;;;;ACR9B;;;;;;;;;AAE+B;AAG/B;;;;;;;;iBEgDgB,cAAA,CAAA;EAAiB;AAAA,GAAQ,mBAAA,GAAsB,SAAA;;;;;;AHrD/D;;;;;;;;;AAE+B;AAG/B;;;;;;;UIWiB,cAAA;EACf,IAAI;AAAA;AAAA,iBAGU,oBAAA,CAAA,GAAwB,cAAc;;;UCjBrC,uBAAA;EAAA,SACN,IAAA,EAAM,cAAA;EAAA,SACN,QAAA,EAAU,SAAS;AAAA;AAAA,iBAGd,kBAAA,CAAA;EACd,IAAA;EACA;AAAA,GACC,uBAAA,GAA0B,SAAA"}
1
+ {"version":3,"file":"HttpStatusProvider-DfsVxZba.d.ts","names":[],"sources":["../../src/components/ClientOnly.tsx","../../src/components/ServerOnly.tsx","../../src/components/Streamed.tsx","../../src/components/HttpStatusCode.tsx","../../src/utils/createHttpStatusSink.ts","../../src/components/HttpStatusProvider.tsx"],"mappings":";;;UAIiB,eAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,GAAW,SAAS;AAAA;AAAA,iBAGf,UAAA,CAAA;EACd,QAAA;EACA;AAAA,GACC,eAAA,GAAkB,SAAA;;;UCRJ,eAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,GAAW,SAAS;AAAA;AAAA,iBAGf,UAAA,CAAA;EACd,QAAA;EACA;AAAA,GACC,eAAA,GAAkB,SAAA;;;UCRJ,aAAA;;WAEN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,EAAU,SAAS;AAAA;;;;;;;AFDC;AAG/B;;;;;;;;;;iBEkBgB,QAAA,CAAA;EAAW,QAAA;EAAU;AAAA,GAAY,aAAA,GAAgB,SAAA;;;UCrBhD,mBAAA;;WAEN,IAAI;AAAA;;;;;;;;AHFgB;AAG/B;;;;;;;;;;;;;;;;AAG8B;;;;ACR9B;;;;;;;;;AAE+B;AAG/B;;;;;;;;iBEgDgB,cAAA,CAAA;EAAiB;AAAA,GAAQ,mBAAA,GAAsB,SAAA;;;;;;AHrD/D;;;;;;;;;AAE+B;AAG/B;;;;;;;UIWiB,cAAA;EACf,IAAI;AAAA;AAAA,iBAGU,oBAAA,CAAA,GAAwB,cAAc;;;UCjBrC,uBAAA;EAAA,SACN,IAAA,EAAM,cAAA;EAAA,SACN,QAAA,EAAU,SAAS;AAAA;AAAA,iBAGd,kBAAA,CAAA;EACd,IAAA;EACA;AAAA,GACC,uBAAA,GAA0B,SAAA"}
@@ -1,2 +1,2 @@
1
- const e=require(`./useRoute-Dudo2K_0.js`),t=require(`./RouterProvider-DGrUfyLj.js`);let n=require(`react`),r=require(`react/jsx-runtime`);function i(e,n){return e.routeName===n.routeName&&e.className===n.className&&e.activeClassName===n.activeClassName&&e.activeStrict===n.activeStrict&&e.ignoreQueryParams===n.ignoreQueryParams&&e.onClick===n.onClick&&e.target===n.target&&e.style===n.style&&e.children===n.children&&e.hash===n.hash&&t.u(e.routeParams,n.routeParams)&&t.u(e.routeOptions,n.routeOptions)}const a=(0,n.memo)(({routeName:i,routeParams:a=e.r,routeOptions:o=e.n,className:s,activeClassName:c=`active`,activeStrict:l=!1,ignoreQueryParams:u=!0,hash:d,onClick:f,target:p,children:m,...h})=>{let g=t.p(),_=t.o(i,a,l,u,d),v=t.c(g,i,a,d===void 0?void 0:{hash:d}),y=e=>{f&&(f(e),e.defaultPrevented)||!t.d(e.nativeEvent)||p===`_blank`||(e.preventDefault(),t.l(g,i,a,d,o).catch(()=>{}))},b=(0,n.useMemo)(()=>t.s(_,c,s),[_,c,s]);return(0,r.jsx)(`a`,{...h,href:v,className:b,onClick:y,children:m})},i);a.displayName=`Link`,Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return a}});
2
- //# sourceMappingURL=Link-tZAtICIG.js.map
1
+ const e=require("./useRoute-D2vAzKWM.js"),t=require("./RouterProvider-CPsCmrRw.js");let n=require("react"),r=require("react/jsx-runtime");function i(e,n){return e.routeName===n.routeName&&e.className===n.className&&e.activeClassName===n.activeClassName&&e.activeStrict===n.activeStrict&&e.ignoreQueryParams===n.ignoreQueryParams&&e.onClick===n.onClick&&e.target===n.target&&e.style===n.style&&e.children===n.children&&e.hash===n.hash&&t.u(e.routeParams,n.routeParams)&&t.u(e.routeOptions,n.routeOptions)}const a=(0,n.memo)(({routeName:i,routeParams:a=e.r,routeOptions:o=e.n,className:s,activeClassName:c=`active`,activeStrict:l=!1,ignoreQueryParams:u=!0,hash:d,onClick:f,target:p,children:m,...h})=>{let g=t.p(),_=t.o(i,a,l,u,d),v=t.c(g,i,a,d===void 0?void 0:{hash:d}),y=e=>{f&&(f(e),e.defaultPrevented)||!t.d(e.nativeEvent)||p===`_blank`||(e.preventDefault(),t.l(g,i,a,d,o).catch(()=>{}))},b=(0,n.useMemo)(()=>t.s(_,c,s),[_,c,s]);return(0,r.jsx)(`a`,{...h,href:v,className:b,onClick:y,children:m})},i);a.displayName=`Link`,Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return a}});
2
+ //# sourceMappingURL=Link-CyDwbrFA.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Link-tZAtICIG.js","names":["shallowEqual","EMPTY_PARAMS","EMPTY_OPTIONS","useRouter","useIsActiveRoute","buildHref","shouldNavigate","buildActiveClassName"],"sources":["../../src/components/Link.tsx"],"sourcesContent":["import { memo, useMemo } from \"react\";\n\nimport { EMPTY_PARAMS, EMPTY_OPTIONS } from \"../constants\";\nimport {\n shouldNavigate,\n buildHref,\n buildActiveClassName,\n navigateWithHash,\n shallowEqual,\n} from \"../dom-utils\";\nimport { useIsActiveRoute } from \"../hooks/useIsActiveRoute\";\nimport { useRouter } from \"../hooks/useRouter\";\n\nimport type { LinkProps } from \"../types\";\nimport type { FC, MouseEvent } from \"react\";\n\nfunction areLinkPropsEqual(\n prev: Readonly<LinkProps>,\n next: Readonly<LinkProps>,\n): boolean {\n return (\n prev.routeName === next.routeName &&\n prev.className === next.className &&\n prev.activeClassName === next.activeClassName &&\n prev.activeStrict === next.activeStrict &&\n prev.ignoreQueryParams === next.ignoreQueryParams &&\n prev.onClick === next.onClick &&\n prev.target === next.target &&\n prev.style === next.style &&\n prev.children === next.children &&\n prev.hash === next.hash &&\n shallowEqual(prev.routeParams, next.routeParams) &&\n shallowEqual(prev.routeOptions, next.routeOptions)\n );\n}\n\nconst LinkImpl: FC<LinkProps> = ({\n routeName,\n routeParams = EMPTY_PARAMS,\n routeOptions = EMPTY_OPTIONS,\n className,\n activeClassName = \"active\",\n activeStrict = false,\n ignoreQueryParams = true,\n hash,\n onClick,\n target,\n children,\n ...props\n}) => {\n // memo + areLinkPropsEqual guarantees that on bail-out the component does\n // not render; on render, routeParams/routeOptions either changed reference\n // (true change) or comparator failed (e.g., BigInt fallback to identity),\n // so they're safe to use directly in hook deps.\n\n const router = useRouter();\n\n // When `hash` prop is set, active state requires both route AND hash to\n // match (#532). Without this, three tab links sharing routeName=\"settings\"\n // would all be marked active by route-name alone, defeating tab semantics.\n const isActive = useIsActiveRoute(\n routeName,\n routeParams,\n activeStrict,\n ignoreQueryParams,\n hash,\n );\n\n // No useMemo: outer memo()+shallowEqual prevents Link re-render unless a\n // prop actually changed. When this body runs, either `hash` differs from\n // last render or another prop changed — in both cases the `{ hash }` alloc\n // is unavoidable. The useMemo wrapper added one closure + deps slot per\n // render without saving an allocation.\n const hashOption = hash === undefined ? undefined : { hash };\n const href = buildHref(router, routeName, routeParams, hashOption);\n\n // useCallback was wasteful: 7 deps recreated the closure on every meaningful\n // render anyway, and `<a onClick>` does not benefit from a stable function\n // identity (no child-memo-bail-out chain past it). Inline arrow function is\n // what React Compiler emits automatically for this shape.\n const handleClick = (evt: MouseEvent<HTMLAnchorElement>) => {\n if (onClick) {\n onClick(evt);\n\n if (evt.defaultPrevented) {\n return;\n }\n }\n\n if (!shouldNavigate(evt.nativeEvent) || target === \"_blank\") {\n return;\n }\n\n evt.preventDefault();\n navigateWithHash(router, routeName, routeParams, hash, routeOptions).catch(\n () => {},\n );\n };\n\n // Memoize the joined class string. parseTokens + Set + join on every render\n // adds up on pages with N Links navigating frequently; deps cover every\n // input the function reads so cache invalidation is exact.\n const finalClassName = useMemo(\n () => buildActiveClassName(isActive, activeClassName, className),\n [isActive, activeClassName, className],\n );\n\n return (\n <a {...props} href={href} className={finalClassName} onClick={handleClick}>\n {children}\n </a>\n );\n};\n\nexport const Link: FC<LinkProps> = memo(LinkImpl, areLinkPropsEqual);\n\nLink.displayName = \"Link\";\n"],"mappings":"0IAgBA,SAAS,EACP,EACA,EACS,CACT,OACE,EAAK,YAAc,EAAK,WACxB,EAAK,YAAc,EAAK,WACxB,EAAK,kBAAoB,EAAK,iBAC9B,EAAK,eAAiB,EAAK,cAC3B,EAAK,oBAAsB,EAAK,mBAChC,EAAK,UAAY,EAAK,SACtB,EAAK,SAAW,EAAK,QACrB,EAAK,QAAU,EAAK,OACpB,EAAK,WAAa,EAAK,UACvB,EAAK,OAAS,EAAK,MACnBA,EAAAA,EAAa,EAAK,YAAa,EAAK,WAAW,GAC/CA,EAAAA,EAAa,EAAK,aAAc,EAAK,YAAY,CAErD,CAgFA,MAAa,GAAA,EAAA,EAAA,OA9EoB,CAC/B,YACA,cAAcC,EAAAA,EACd,eAAeC,EAAAA,EACf,YACA,kBAAkB,SAClB,eAAe,GACf,oBAAoB,GACpB,OACA,UACA,SACA,WACA,GAAG,KACC,CAMJ,IAAM,EAASC,EAAAA,EAAU,EAKnB,EAAWC,EAAAA,EACf,EACA,EACA,EACA,EACA,CACF,EAQM,EAAOC,EAAAA,EAAU,EAAQ,EAAW,EADvB,IAAS,IAAA,GAAY,IAAA,GAAY,CAAE,MAAK,CACM,EAM3D,EAAe,GAAuC,CACtD,IACF,EAAQ,CAAG,EAEP,EAAI,mBAKN,CAACC,EAAAA,EAAe,EAAI,WAAW,GAAK,IAAW,WAInD,EAAI,eAAe,EACnB,EAAA,EAAiB,EAAQ,EAAW,EAAa,EAAM,CAAY,EAAE,UAC7D,CAAC,CACT,EACF,EAKM,GAAA,EAAA,EAAA,aACEC,EAAAA,EAAqB,EAAU,EAAiB,CAAS,EAC/D,CAAC,EAAU,EAAiB,CAAS,CACvC,EAEA,OACE,EAAA,EAAA,KAAC,IAAD,CAAG,GAAI,EAAa,OAAM,UAAW,EAAgB,QAAS,EAC3D,UACA,CAAA,CAEP,EAEkD,CAAiB,EAEnE,EAAK,YAAc"}
1
+ {"version":3,"file":"Link-CyDwbrFA.js","names":["shallowEqual","EMPTY_PARAMS","EMPTY_OPTIONS","useRouter","useIsActiveRoute","buildHref","shouldNavigate","buildActiveClassName"],"sources":["../../src/components/Link.tsx"],"sourcesContent":["import { memo, useMemo } from \"react\";\n\nimport { EMPTY_PARAMS, EMPTY_OPTIONS } from \"../constants\";\nimport {\n shouldNavigate,\n buildHref,\n buildActiveClassName,\n navigateWithHash,\n shallowEqual,\n} from \"../dom-utils\";\nimport { useIsActiveRoute } from \"../hooks/useIsActiveRoute\";\nimport { useRouter } from \"../hooks/useRouter\";\n\nimport type { LinkProps } from \"../types\";\nimport type { FC, MouseEvent } from \"react\";\n\nfunction areLinkPropsEqual(\n prev: Readonly<LinkProps>,\n next: Readonly<LinkProps>,\n): boolean {\n return (\n prev.routeName === next.routeName &&\n prev.className === next.className &&\n prev.activeClassName === next.activeClassName &&\n prev.activeStrict === next.activeStrict &&\n prev.ignoreQueryParams === next.ignoreQueryParams &&\n prev.onClick === next.onClick &&\n prev.target === next.target &&\n prev.style === next.style &&\n prev.children === next.children &&\n prev.hash === next.hash &&\n shallowEqual(prev.routeParams, next.routeParams) &&\n shallowEqual(prev.routeOptions, next.routeOptions)\n );\n}\n\nconst LinkImpl: FC<LinkProps> = ({\n routeName,\n routeParams = EMPTY_PARAMS,\n routeOptions = EMPTY_OPTIONS,\n className,\n activeClassName = \"active\",\n activeStrict = false,\n ignoreQueryParams = true,\n hash,\n onClick,\n target,\n children,\n ...props\n}) => {\n // memo + areLinkPropsEqual guarantees that on bail-out the component does\n // not render; on render, routeParams/routeOptions either changed reference\n // (true change) or comparator failed (e.g., BigInt fallback to identity),\n // so they're safe to use directly in hook deps.\n\n const router = useRouter();\n\n // When `hash` prop is set, active state requires both route AND hash to\n // match (#532). Without this, three tab links sharing routeName=\"settings\"\n // would all be marked active by route-name alone, defeating tab semantics.\n const isActive = useIsActiveRoute(\n routeName,\n routeParams,\n activeStrict,\n ignoreQueryParams,\n hash,\n );\n\n // No useMemo: outer memo()+shallowEqual prevents Link re-render unless a\n // prop actually changed. When this body runs, either `hash` differs from\n // last render or another prop changed — in both cases the `{ hash }` alloc\n // is unavoidable. The useMemo wrapper added one closure + deps slot per\n // render without saving an allocation.\n const hashOption = hash === undefined ? undefined : { hash };\n const href = buildHref(router, routeName, routeParams, hashOption);\n\n // useCallback was wasteful: 7 deps recreated the closure on every meaningful\n // render anyway, and `<a onClick>` does not benefit from a stable function\n // identity (no child-memo-bail-out chain past it). Inline arrow function is\n // what React Compiler emits automatically for this shape.\n const handleClick = (evt: MouseEvent<HTMLAnchorElement>) => {\n if (onClick) {\n onClick(evt);\n\n if (evt.defaultPrevented) {\n return;\n }\n }\n\n if (!shouldNavigate(evt.nativeEvent) || target === \"_blank\") {\n return;\n }\n\n evt.preventDefault();\n navigateWithHash(router, routeName, routeParams, hash, routeOptions).catch(\n () => {},\n );\n };\n\n // Memoize the joined class string. parseTokens + Set + join on every render\n // adds up on pages with N Links navigating frequently; deps cover every\n // input the function reads so cache invalidation is exact.\n const finalClassName = useMemo(\n () => buildActiveClassName(isActive, activeClassName, className),\n [isActive, activeClassName, className],\n );\n\n return (\n <a {...props} href={href} className={finalClassName} onClick={handleClick}>\n {children}\n </a>\n );\n};\n\nexport const Link: FC<LinkProps> = memo(LinkImpl, areLinkPropsEqual);\n\nLink.displayName = \"Link\";\n"],"mappings":"0IAgBA,SAAS,EACP,EACA,EACS,CACT,OACE,EAAK,YAAc,EAAK,WACxB,EAAK,YAAc,EAAK,WACxB,EAAK,kBAAoB,EAAK,iBAC9B,EAAK,eAAiB,EAAK,cAC3B,EAAK,oBAAsB,EAAK,mBAChC,EAAK,UAAY,EAAK,SACtB,EAAK,SAAW,EAAK,QACrB,EAAK,QAAU,EAAK,OACpB,EAAK,WAAa,EAAK,UACvB,EAAK,OAAS,EAAK,MACnBA,EAAAA,EAAa,EAAK,YAAa,EAAK,WAAW,GAC/CA,EAAAA,EAAa,EAAK,aAAc,EAAK,YAAY,CAErD,CAgFA,MAAa,GAAA,EAAA,EAAA,OA9EoB,CAC/B,YACA,cAAcC,EAAAA,EACd,eAAeC,EAAAA,EACf,YACA,kBAAkB,SAClB,eAAe,GACf,oBAAoB,GACpB,OACA,UACA,SACA,WACA,GAAG,KACC,CAMJ,IAAM,EAASC,EAAAA,EAAU,EAKnB,EAAWC,EAAAA,EACf,EACA,EACA,EACA,EACA,CACF,EAQM,EAAOC,EAAAA,EAAU,EAAQ,EAAW,EADvB,IAAS,IAAA,GAAY,IAAA,GAAY,CAAE,MAAK,CACM,EAM3D,EAAe,GAAuC,CACtD,IACF,EAAQ,CAAG,EAEP,EAAI,mBAKN,CAACC,EAAAA,EAAe,EAAI,WAAW,GAAK,IAAW,WAInD,EAAI,eAAe,EACnB,EAAA,EAAiB,EAAQ,EAAW,EAAa,EAAM,CAAY,EAAE,UAC7D,CAAC,CACT,EACF,EAKM,GAAA,EAAA,EAAA,aACEC,EAAAA,EAAqB,EAAU,EAAiB,CAAS,EAC/D,CAAC,EAAU,EAAiB,CAAS,CACvC,EAEA,OACE,EAAA,EAAA,KAAC,IAAD,CAAG,GAAI,EAAa,OAAM,UAAW,EAAgB,QAAS,EAC3D,UACA,CAAA,CAEP,EAEkD,CAAiB,EAEnE,EAAK,YAAc"}
@@ -44,4 +44,4 @@ declare function RouterErrorBoundary({
44
44
  }: RouterErrorBoundaryProps): ReactElement;
45
45
  //#endregion
46
46
  export { RouteContext as i, RouterErrorBoundaryProps as n, LinkProps as r, RouterErrorBoundary as t };
47
- //# sourceMappingURL=RouterErrorBoundary-BlJmaoyr.d.ts.map
47
+ //# sourceMappingURL=RouterErrorBoundary-3UhUelqY.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"RouterErrorBoundary-BlJmaoyr.d.ts","names":[],"sources":["../../src/types.ts","../../src/components/RouterErrorBoundary.tsx"],"mappings":";;;;UAQiB,UAAA,WAAqB,MAAA,GAAS,MAAA;EAC7C,KAAA,EAAO,KAAA,CAAM,CAAA;EACb,aAAA,GAAgB,KAAA;AAAA;AAAA,KAGN,YAAA,WAAuB,MAAA,GAAS,MAAA;EAC1C,SAAA,EAAW,SAAA;AAAA,IACT,UAAA,CAAW,CAAA;AAAA,UAEE,SAAA,WACL,MAAA,GAAS,MAAA,UACX,cAAA,CAAe,iBAAA;EACvB,SAAA;EACA,WAAA,GAAc,CAAA;EACd,YAAA,GAAe,iBAAA;EACf,eAAA;EACA,YAAA;EACA,iBAAA;EAjB6C;;;;;;;AAExB;AAGvB;EAsBE,IAAA;EACA,MAAA;EACA,OAAA,GAAU,iBAAA,CAAkB,iBAAA;EAC5B,WAAA,GAAc,iBAAA,CAAkB,iBAAA;AAAA;;;UCxBjB,wBAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,GAAW,KAAA,EAAO,WAAA,EAAa,UAAA,iBAA2B,SAAA;EAAA,SAC1D,OAAA,IACP,KAAA,EAAO,WAAA,EACP,OAAA,EAAS,KAAA,SACT,SAAA,EAAW,KAAA;AAAA;AAAA,iBAIC,mBAAA,CAAA;EACd,QAAA;EACA,QAAA;EACA;AAAA,GACC,wBAAA,GAA2B,YAAA"}
1
+ {"version":3,"file":"RouterErrorBoundary-3UhUelqY.d.ts","names":[],"sources":["../../src/types.ts","../../src/components/RouterErrorBoundary.tsx"],"mappings":";;;;UAQiB,UAAA,WAAqB,MAAA,GAAS,MAAA;EAC7C,KAAA,EAAO,KAAA,CAAM,CAAA;EACb,aAAA,GAAgB,KAAA;AAAA;AAAA,KAGN,YAAA,WAAuB,MAAA,GAAS,MAAA;EAC1C,SAAA,EAAW,SAAA;AAAA,IACT,UAAA,CAAW,CAAA;AAAA,UAEE,SAAA,WACL,MAAA,GAAS,MAAA,UACX,cAAA,CAAe,iBAAA;EACvB,SAAA;EACA,WAAA,GAAc,CAAA;EACd,YAAA,GAAe,iBAAA;EACf,eAAA;EACA,YAAA;EACA,iBAAA;EAjB6C;;;;;;;AAExB;AAGvB;EAsBE,IAAA;EACA,MAAA;EACA,OAAA,GAAU,iBAAA,CAAkB,iBAAA;EAC5B,WAAA,GAAc,iBAAA,CAAkB,iBAAA;AAAA;;;UCxBjB,wBAAA;EAAA,SACN,QAAA,EAAU,SAAA;EAAA,SACV,QAAA,GAAW,KAAA,EAAO,WAAA,EAAa,UAAA,iBAA2B,SAAA;EAAA,SAC1D,OAAA,IACP,KAAA,EAAO,WAAA,EACP,OAAA,EAAS,KAAA,SACT,SAAA,EAAW,KAAA;AAAA;AAAA,iBAIC,mBAAA,CAAA;EACd,QAAA;EACA,QAAA;EACA;AAAA,GACC,wBAAA,GAA2B,YAAA"}
@@ -0,0 +1,2 @@
1
+ const e=require("./useRoute-D2vAzKWM.js");let t=require("react"),n=require("@real-router/core"),r=require("@real-router/route-utils"),i=require("react/jsx-runtime"),a=require("@real-router/sources"),o=require("@real-router/core/api");const s=()=>{let n=(0,t.useContext)(e.s);if(!n)throw Error(`useRouter must be used within a RouterProvider`);return n};function c(e){let r=s(),i=(0,t.useMemo)(()=>(0,a.createRouteNodeSource)(r,e),[r,e]),o=(0,t.useSyncExternalStore)(i.subscribe,i.getSnapshot,i.getSnapshot),c=(0,n.getNavigator)(r);return(0,t.useMemo)(()=>({navigator:c,route:o.route,previousRoute:o.previousRoute}),[c,o])}const l=`data-real-router-announcer`,u=Object.freeze({destroy:()=>{}});function d(e,t){if(typeof document>`u`)return u;let n=t?.prefix??`Navigated to `,r=t?.getAnnouncementText,i=!0,a=!1,o=!1,s=``,c=null,l,d=f(),g=(e,t)=>{s=e,clearTimeout(l),d.textContent=e,l=setTimeout(()=>{d.textContent=``,s=``},7e3),h(t)},_=setTimeout(()=>{if(a=!0,c!==null&&!o){let e=c;c=null,g(e,document.querySelector(`h1`))}},100),v=e.subscribe(({route:e})=>{if(i){i=!1;return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(o)return;let t=document.querySelector(`h1`),i=m(e,n,r,t);if(!(!i||i===s)){if(!a){c=i;return}g(i,t)}})})});return{destroy(){o=!0,v(),clearTimeout(l),clearTimeout(_),p()}}}function f(){let e=document.querySelector(`[${l}]`);if(e)return e;let t=document.createElement(`div`);return t.setAttribute(`style`,`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);clip-path:inset(50%);white-space:nowrap;border:0`),t.setAttribute(`aria-live`,`assertive`),t.setAttribute(`aria-atomic`,`true`),t.setAttribute(l,``),(document.body??document.documentElement).prepend(t),t}function p(){document.querySelector(`[${l}]`)?.remove()}function m(e,t,n,r){if(n)try{let t=n(e);if(t)return t}catch(e){console.error(`[real-router] getAnnouncementText threw; falling back to default resolution.`,e)}let i=(r?.textContent??``).trim(),a=e.name.startsWith(`@@`)?``:e.name;return`${t}${i||document.title||a||globalThis.location.pathname}`}function h(e){e&&(e.hasAttribute(`tabindex`)||e.setAttribute(`tabindex`,`-1`),e.focus({preventScroll:!0}))}const g=Object.freeze({destroy:()=>{}});function _(e,t){if(globalThis.window===void 0)return g;let n=t?.mode??`restore`;if(n===`native`)return g;let r=t?.anchorScrolling??!0,i=t?.scrollContainer,a=t?.behavior??`auto`,o=t?.storageKey??`real-router:scroll`,s,c=()=>{if(s!==void 0)return s;try{let e=sessionStorage.getItem(o);s=e?JSON.parse(e):{}}catch{s={}}return s},l=(e,t)=>{try{let n=c();if(n[e]===t)return;n[e]=t,sessionStorage.setItem(o,JSON.stringify(n))}catch{}},u=history.scrollRestoration;try{history.scrollRestoration=`manual`}catch{}let d=()=>{let e=i?.();return e?e.scrollTop:globalThis.scrollY},f=e=>{let t=i?.();t?t.scrollTo({top:e,left:0,behavior:a}):globalThis.scrollTo({top:e,left:0,behavior:a})},p=e=>{if(!i){globalThis.scrollTo({top:e,left:0,behavior:a});return}let t=0,n=()=>{if(h)return;let r=i();if(r){if(r.scrollTo({top:e,left:0,behavior:a}),a!==`smooth`&&Math.abs(r.scrollTop-e)<=1)return}else globalThis.scrollTo({top:e,left:0,behavior:a});t>=10||(t+=1,requestAnimationFrame(n))};n()},m=e=>{let t=e.context?.url?.hash;if(t!==void 0){if(r&&t.length>0){let e=document.getElementById(t);if(e){e.scrollIntoView({behavior:a});return}}f(0);return}let n=globalThis.location.hash;if(r&&n.length>1){let e;try{e=decodeURIComponent(n.slice(1))}catch{e=n.slice(1)}let t=document.getElementById(e);if(t){t.scrollIntoView({behavior:a});return}}f(0)},h=!1,_=!1,v=e=>{try{return y(e)}catch{return _||(_=!0,console.error(`[real-router] scroll-restore: route "${e.name}" has params that cannot be canonicalized (e.g. BigInt or cyclic structure). Scroll position will not be captured or restored for this route.`)),null}},b=e.subscribe(({route:e,previousRoute:t})=>{let r=e.context.navigation;if(t){let e=v(t);e!==null&&l(e,d())}requestAnimationFrame(()=>{if(!h){if(n===`top`){m(e);return}if(e.transition.reload||r?.navigationType===`reload`){let t=v(e);p(t===null?0:c()[t]??0);return}if(r?.direction===`back`||r?.navigationType===`traverse`){let t=v(e);p(t===null?0:c()[t]??0);return}e.transition.replace||r?.navigationType===`replace`||m(e)}})}),x=()=>{let t=e.getState();if(t){let e=v(t);e!==null&&l(e,d())}};return globalThis.addEventListener(`pagehide`,x),{destroy:()=>{if(!h){h=!0,b(),globalThis.removeEventListener(`pagehide`,x);try{history.scrollRestoration=u}catch{}}}}}const v=new WeakMap;function y(e){let t=v.get(e);if(t!==void 0)return t;let n=`${e.name}:${b(e.params)}`;return v.set(e,n),n}function b(e){return JSON.stringify(e,x)}function x(e,t){if(typeof t==`function`)return`<fn>`;if(typeof t==`symbol`)return`<sym>`;if(typeof t==`object`&&t&&!Array.isArray(t)){let e=Object.create(null),n=Object.keys(t).sort((e,t)=>e.localeCompare(t));for(let r of n)e[r]=t[r];return e}return t}const S=Object.freeze({destroy:()=>{}}),C=e=>e.context?.url,w=e=>{let t=null,n=1/0,r=null,i=-1/0;for(let a of e){if(!a.isIntersecting)continue;let e=a.rootBounds?.top??0,o=a.boundingClientRect.top-e;o>=0?o<n&&(t=a,n=o):o>i&&(r=a,i=o)}return t??r},T=(e,t)=>{let n=null,r=e=>{let n=e.context;n&&n.url===void 0&&(console.warn(`[real-router] scroll-spy: state.context.url is not claimed. Spy requires browser-plugin or navigation-plugin. Disabling.`),t())},i=e.getState();if(i)r(i);else{let t=!1;n=e.subscribe(({route:e})=>{t||(t=!0,r(e),n?.(),n=null)})}return{destroy(){n?.(),n=null}}},E=e=>{let t=!1,n=null,r=null,i=null,a=()=>{n!==null&&(clearTimeout(n),n=null),i&&(r??globalThis).removeEventListener(`scrollend`,i),i=null,r=null,t=!1};return{get active(){return t},start(){a(),t=!0;let o=()=>{a()};i=o,r=e(),(r??globalThis).addEventListener(`scrollend`,o,{once:!0}),n=setTimeout(o,500)},destroy(){a()}}},D=(e,t)=>{let n=null,r=null;return{schedule(){n===null&&(n=requestAnimationFrame(()=>{n=null,r!==null&&clearTimeout(r),r=setTimeout(()=>{r=null,e()},t)}))},destroy(){n!==null&&(cancelAnimationFrame(n),n=null),r!==null&&(clearTimeout(r),r=null)}}},O=(e,t,n,r,i,a)=>{let o=new Set,s=new Map,c=!1,l=null,u=new IntersectionObserver(e=>{if(!a()){for(let t of e)s.set(t.target,t);r()}},{root:n(),rootMargin:t,threshold:0}),d=()=>{let t=n()??document,r;try{r=t.querySelectorAll(e)}catch{i();return}let a=new Set;for(let e of r){let t=e.id;t&&!c&&(a.has(t)&&(c=!0,console.warn(`[real-router] scroll-spy: duplicate id "${t}" observed. Selection picks the topmost visible match deterministically.`)),a.add(t)),!o.has(e)&&(u.observe(e),o.add(e))}},f=()=>{for(let e of o)e.isConnected||(u.unobserve(e),o.delete(e),s.delete(e));d()};d();let p=n()??document.body,m=new MutationObserver(()=>{l!==null&&clearTimeout(l),l=setTimeout(()=>{l=null,f()},250)});return m.observe(p,{childList:!0,subtree:!0,attributes:!0,attributeFilter:[`id`]}),{pending:s,destroy(){u.disconnect(),m.disconnect(),l!==null&&(clearTimeout(l),l=null),o.clear(),s.clear()}}};function k(e,t){if(typeof document>`u`||typeof IntersectionObserver>`u`)return S;let{selector:n}=t;if(!n)return S;let r=t.rootMargin??`-20% 0px -60% 0px`,i=t.scrollContainer,o=()=>i?.()??null,s=!1,c=!1,l=!1,u=()=>c||s,d=null,f=(0,a.getTransitionSource)(e),p=T(e,()=>{c=!0}),m=E(o),h=D(()=>{d?.()},150),g=O(n,r,o,()=>{h.schedule()},()=>{c||(c=!0,console.warn(`[real-router] scroll-spy: invalid selector "${n}". Disabling.`))},u);d=()=>{if(s||c){g.pending.clear();return}if(f.getSnapshot().isTransitioning||m.active||g.pending.size===0)return;let t=w(g.pending.values());if(g.pending.clear(),!t)return;let n=t.target.id;if(!n)return;let r=e.getState();if(!r||n===(C(r)?.hash??``))return;let i={hash:n,replace:!0,force:!0,hashChange:!0};l=!0,e.navigate(r.name,r.params,i).catch(()=>{}).finally(()=>{l=!1})};let _=e.subscribe(({route:e})=>{l||C(e)?.hashChanged&&m.start()});return{destroy(){s||(s=!0,_(),g.destroy(),h.destroy(),m.destroy(),p.destroy())}}}const A=Object.freeze({destroy:()=>{}});function j(e){if(typeof document>`u`||typeof document.startViewTransition!=`function`)return A;let t=null,n=null,r=!1,i=()=>{t?.(),t=null},a=e.subscribeLeave(({signal:e})=>{if(!e.aborted)return r=!1,i(),new Promise(a=>{let o=new Promise(e=>{t=e});e.addEventListener(`abort`,()=>{r||(i(),n?.skipTransition?.(),a())},{once:!0});try{n=document.startViewTransition(()=>(a(),o))}catch{i(),a()}})}),o=e.subscribe(()=>{let e=t;r=!0,t=null,e===null?n=null:setTimeout(()=>{e(),n=null},0)});return{destroy:()=>{a(),o(),n?.skipTransition?.(),n=null,i()}}}function M(e){return e.button===0&&!e.metaKey&&!e.altKey&&!e.ctrlKey&&!e.shiftKey}const N=/%[\dA-Fa-f]{2}/;function P(e){if(N.test(e))try{return encodeURI(decodeURIComponent(e)).replaceAll(`#`,`%23`)}catch{}return encodeURI(e).replaceAll(`#`,`%23`)}function F(e,t,n,r){try{let i=r?.hash,a;i!==void 0&&(a=i.startsWith(`#`)?i.slice(1):i);let o=e.buildUrl;if(o){let e=o(t,n,a===void 0?void 0:{hash:a});if(typeof e==`string`&&e.length>0)return e}let s=e.buildPath(t,n);if(typeof s!=`string`||s.length===0){console.error(`[real-router] Route "${t}" yielded an empty path. The element will render without an href attribute.`);return}return a?`${s}#${P(a)}`:s}catch{console.error(`[real-router] Route "${t}" is not defined. The element will render without an href attribute.`);return}}function I(e,t,n,r,i){let a={...i};r!==void 0&&(a.hash=r);let o=e.getState();if(o?.name===t&&V(o.params,n)){let e=o.context?.url?.hash??``;e!==(r??e)&&(a.force=!0,a.hashChange=!0)}return e.navigate(t,n,a)}const L=/\s/,R=/\S+/g;function z(e){return e?L.test(e)?e.match(R)??[]:[e]:[]}function B(e,t,n){if(e&&t){let e=z(t);if(e.length===0)return n??void 0;if(!n)return e.join(` `);let r=z(n),i=new Set(r);for(let t of e)i.has(t)||(i.add(t),r.push(t));return r.join(` `)}return n??void 0}function V(e,t){if(Object.is(e,t))return!0;if(!e||!t)return!1;let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;let r=e,i=t;for(let e of n)if(!Object.prototype.hasOwnProperty.call(t,e)||!Object.is(r[e],i[e]))return!1;return!0}function H(e,n,r=!1,i=!0,o){let c=s(),l=(0,t.useMemo)(()=>(0,a.createActiveRouteSource)(c,e,n,{strict:r,ignoreQueryParams:i,...o!==void 0&&{hash:o}}),[c,e,n,r,i,o]);return(0,t.useSyncExternalStore)(l.subscribe,l.getSnapshot,l.getSnapshot)}function U({children:e,fallback:n,onError:r}){let o=s(),c=(0,t.useMemo)(()=>(0,a.createDismissableError)(o),[o]),l=(0,t.useSyncExternalStore)(c.subscribe,c.getSnapshot,c.getSnapshot),u=(0,t.useRef)(r);return(0,t.useLayoutEffect)(()=>{u.current=r}),(0,t.useEffect)(()=>{l.error&&u.current?.(l.error,l.toRoute,l.fromRoute)},[l.version]),(0,i.jsxs)(i.Fragment,{children:[e,l.error?n(l.error,l.resetError):null]})}const W=()=>{let n=(0,t.useContext)(e.a);if(!n)throw Error(`useNavigator must be used within a RouterProvider`);return n},G=()=>(0,r.getRouteUtils)((0,o.getPluginApi)(s()).getTree());function K(){let e=(0,a.getTransitionSource)(s());return(0,t.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getSnapshot)}const q=({router:r,children:o,announceNavigation:s,scrollRestoration:c,scrollSpy:l,viewTransitions:u})=>{(0,t.useEffect)(()=>{if(!s)return;let e=d(r);return()=>{e.destroy()}},[s,r]);let f=c?.mode,p=c?.anchorScrolling,m=c?.behavior,h=c?.storageKey,g=c!==void 0;(0,t.useEffect)(()=>{if(!g)return;let e=_(r,{mode:f,anchorScrolling:p,behavior:m,storageKey:h,scrollContainer:c.scrollContainer});return()=>{e.destroy()}},[r,g,f,p,m,h]);let v=l?.selector,y=l?.rootMargin,b=l!==void 0&&v!==void 0&&v!==``;(0,t.useEffect)(()=>{if(!b)return;let e=k(r,{selector:v,rootMargin:y,scrollContainer:l.scrollContainer});return()=>{e.destroy()}},[r,b,v,y]),(0,t.useEffect)(()=>{if(!u)return;let e=j(r);return()=>{e.destroy()}},[r,u]);let x=(0,t.useMemo)(()=>(0,n.getNavigator)(r),[r]),S=(0,t.useMemo)(()=>(0,a.createRouteSource)(r),[r]),C=(0,t.useSyncExternalStore)(S.subscribe,S.getSnapshot,S.getSnapshot),w=(0,t.useMemo)(()=>({navigator:x,route:C.route,previousRoute:C.previousRoute}),[x,C]);return(0,i.jsx)(e.s.Provider,{value:r,children:(0,i.jsx)(e.a.Provider,{value:x,children:(0,i.jsx)(e.o.Provider,{value:w,children:o})})})};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return W}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return V}});
2
+ //# sourceMappingURL=RouterProvider-CPsCmrRw.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RouterProvider-CPsCmrRw.js","names":["RouterContext","NOOP_INSTANCE","NOOP_INSTANCE","NOOP_INSTANCE","NavigatorContext","RouterContext","NavigatorContext","RouteContext"],"sources":["../../src/hooks/useRouter.tsx","../../src/hooks/useRouteNode.tsx","../../../../shared/dom-utils/route-announcer.ts","../../../../shared/dom-utils/scroll-restore.ts","../../../../shared/dom-utils/scroll-spy.ts","../../../../shared/dom-utils/view-transitions.ts","../../../../shared/dom-utils/link-utils.ts","../../src/hooks/useIsActiveRoute.tsx","../../src/components/RouterErrorBoundary.tsx","../../src/hooks/useNavigator.tsx","../../src/hooks/useRouteUtils.tsx","../../src/hooks/useRouterTransition.tsx","../../src/RouterProvider.tsx"],"sourcesContent":["import { useContext } from \"react\";\n\nimport { RouterContext } from \"../context\";\n\nimport type { Router } from \"@real-router/core\";\n\nexport const useRouter = (): Router => {\n const router = useContext(RouterContext);\n\n if (!router) {\n throw new Error(\"useRouter must be used within a RouterProvider\");\n }\n\n return router;\n};\n","import { getNavigator } from \"@real-router/core\";\nimport { createRouteNodeSource } from \"@real-router/sources\";\nimport { useMemo, useSyncExternalStore } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { RouteContext } from \"../types\";\n\nexport function useRouteNode(nodeName: string): RouteContext {\n const router = useRouter();\n\n const store = useMemo(\n () => createRouteNodeSource(router, nodeName),\n [router, nodeName],\n );\n\n // Use snapshot reference directly. createRouteNodeSource via stabilizeState\n // returns the SAME snapshot when the node-relevant state did not change,\n // so memoization on `[navigator, snapshot]` preserves identity for consumers.\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot, // SSR: router returns same state on server and client\n );\n\n // getNavigator is WeakMap-cached in core; additional useMemo is redundant.\n const navigator = getNavigator(router);\n\n return useMemo(\n (): RouteContext => ({\n navigator,\n route: snapshot.route,\n previousRoute: snapshot.previousRoute,\n }),\n [navigator, snapshot],\n );\n}\n","import type { Router, State } from \"@real-router/core\";\n\nconst CLEAR_DELAY = 7000;\nconst SAFARI_READY_DELAY = 100;\nconst ANNOUNCER_ATTR = \"data-real-router-announcer\";\nconst INTERNAL_ROUTE_PREFIX = \"@@\";\nconst VISUALLY_HIDDEN =\n \"position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);clip-path:inset(50%);white-space:nowrap;border:0\";\n\nexport interface RouteAnnouncerOptions {\n prefix?: string;\n getAnnouncementText?: (route: State) => string;\n}\n\nconst NOOP_INSTANCE: { destroy: () => void } = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\nexport function createRouteAnnouncer(\n router: Router,\n options?: RouteAnnouncerOptions,\n): { destroy: () => void } {\n // Defensive SSR / non-browser guard: in SSR (Node.js) or non-DOM\n // environments, `document` is undefined and the announcer cannot\n // attach its aria-live region. Return a frozen NOOP_INSTANCE — same\n // pattern as `createDirectionTracker`, `createScrollRestoration`, and\n // `createViewTransitions`. Without this guard, `NavigationAnnouncer`\n // component construction would throw `ReferenceError: document is not\n // defined` under `@angular/ssr` rendering, tearing down the whole SSR\n // bootstrap. Closes review-2026-05-10 §5.10 ⛔ \"NavigationAnnouncer\n // SSR mode\" MED.\n if (typeof document === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n const prefix = options?.prefix ?? \"Navigated to \";\n const getCustomText = options?.getAnnouncementText;\n\n let isInitialNavigation = true;\n let isReady = false;\n let isDestroyed = false;\n let lastAnnouncedText = \"\";\n let pendingText: string | null = null;\n let clearTimeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const announcer = getOrCreateAnnouncer();\n\n const doAnnounce = (text: string, h1: HTMLElement | null): void => {\n lastAnnouncedText = text;\n clearTimeout(clearTimeoutId);\n announcer.textContent = text;\n clearTimeoutId = setTimeout(() => {\n announcer.textContent = \"\";\n lastAnnouncedText = \"\";\n }, CLEAR_DELAY);\n\n manageFocus(h1);\n };\n\n // Safari-ready delay: announcing before VoiceOver wires up the aria-live region\n // causes the first announcement to be silently dropped. Wait SAFARI_READY_DELAY ms\n // before marking the announcer \"ready\" — any navigation during that window is\n // buffered in pendingText and flushed once the delay expires.\n const safariTimeoutId = setTimeout(() => {\n isReady = true;\n\n if (pendingText !== null && !isDestroyed) {\n const text = pendingText;\n\n pendingText = null;\n doAnnounce(text, document.querySelector<HTMLElement>(\"h1\"));\n }\n }, SAFARI_READY_DELAY);\n\n const unsubscribe = router.subscribe(({ route }) => {\n if (isInitialNavigation) {\n isInitialNavigation = false;\n\n return;\n }\n\n // Double rAF: waits for two paint frames so the incoming route's DOM\n // (including the new <h1>) is fully rendered before resolveText reads it.\n // Single rAF fires before the new route's template has been attached,\n // which would cause resolveText to pick up the OLD h1 or fall back to\n // document.title / route.name prematurely.\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n if (isDestroyed) {\n return;\n }\n\n const h1 = document.querySelector<HTMLElement>(\"h1\");\n const text = resolveText(route, prefix, getCustomText, h1);\n\n if (!text || text === lastAnnouncedText) {\n return;\n }\n\n if (!isReady) {\n // Defer announcement until Safari-ready window elapses (see safariTimeoutId).\n pendingText = text;\n\n return;\n }\n\n doAnnounce(text, h1);\n });\n });\n });\n\n return {\n destroy() {\n isDestroyed = true;\n unsubscribe();\n clearTimeout(clearTimeoutId);\n clearTimeout(safariTimeoutId);\n removeAnnouncer();\n },\n };\n}\n\nfunction getOrCreateAnnouncer(): HTMLElement {\n const existing = document.querySelector<HTMLElement>(`[${ANNOUNCER_ATTR}]`);\n\n if (existing) {\n return existing;\n }\n\n const element = document.createElement(\"div\");\n\n element.setAttribute(\"style\", VISUALLY_HIDDEN);\n element.setAttribute(\"aria-live\", \"assertive\");\n element.setAttribute(\"aria-atomic\", \"true\");\n element.setAttribute(ANNOUNCER_ATTR, \"\");\n\n // Defensive SSR / pre-`<body>` guard: in some environments (early\n // injection, deferred-body documents, certain SSR rehydration paths)\n // `document.body` can be null when the announcer is constructed.\n // `document.body.prepend(...)` would throw `TypeError: Cannot read\n // properties of null`, tearing down the consumer's RouterProvider /\n // NavigationAnnouncer mount. Fallback to `documentElement` keeps the\n // announcer working for SR users; visual-hidden styling means there is\n // no visible artifact regardless of mount point.\n //\n // TS dom lib types `document.body` as `HTMLElement` (non-null), but\n // runtime can return null per spec. The `as` cast narrows the type to\n // include null so the `??` short-circuit is type-safe.\n ((document.body as HTMLElement | null) ?? document.documentElement).prepend(\n element,\n );\n\n return element;\n}\n\nfunction removeAnnouncer(): void {\n document.querySelector(`[${ANNOUNCER_ATTR}]`)?.remove();\n}\n\nfunction resolveText(\n route: State,\n prefix: string,\n getCustomText: ((route: State) => string) | undefined,\n h1: HTMLElement | null,\n): string {\n if (getCustomText) {\n try {\n const customText = getCustomText(route);\n\n // Mini-sprint E.4 (audit-5 §4.2 #4) — empty-string fallback.\n // A consumer pattern like\n // getAnnouncementText: (route) => myMap[route.name] ?? \"\"\n // returns `\"\"` for routes outside the map. The subscribe loop\n // then sees an empty text and silently no-announces — screen\n // readers stay quiet without any signal to the developer. Treat\n // a falsy custom result (`\"\"` / `null` / `undefined`) as\n // \"consumer doesn't have a name for this route\" and fall through\n // to the default resolution chain (h1 → title → route name).\n if (customText) {\n return customText;\n }\n } catch (error) {\n // A throwing consumer callback inside the router's subscribe loop\n // would tear down sibling listeners — log and fall through to the\n // built-in resolution chain so the announcer keeps working.\n console.error(\n \"[real-router] getAnnouncementText threw; falling back to default resolution.\",\n error,\n );\n }\n }\n\n const h1Text = (h1?.textContent ?? \"\").trim();\n const routeName = route.name.startsWith(INTERNAL_ROUTE_PREFIX)\n ? \"\"\n : route.name;\n const rawText =\n h1Text || document.title || routeName || globalThis.location.pathname;\n\n return `${prefix}${rawText}`;\n}\n\nfunction manageFocus(h1: HTMLElement | null): void {\n if (!h1) {\n return;\n }\n\n if (!h1.hasAttribute(\"tabindex\")) {\n h1.setAttribute(\"tabindex\", \"-1\");\n }\n\n h1.focus({ preventScroll: true });\n}\n","import type { Router, State } from \"@real-router/core\";\n\nconst DEFAULT_STORAGE_KEY = \"real-router:scroll\";\n\n// Bounded retry budget for resolving a late-mounting scroll container on the\n// restore path. A per-route container (e.g. an `overflow:auto` div rendered\n// only on one route) can be committed to the DOM a few frames after the\n// navigation settles — heavier routes paint later than the subscribe's rAF.\n// ~10 frames (≈160ms at 60fps) comfortably covers a React commit of a large\n// route without being perceptible. See the doc-block on `restorePos`.\nconst RESTORE_RETRY_FRAMES = 10;\n\nconst NOOP_INSTANCE: { destroy: () => void } = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\nexport type ScrollRestorationMode = \"restore\" | \"top\" | \"native\";\n\nexport interface ScrollRestorationOptions {\n mode?: ScrollRestorationMode | undefined;\n anchorScrolling?: boolean | undefined;\n scrollContainer?: (() => HTMLElement | null) | undefined;\n /**\n * Scroll behavior passed to `scrollTo({ behavior })` and\n * `scrollIntoView({ behavior })`.\n *\n * - `\"auto\"` (default) — browser-defined, usually instant.\n * - `\"instant\"` — explicit instant jump (no animation).\n * - `\"smooth\"` — animated transition. Note: smooth restore on back/traverse\n * can feel disorienting if the user expects to land at the saved position\n * immediately. Recommended for `mode: \"top\"` or anchor scroll only.\n *\n * See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/ScrollToOptions/behavior).\n */\n behavior?: ScrollBehavior | undefined;\n /**\n * sessionStorage key used to persist saved scroll positions. Default:\n * `\"real-router:scroll\"`. Override only when multiple independent\n * `RouterProvider` instances share the same document and you need to\n * isolate their scroll stores (e.g. micro-frontends, embedded widgets,\n * or testing). For a single app with one provider the default is fine.\n */\n storageKey?: string | undefined;\n}\n\ninterface NavigationContext {\n direction?: \"forward\" | \"back\" | \"unknown\";\n navigationType?: \"push\" | \"replace\" | \"traverse\" | \"reload\";\n}\n\nexport function createScrollRestoration(\n router: Router,\n options?: ScrollRestorationOptions,\n): { destroy: () => void } {\n if (typeof globalThis.window === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n const mode = options?.mode ?? \"restore\";\n\n // mode \"native\" = utility does nothing. Don't flip history.scrollRestoration,\n // don't subscribe, don't register pagehide — `history.scrollRestoration`\n // stays at the browser default (\"auto\") so the browser handles scroll\n // restore natively. (Note: this is the OPPOSITE of `history.scrollRestoration\n // === \"manual\"` — utility's \"native\" leaves the DOM property at \"auto\" so\n // the browser is in charge.)\n if (mode === \"native\") {\n return NOOP_INSTANCE;\n }\n\n const anchorEnabled = options?.anchorScrolling ?? true;\n const getContainer = options?.scrollContainer;\n const behavior: ScrollBehavior = options?.behavior ?? \"auto\";\n const storageKey = options?.storageKey ?? DEFAULT_STORAGE_KEY;\n\n // Write-through in-memory cache: parse sessionStorage once per provider\n // mount, then mutate in-memory. Avoids a JSON.parse + JSON.stringify pair\n // on every subscribeLeave / pagehide event.\n let store: Record<string, number> | undefined;\n\n const loadStore = (): Record<string, number> => {\n if (store !== undefined) {\n return store;\n }\n\n try {\n const raw = sessionStorage.getItem(storageKey);\n\n store = raw ? (JSON.parse(raw) as Record<string, number>) : {};\n } catch {\n store = {};\n }\n\n return store;\n };\n\n const putPos = (key: string, pos: number): void => {\n try {\n const cached = loadStore();\n\n // Skip-same-value: when a route is left at the same scroll position it\n // already holds in the cache (e.g. tab-switching without scrolling),\n // both the in-memory write and the JSON.stringify + setItem pair are\n // no-ops. Eliminates redundant serialization on the navigation hot\n // path for the common \"click tabs without scrolling\" case.\n if (cached[key] === pos) {\n return;\n }\n\n cached[key] = pos;\n sessionStorage.setItem(storageKey, JSON.stringify(cached));\n } catch {\n // Ignore quota / security errors.\n }\n };\n\n const prevScrollRestoration = history.scrollRestoration;\n\n try {\n history.scrollRestoration = \"manual\";\n } catch {\n // Ignore — some embedded contexts may reject the assignment.\n }\n\n // Resolve the container lazily on every event so containers mounted AFTER\n // the provider still get correct scroll handling. Falls back to window when\n // the getter is absent or returns null (pre-mount).\n const readPos = (): number => {\n const element = getContainer?.();\n\n return element ? element.scrollTop : globalThis.scrollY;\n };\n\n const writePos = (top: number): void => {\n const element = getContainer?.();\n\n if (element) {\n element.scrollTo({ top, left: 0, behavior });\n } else {\n globalThis.scrollTo({ top, left: 0, behavior });\n }\n };\n\n // Restore path (back / traverse / reload). Unlike `writePos`, this tolerates a\n // scroll container that both MOUNTS and LAYS OUT a few frames AFTER the\n // navigation settles.\n //\n // The capture-side `readPos` always runs against an already-mounted DOM (the\n // route being left). On restore the target route — and its container — is\n // still being committed by the view layer. The subscribe callback schedules a\n // single rAF; for a heavy route (e.g. a long virtual list) the framework's\n // commit can land AFTER that frame. Two distinct failures follow, each losing\n // the saved position (Scenario 6 e2e, reproduced under CI's slower runner):\n //\n // 1. Container not mounted yet → `getContainer()` is `null`, the scroll\n // silently falls back to `window`, which on a container-only route has\n // nothing to scroll.\n // 2. Container mounted but its content not laid out yet → `scrollHeight`\n // is still small, so a single `scrollTo({ top })` clamps short of the\n // saved position and never re-applies once layout grows.\n //\n // With no `scrollContainer` getter the target is always `window`, present\n // from the first frame — restore in a single shot (unchanged behaviour). When\n // a getter is configured we cannot tell \"this route legitimately uses window\"\n // from \"the container is still mounting\", so re-apply the scroll on every\n // frame for a bounded budget: window as a fallback while the container is\n // absent (harmless clamp on container routes), the container itself once it\n // appears. For instant restores we stop early the moment the position sticks;\n // smooth restores animate asynchronously, so they run the full budget. The\n // frame budget is the hard backstop against an unreachable target (saved\n // position taller than the restored content).\n const restorePos = (top: number): void => {\n if (!getContainer) {\n globalThis.scrollTo({ top, left: 0, behavior });\n\n return;\n }\n\n let frames = 0;\n\n const attempt = (): void => {\n if (destroyed) {\n return;\n }\n\n const element = getContainer();\n\n if (element) {\n element.scrollTo({ top, left: 0, behavior });\n\n // Instant restore landed within rounding tolerance → done; no point\n // re-applying. Smooth restore never matches synchronously, so let it\n // ride the budget.\n if (behavior !== \"smooth\" && Math.abs(element.scrollTop - top) <= 1) {\n return;\n }\n } else {\n globalThis.scrollTo({ top, left: 0, behavior });\n }\n\n if (frames >= RESTORE_RETRY_FRAMES) {\n return;\n }\n\n frames += 1;\n requestAnimationFrame(attempt);\n };\n\n attempt();\n };\n\n const scrollToHashOrTop = (route: State): void => {\n // URL plugin path (#532): `state.context.url.hash` is the source of truth\n // when one of the URL plugins (browser-plugin / navigation-plugin) is\n // installed. The value is already DECODED — feeding it through\n // `decodeURIComponent` again would throw on a bare `%`.\n const ctxHash = (route.context as { url?: { hash?: string } } | undefined)\n ?.url?.hash;\n\n if (ctxHash !== undefined) {\n if (anchorEnabled && ctxHash.length > 0) {\n // eslint-disable-next-line unicorn/prefer-query-selector -- ids may contain CSS-unsafe chars\n const element = document.getElementById(ctxHash);\n\n if (element) {\n element.scrollIntoView({ behavior });\n\n return;\n }\n }\n\n writePos(0);\n\n return;\n }\n\n // Fallback path: no URL plugin, read the DOM. `location.hash` is\n // percent-encoded; ids in the DOM are the raw string, so decode for the\n // match. Fall back to the raw slice if the hash contains a malformed\n // escape sequence (decodeURIComponent throws on those).\n const hash = globalThis.location.hash;\n\n if (anchorEnabled && hash.length > 1) {\n let id: string;\n\n try {\n id = decodeURIComponent(hash.slice(1));\n } catch {\n id = hash.slice(1);\n }\n\n // eslint-disable-next-line unicorn/prefer-query-selector -- ids may contain CSS-unsafe chars\n const element = document.getElementById(id);\n\n if (element) {\n element.scrollIntoView({ behavior });\n\n return;\n }\n }\n\n writePos(0);\n };\n\n let destroyed = false;\n let unserializableWarned = false;\n\n // `keyOf` defers to `canonicalJson` which calls `JSON.stringify`. Two\n // realistic inputs blow up the serializer and would otherwise crash the\n // subscribe callback (taking scroll-restore offline for the whole session):\n // - `BigInt` params → `TypeError: Do not know how to serialize a BigInt`\n // - cyclic params (reactive proxies, DOM-ref back-pointers) → stack\n // overflow.\n // The defensive wrapper drops capture/restore for that specific navigation\n // and warns once per provider — the rest of the cache stays usable.\n const safeKeyOf = (state: State): string | null => {\n try {\n return keyOf(state);\n } catch {\n if (!unserializableWarned) {\n unserializableWarned = true;\n console.error(\n `[real-router] scroll-restore: route \"${state.name}\" has params that cannot be canonicalized (e.g. BigInt or cyclic structure). Scroll position will not be captured or restored for this route.`,\n );\n }\n\n return null;\n }\n };\n\n const unsubscribe = router.subscribe(({ route, previousRoute }) => {\n const nav = (route.context as { navigation?: NavigationContext })\n .navigation;\n\n // Browsers dispatch reload as the initial navigation after refresh, so\n // previousRoute is undefined and capture is naturally skipped. The\n // pre-refresh position was already persisted via pagehide.\n if (previousRoute) {\n const prevKey = safeKeyOf(previousRoute);\n\n if (prevKey !== null) {\n putPos(prevKey, readPos());\n }\n }\n\n requestAnimationFrame(() => {\n if (destroyed) {\n return;\n }\n\n if (mode === \"top\") {\n scrollToHashOrTop(route);\n\n return;\n }\n\n // Restore branches (reload, back/traverse) MUST be evaluated before the\n // replace-skip below. Since #657 lifted `replace` into TransitionMeta, a\n // history TRAVERSAL (back/forward) under navigation-plugin carries\n // `transition.replace === true` — a traversal reuses an existing history\n // entry, which is replace-shaped at the history level. If the replace-skip\n // ran first it would swallow every back/forward navigation and restore\n // would never fire (the Scenario 6 e2e regression). Genuine in-place\n // replaces (`router.navigate({ replace: true })`, navigateToNotFound) are\n // not traversals and fall through to the skip below.\n //\n // Both arms of each check are required: `transition.reload` only fires for\n // programmatic `router.navigate({reload:true})`. F5 under navigation-plugin\n // primes `nav.navigationType === \"reload\"` via #531 getActivationType but\n // leaves opts.reload undefined, so dropping the plugin arm would regress F5\n // scroll-restore. Browser-plugin's F5 is not covered (no priming, out of\n // scope).\n if (route.transition.reload || nav?.navigationType === \"reload\") {\n const key = safeKeyOf(route);\n\n restorePos(key === null ? 0 : (loadStore()[key] ?? 0));\n\n return;\n }\n\n if (nav?.direction === \"back\" || nav?.navigationType === \"traverse\") {\n const key = safeKeyOf(route);\n\n restorePos(key === null ? 0 : (loadStore()[key] ?? 0));\n\n return;\n }\n\n // Genuine in-place replace (not a traversal) — leave scroll untouched.\n if (route.transition.replace || nav?.navigationType === \"replace\") {\n return;\n }\n\n scrollToHashOrTop(route);\n });\n });\n\n const onPageHide = (): void => {\n const current = router.getState();\n\n if (current) {\n const key = safeKeyOf(current);\n\n if (key !== null) {\n putPos(key, readPos());\n }\n }\n };\n\n globalThis.addEventListener(\"pagehide\", onPageHide);\n\n return {\n destroy: () => {\n if (destroyed) {\n return;\n }\n\n destroyed = true;\n unsubscribe();\n globalThis.removeEventListener(\"pagehide\", onPageHide);\n\n try {\n history.scrollRestoration = prevScrollRestoration;\n } catch {\n // Ignore.\n }\n },\n };\n}\n\n/**\n * Internal cache-key builder for scroll-position storage.\n *\n * **Exported for testing only — not part of the public API** (intentionally\n * excluded from `index.ts` barrel). Adapter property tests import it via\n * the direct path to lock the `(name, canonicalJson(params))` key shape\n * as a regression guard (§8b H20 / audit-2026-05-16 #S3). A change to\n * key format would silently lose scroll positions across an upgrade —\n * the test set is the contract.\n *\n * ## Identity-based memoization (audit-2026-05-17 §8b #2)\n *\n * `State` objects emitted by core are frozen per-navigation: their\n * `name` / `params` are immutable for the lifetime of the snapshot, and\n * any change produces a new `State` reference. A `WeakMap<State, string>`\n * therefore safely caches the canonicalised key by identity — repeat\n * `keyOf(state)` calls on the same snapshot (typical on\n * back/forward/traverse where the same prior `State` is re-emitted)\n * skip the recursive `canonicalJson` pass entirely.\n *\n * The cache key is the `State` reference, so entries auto-release when\n * the snapshot is GC'd — no eviction needed.\n */\nconst KEY_CACHE = new WeakMap<State, string>();\n\nexport function keyOf(state: State): string {\n const cached = KEY_CACHE.get(state);\n\n if (cached !== undefined) {\n return cached;\n }\n\n const key = `${state.name}:${canonicalJson(state.params)}`;\n\n KEY_CACHE.set(state, key);\n\n return key;\n}\n\n/**\n * Stable JSON serializer with sorted object keys.\n *\n * **Exported for testing only — not part of the public API** (intentionally\n * excluded from `index.ts` barrel). Adapter property tests import it via\n * the direct path to lock the key-order-insensitive property\n * (`canonicalJson({a:1,b:2}) === canonicalJson({b:2,a:1})`).\n *\n * ## Divergence from `@real-router/sources/canonicalJson` — by design\n *\n * Two independent implementations live in the monorepo:\n *\n * - **`shared/dom-utils/scroll-restore.canonicalJson`** (this file) — scroll\n * cache key builder. Uses `localeCompare` and a plain-object accumulator;\n * tolerates `__proto__`-keyed inputs only insofar as `JSON.stringify`'s\n * replacer happens to sort them; relies on `JSON.stringify`'s native cycle\n * detector. Designed to be cheap on the navigation hot path. The\n * surrounding [[safeKeyOf]] wrapper catches the two crash inputs (`BigInt`,\n * cyclic) and skips the offending capture/restore.\n *\n * - **`@real-router/sources/canonicalJson`** — sources cache key builder.\n * Uses byte-order compare (`< / >`) for locale-independence, a\n * `Object.create(null)` accumulator to prevent prototype pollution, and a\n * bespoke path-based cycle detector (the native one cannot see the cloned\n * graph). Throws eagerly on `Map`/`Set`/`RegExp`/cycles — the caller falls\n * back to a non-cached source.\n *\n * **They are intentionally NOT interchangeable.** Aligning them would either\n * regress scroll-restore performance (byte-order + recursive clone is heavier\n * per call) or weaken the sources cache (locale dependence breaks\n * deterministic cache keys across machines). No cross-package equivalence\n * test exists or should be added; the relationship is \"different invariants,\n * different costs, different consumers.\" Audit-2 / audit-2026-05-17 §2\n * documents the choice.\n */\nexport function canonicalJson(value: unknown): string {\n return JSON.stringify(value, canonicalReplacer);\n}\n\nfunction canonicalReplacer(_key: string, val: unknown): unknown {\n // audit-2026-05-17 §5 MEDIUM (Sprint A.3) — function/Symbol marker.\n // `JSON.stringify` silently drops function and symbol values from\n // object output. Two routes that differ ONLY in a function/Symbol\n // value would canonicalize to the same string → silent scroll-cache\n // key collision (positions clobber each other). Replacing the value\n // with a sentinel string breaks the collision while keeping the\n // canonical form deterministic. The sentinels are intentionally\n // ASCII-only and lexically distinct from valid JSON-stringified\n // values; consumers will see `\"<fn>\"` / `\"<sym>\"` if they ever\n // round-trip the cache key, signalling the substitution clearly.\n if (typeof val === \"function\") {\n return \"<fn>\";\n }\n if (typeof val === \"symbol\") {\n return \"<sym>\";\n }\n\n if (val !== null && typeof val === \"object\" && !Array.isArray(val)) {\n // Null-prototype accumulator: a plain `{}` would interpret\n // `sorted[\"__proto__\"] = x` as a prototype assignment (silently dropped\n // from JSON.stringify output AND a prototype-pollution vector). Mirrors\n // the same guard in `@real-router/sources/canonicalJson`. The two\n // implementations are still intentionally divergent (see the doc-block\n // on [[canonicalJson]] above), but prototype-safety is non-negotiable\n // on both. Lock-test: scrollRestoreKey.properties.ts Invariant 11.\n const sorted = Object.create(null) as Record<string, unknown>;\n // eslint-disable-next-line unicorn/no-array-sort -- ng-packagr uses pre-ES2023 lib; toSorted unavailable\n const keys = Object.keys(val).sort((left: string, right: string) =>\n left.localeCompare(right),\n );\n\n for (const key of keys) {\n sorted[key] = (val as Record<string, unknown>)[key];\n }\n\n return sorted;\n }\n\n return val;\n}\n","import { getTransitionSource } from \"@real-router/sources\";\n\nimport type { NavigationOptions, Router } from \"@real-router/core\";\n\n/**\n * Router-coordinated scroll spy (#575).\n *\n * On `IntersectionObserver` notifications the utility picks the topmost\n * visible anchor inside the configured scroll container and emits a forced\n * same-route transition with `{ hash, replace: true, force: true, hashChange:\n * true }` through `router.navigate(...)`. The URL plugin\n * (`@real-router/browser-plugin` or `@real-router/navigation-plugin`) updates\n * `state.context.url.hash` so sibling hash-aware `<Link hash>` re-highlights\n * via the standard `createActiveRouteSource` pipeline.\n *\n * **Anti-flicker gates** (RFC §5.2):\n * 1. `getTransitionSource(router).getSnapshot().isTransitioning` — skip emits\n * while a transition is in-flight (re-entrant lock).\n * 2. `coolingDown` — set on a user-driven hash transition (e.g. `<Link hash>`\n * click + smooth `scrollIntoView`). Cleared on `scrollend` or after a\n * 500ms safety timeout. Spy's own emits are excluded via the synchronous\n * `selfEmitting` flag — required so the spy doesn't rate-limit itself.\n *\n * **Self-healing** (RFC §7.3): if the initial URL contains a hash without a\n * matching `id` (e.g. `/page#nonexistent`), the first IO event emitted right\n * after observe()-ing picks the topmost real anchor and corrects the URL.\n *\n * **Hash-only transition pipeline cost** (RFC §5.3): for same-route same-\n * params hash-only navigations, `getTransitionPath` returns empty\n * `toDeactivate` / `toActivate` arrays, so `runGuards` is a no-op. The only\n * work is the URL plugin's `onTransitionSuccess` write and the\n * `getTransitionSource` flip — cheap.\n *\n * **Architecture**: decomposed into 4 private subsystem closure factories\n * (`createUrlPluginDetector`, `createCooldown`, `createDebouncer`,\n * `createObserverPair`). The main `createScrollSpy` wires them together\n * around the shared `silenced` / `destroyed` / `selfEmitting` flags and the\n * `flush()` emit logic. Each subsystem owns its state + cleanup; `destroy()`\n * delegates to each. See section banners below.\n *\n * @returns A `ScrollSpy` handle whose `destroy()` is idempotent.\n */\nexport interface ScrollSpyOptions {\n /**\n * CSS selector for anchor candidates. Empty string `\"\"` or `undefined`\n * disables the spy (returns a NOOP handle). Common values:\n * `\"[id]\"`, `\"[id]:is(h1,h2,h3)\"`, `\"section[id]\"`.\n */\n selector: string;\n\n /**\n * `IntersectionObserver` `rootMargin`. Default\n * `\"-20% 0px -60% 0px\"` — an anchor is considered \"active\" once it crosses\n * into the top 20 % of the viewport (or scroll container).\n */\n rootMargin?: string | undefined;\n\n /**\n * Lazy getter for the scrollable container. Resolved on every event.\n * `null` (or missing getter) falls back to the window viewport\n * (`root: null` on the `IntersectionObserver`).\n */\n scrollContainer?: (() => HTMLElement | null) | undefined;\n}\n\nexport interface ScrollSpy {\n /** Tear down observer + listeners. Idempotent. */\n destroy: () => void;\n}\n\nconst NOOP_INSTANCE: ScrollSpy = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\n// Hardcoded internals (RFC §5.1 — promote only with evidence).\nconst RAF_DEBOUNCE_MS = 150;\nconst MUTATION_DEBOUNCE_MS = 250;\nconst COOLDOWN_TIMEOUT_MS = 500;\nconst DEFAULT_ROOT_MARGIN = \"-20% 0px -60% 0px\";\n\n// Local extension type — browser-plugin / navigation-plugin augment\n// `NavigationOptions` with `hash` and `hashChange`, but `shared/dom-utils`\n// is plugin-agnostic and cannot rely on the augmentation. Mirrors the\n// `HashAwareNavigationOptions` pattern in `link-utils.ts`.\ntype HashAwareNavigationOptions = NavigationOptions & {\n hash?: string;\n hashChange?: boolean;\n};\n\ninterface UrlContextSlice {\n hash?: string;\n hashChanged?: boolean;\n}\n\nconst getUrlContext = (state: {\n context?: unknown;\n}): UrlContextSlice | undefined =>\n (state.context as { url?: UrlContextSlice } | undefined)?.url;\n\n// =============================================================================\n// Picker — pure, no state. RFC §5.2 selection rule.\n// =============================================================================\n\n// Pick the anchor closest to the active zone top in viewport coordinates.\n// `entry.rootBounds.top` already reflects `rootMargin` (per W3C IO spec\n// §3.3) — for `rootMargin: \"-20% 0px -60% 0px\"` it returns 20% of root\n// height, for `\"-50% 0px -50% 0px\"` it returns the center, etc. Distance\n// = boundingClientRect.top − zoneTop in viewport pixels: positive = anchor\n// below zone top (just entered), negative = anchor above zone top (body\n// crossing zone from above). We prefer smallest non-negative; fall back to\n// least-negative when no entry has crossed yet.\n// Falls back to zoneTop = 0 when rootBounds is null (cross-origin roots,\n// unit tests). Single pass — handles `Iterable` so flushes can pass\n// `Map.values()` directly without realising the array.\nconst pickTopmost = (\n entries: Iterable<IntersectionObserverEntry>,\n): IntersectionObserverEntry | null => {\n let bestPositive: IntersectionObserverEntry | null = null;\n let bestPositiveDist = Number.POSITIVE_INFINITY;\n let bestNegative: IntersectionObserverEntry | null = null;\n let bestNegativeDist = Number.NEGATIVE_INFINITY;\n\n for (const entry of entries) {\n if (!entry.isIntersecting) {\n continue;\n }\n\n const zoneTop = entry.rootBounds?.top ?? 0;\n const distance = entry.boundingClientRect.top - zoneTop;\n\n if (distance >= 0) {\n if (distance < bestPositiveDist) {\n bestPositive = entry;\n bestPositiveDist = distance;\n }\n } else if (distance > bestNegativeDist) {\n bestNegative = entry;\n bestNegativeDist = distance;\n }\n }\n\n return bestPositive ?? bestNegative;\n};\n\n// =============================================================================\n// Subsystem: URL plugin detector (RFC §5.5)\n// Calls `onMissing` if `state.context` is published but `url` key is missing\n// (i.e. no URL plugin installed). Either synchronous on start, or deferred\n// via a one-shot `router.subscribe` if the router has not started yet.\n// `silenced` flag itself lives in main scope — detector signals via callback\n// (per Oracle Q1 — `silenced` has multiple unrelated triggers; main scope\n// owns the kill switch).\n// =============================================================================\n\ninterface UrlPluginDetector {\n destroy: () => void;\n}\n\nconst createUrlPluginDetector = (\n router: Router,\n onMissing: () => void,\n): UrlPluginDetector => {\n let detectionUnsub: (() => void) | null = null;\n\n const verify = (state: { context?: unknown }): void => {\n const context = state.context as\n | (Record<string, unknown> & { url?: unknown })\n | undefined;\n\n if (context && context.url === undefined) {\n console.warn(\n \"[real-router] scroll-spy: state.context.url is not claimed. \" +\n \"Spy requires browser-plugin or navigation-plugin. Disabling.\",\n );\n onMissing();\n }\n };\n\n const peekState = router.getState();\n\n if (peekState) {\n verify(peekState);\n } else {\n // Re-entry guard: `router.subscribe` MAY invoke the callback synchronously\n // from inside `.subscribe(...)` before the function returns. In that case\n // `detectionUnsub` is still `null` when the callback fires. Without this\n // boolean, a hypothetical multi-fire would double-warn.\n let detectionConsumed = false;\n\n detectionUnsub = router.subscribe(({ route }) => {\n if (detectionConsumed) {\n return;\n }\n\n detectionConsumed = true;\n verify(route);\n\n detectionUnsub?.();\n detectionUnsub = null;\n });\n }\n\n return {\n destroy(): void {\n detectionUnsub?.();\n detectionUnsub = null;\n },\n };\n};\n\n// =============================================================================\n// Subsystem: Cooldown gate (RFC §5.2 — anti-flicker for smooth scrollIntoView)\n// Set on user-driven `<Link hash>` click → smooth scroll. Cleared on\n// `scrollend` (Baseline 2026) or 500ms safety timeout (older Safari).\n// =============================================================================\n\ninterface Cooldown {\n readonly active: boolean;\n start: () => void;\n destroy: () => void;\n}\n\nconst createCooldown = (getContainer: () => HTMLElement | null): Cooldown => {\n let active = false;\n let timeout: ReturnType<typeof setTimeout> | null = null;\n let listenerContainer: HTMLElement | null = null;\n let listener: (() => void) | null = null;\n\n const clear = (): void => {\n if (timeout !== null) {\n clearTimeout(timeout);\n timeout = null;\n }\n\n if (listener) {\n const target: EventTarget = listenerContainer ?? globalThis;\n\n target.removeEventListener(\"scrollend\", listener);\n }\n\n listener = null;\n listenerContainer = null;\n active = false;\n };\n\n return {\n get active(): boolean {\n return active;\n },\n start(): void {\n // Reset rather than stack timers if cooldown is already active.\n clear();\n\n active = true;\n\n const lift = (): void => {\n clear();\n };\n\n listener = lift;\n listenerContainer = getContainer();\n\n const target: EventTarget = listenerContainer ?? globalThis;\n\n target.addEventListener(\"scrollend\", lift, { once: true });\n\n timeout = setTimeout(lift, COOLDOWN_TIMEOUT_MS);\n },\n destroy(): void {\n clear();\n },\n };\n};\n\n// =============================================================================\n// Subsystem: rAF + trailing debounce (RFC §5.1)\n// Coalesces a burst of IO events into ≤ 1 callback per debounce window.\n// rAF reduces N setTimeout creations to 1 per animation frame; the trailing\n// 150ms setTimeout waits for the IO stream to quiesce.\n// =============================================================================\n\ninterface Debouncer {\n schedule: () => void;\n destroy: () => void;\n}\n\nconst createDebouncer = (\n callback: () => void,\n trailingMs: number,\n): Debouncer => {\n let raf: number | null = null;\n let timeout: ReturnType<typeof setTimeout> | null = null;\n\n return {\n schedule(): void {\n if (raf !== null) {\n return;\n }\n\n raf = requestAnimationFrame(() => {\n raf = null;\n\n if (timeout !== null) {\n clearTimeout(timeout);\n }\n\n timeout = setTimeout(() => {\n timeout = null;\n callback();\n }, trailingMs);\n });\n },\n destroy(): void {\n if (raf !== null) {\n cancelAnimationFrame(raf);\n raf = null;\n }\n\n if (timeout !== null) {\n clearTimeout(timeout);\n timeout = null;\n }\n },\n };\n};\n\n// =============================================================================\n// Subsystem: Observer pair (IntersectionObserver + MutationObserver)\n// IO + MO genuinely form one subsystem — both write/read `observed` set and\n// `pending` map, and reconcile flow couples them. Per Oracle Q10, splitting\n// would force cross-subsystem references that re-introduce the wiring\n// problem we're trying to solve.\n//\n// Exposes `pending` directly (per Oracle Q4: hiding behind `consume()` adds\n// boilerplate without isolating the shared mutable state — observers write\n// from IO callbacks while main scope reads in `flush()`).\n// =============================================================================\n\ninterface ObserverPair {\n readonly pending: Map<Element, IntersectionObserverEntry>;\n destroy: () => void;\n}\n\nconst createObserverPair = (\n selector: string,\n rootMargin: string,\n getContainer: () => HTMLElement | null,\n onIntersection: () => void,\n onInvalidSelector: () => void,\n isStopped: () => boolean,\n): ObserverPair => {\n const observed = new Set<Element>();\n // Latest IO entry per target — accumulated across batches. IO delivers\n // entries only for targets whose intersection state CHANGED (W3C IO\n // §3.2.1), so a fast scroll that lands two callbacks inside the same\n // debounce window must merge by target, not overwrite. Entries are\n // dropped from the map when their target leaves the DOM (see `reconcile`)\n // and on `destroy()`.\n const pending = new Map<Element, IntersectionObserverEntry>();\n\n let duplicateIdWarned = false;\n let mutationTimer: ReturnType<typeof setTimeout> | null = null;\n\n const handleIntersection: IntersectionObserverCallback = (entries) => {\n // Defensive: IO callback may fire AFTER `destroy()` if a queued event\n // was already scheduled by the browser before `disconnect()`. Cheap\n // belt-and-suspenders.\n if (isStopped()) {\n return;\n }\n\n for (const entry of entries) {\n pending.set(entry.target, entry);\n }\n\n onIntersection();\n };\n\n const io = new IntersectionObserver(handleIntersection, {\n root: getContainer(),\n rootMargin,\n threshold: 0,\n });\n\n const observeMatches = (): void => {\n const scope = getContainer() ?? document;\n let candidates: NodeListOf<Element>;\n\n try {\n candidates = scope.querySelectorAll(selector);\n } catch {\n onInvalidSelector();\n\n return;\n }\n\n const seenIds = new Set<string>();\n\n for (const element of candidates) {\n // Detect duplicate ids once (RFC §7.7). The DOM permits duplicate ids\n // even though it is a markup bug; the spy keeps working but picks the\n // first one deterministically via the topmost-visible rule.\n const id = (element as HTMLElement).id;\n\n if (id && !duplicateIdWarned) {\n if (seenIds.has(id)) {\n duplicateIdWarned = true;\n\n console.warn(\n `[real-router] scroll-spy: duplicate id \"${id}\" observed. ` +\n \"Selection picks the topmost visible match deterministically.\",\n );\n }\n\n seenIds.add(id);\n }\n\n if (observed.has(element)) {\n continue;\n }\n\n io.observe(element);\n observed.add(element);\n }\n };\n\n const reconcile = (): void => {\n // Drop observed elements that left the DOM. Avoids observer holding\n // strong refs to detached nodes. Also drop their accumulated entry so\n // stale \"was intersecting\" state for a removed node cannot be picked\n // by `pickTopmost` after the node is gone.\n for (const element of observed) {\n if (!element.isConnected) {\n io.unobserve(element);\n observed.delete(element);\n pending.delete(element);\n }\n }\n\n observeMatches();\n };\n\n observeMatches();\n\n // MutationObserver targets the scroll container (or document.body for\n // window viewport). `childList: true, subtree: true` catches structural\n // changes; `attributes: true, attributeFilter: [\"id\"]` catches anchor\n // id renames (typical for client-rendered docs).\n const mutationTarget = getContainer() ?? document.body;\n\n const mo = new MutationObserver(() => {\n if (mutationTimer !== null) {\n clearTimeout(mutationTimer);\n }\n\n mutationTimer = setTimeout(() => {\n mutationTimer = null;\n reconcile();\n }, MUTATION_DEBOUNCE_MS);\n });\n\n mo.observe(mutationTarget, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: [\"id\"],\n });\n\n return {\n pending,\n destroy(): void {\n io.disconnect();\n mo.disconnect();\n\n if (mutationTimer !== null) {\n clearTimeout(mutationTimer);\n mutationTimer = null;\n }\n\n observed.clear();\n pending.clear();\n },\n };\n};\n\n// =============================================================================\n// Main: compositional wiring\n// =============================================================================\n\nexport function createScrollSpy(\n router: Router,\n options: ScrollSpyOptions,\n): ScrollSpy {\n // SSR guard (RFC §7.5) — return early without warnings.\n if (typeof document === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n // Feature-detect IntersectionObserver — no polyfill ships (RFC §4).\n if (typeof IntersectionObserver === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n const { selector } = options;\n\n // Empty selector → disabled. Documented opt-out for conditional enabling\n // (RFC §5.4 `scrollSpy={{ selector: enable ? \"[id]\" : \"\" }}`).\n if (!selector) {\n return NOOP_INSTANCE;\n }\n\n const rootMargin = options.rootMargin ?? DEFAULT_ROOT_MARGIN;\n const getContainer = options.scrollContainer;\n const resolveContainer = (): HTMLElement | null => getContainer?.() ?? null;\n\n // Shared lifecycle flags (Oracle Q1 — `silenced` has multiple unrelated\n // triggers; Oracle Q3 — `selfEmitting` synchronously bracketed around\n // `router.navigate()` cannot cleanly extract). Kept in main scope.\n let destroyed = false;\n let silenced = false;\n let selfEmitting = false;\n\n const isStopped = (): boolean => silenced || destroyed;\n\n // Symmetric late-binding (Oracle Q2): declare `flush` as nullable, wire\n // debouncer + observers, then assign the real implementation. Reads as\n // intentional wiring rather than accidental closure capture ordering.\n // The `flush?.()` call below safely no-ops if a callback somehow fires\n // before assignment (impossible in practice — IO/debounce are async).\n let flush: (() => void) | null = null;\n\n const transitionSource = getTransitionSource(router);\n\n const detector = createUrlPluginDetector(router, () => {\n silenced = true;\n });\n\n const cooldown = createCooldown(resolveContainer);\n\n const debouncer = createDebouncer(() => {\n flush?.();\n }, RAF_DEBOUNCE_MS);\n\n const observers = createObserverPair(\n selector,\n rootMargin,\n resolveContainer,\n () => {\n debouncer.schedule();\n },\n () => {\n if (silenced) {\n return;\n }\n\n silenced = true;\n\n console.warn(\n `[real-router] scroll-spy: invalid selector \"${selector}\". Disabling.`,\n );\n },\n isStopped,\n );\n\n flush = (): void => {\n if (destroyed || silenced) {\n observers.pending.clear();\n\n return;\n }\n\n // Gate-skipped flushes keep `pendingEntries` populated — the merged\n // state is still the best-known snapshot, and the next non-gated flush\n // consumes it. Clearing under a gate would re-introduce the overwrite\n // bug for any anchor whose intersection state did not change during\n // the gate window.\n if (transitionSource.getSnapshot().isTransitioning) {\n return;\n }\n\n if (cooldown.active) {\n return;\n }\n\n if (observers.pending.size === 0) {\n return;\n }\n\n // Successful flush consumes the merged snapshot. We clear so that the\n // next debounce window starts fresh; an anchor that is still\n // intersecting will only stay observable if IO emits another event for\n // it (which it does whenever the anchor's intersection state actually\n // changes). Skipping the clear here would leak state from one user-\n // perceived \"scroll stop\" into the next.\n const picked = pickTopmost(observers.pending.values());\n\n observers.pending.clear();\n\n if (!picked) {\n // No anchor visible / above zone — preserve last hash (RFC §10 #5).\n return;\n }\n\n const newHash = (picked.target as HTMLElement).id;\n\n if (!newHash) {\n return;\n }\n\n const state = router.getState();\n\n if (!state) {\n return;\n }\n\n const currentHash = getUrlContext(state)?.hash ?? \"\";\n\n if (newHash === currentHash) {\n return;\n }\n\n // Emit the same-route same-params hash-only transition. URL plugin\n // writes `state.context.url.hash = newHash` + `hashChanged = true` in\n // its `onTransitionSuccess` claim.\n const opts: HashAwareNavigationOptions = {\n hash: newHash,\n replace: true,\n force: true,\n hashChange: true,\n };\n\n // Self-emit guard (RFC §5.2): set synchronously around our own\n // `router.navigate()` so the `router.subscribe` callback skips the\n // cooldown setup for spy-emitted transitions — otherwise spy would\n // rate-limit itself to ≤ 2 emits/s, contradicting the ≤ 10/s benchmark\n // target. Test coupling (Q8): preserve exact `.catch(noop).finally(reset)`\n // chain — migrating to `try/finally` over `await router.navigate(...)`\n // changes microtask schedule and breaks \"spy continues after rejection\".\n selfEmitting = true;\n router\n .navigate(state.name, state.params, opts)\n .catch(() => {\n // Fire-and-forget — suppress expected rejections (concurrent\n // navigate, router stopped, etc.) consistent with `<Link>` adapter\n // patterns.\n })\n .finally(() => {\n selfEmitting = false;\n });\n };\n\n // Cooldown setup on user-driven hash transitions. Spy's own emits are\n // distinguished via the synchronous `selfEmitting` flag (see `flush`).\n const unsubscribeRouter = router.subscribe(({ route }) => {\n if (selfEmitting) {\n return;\n }\n\n if (getUrlContext(route)?.hashChanged) {\n cooldown.start();\n }\n });\n\n return {\n destroy(): void {\n if (destroyed) {\n return;\n }\n\n destroyed = true;\n\n // Unsubscribe FIRST to prevent late-arriving router transition\n // callback from calling `cooldown.start()` on a half-destroyed\n // instance. Without this ordering, a transition with `hashChanged:\n // true` firing between subsystem teardown and `unsubscribeRouter()`\n // would re-install a 500ms timer that survives `destroy()`. Verified\n // via Oracle review (Q5/Q7).\n unsubscribeRouter();\n\n observers.destroy();\n debouncer.destroy();\n cooldown.destroy();\n detector.destroy();\n },\n };\n}\n","import type { Router } from \"@real-router/core\";\n\nexport interface ViewTransitions {\n destroy: () => void;\n}\n\nconst NOOP_INSTANCE: ViewTransitions = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\nexport function createViewTransitions(router: Router): ViewTransitions {\n if (\n typeof document === \"undefined\" ||\n typeof document.startViewTransition !== \"function\"\n ) {\n return NOOP_INSTANCE;\n }\n\n let closeVT: (() => void) | null = null;\n let currentVT: { skipTransition?: () => void } | null = null;\n // Tracks whether TRANSITION_SUCCESS fired for the current leave. Used to\n // distinguish \"benign cleanup abort\" (router's async path aborts its own\n // controller in a finally block after successful navigation) from \"real\n // cancellation\" (concurrent navigate, guard rejection, dispose).\n let successFired = false;\n\n const resolveAndClear = (): void => {\n closeVT?.();\n closeVT = null;\n };\n\n const offLeave = router.subscribeLeave(({ signal }) => {\n // Reentrant abort: signal already aborted when we're called. Open no VT\n // — router will fall through to TRANSITION_CANCELLED via isCurrentNav()\n // after leave resolves. addEventListener(\"abort\", ...) does not re-fire\n // for past events, so skipping startViewTransition is the safe path.\n if (signal.aborted) {\n return;\n }\n\n successFired = false;\n resolveAndClear();\n\n // Return a Promise so the router awaits until the browser invokes\n // updateCallback. This ensures old DOM snapshot is captured BEFORE the\n // router commits the new state — giving correct exit→state→entry\n // ordering (vs fire-and-forget, where URL changes before VT captures).\n return new Promise<void>((resolveLeave) => {\n // Capture the resolver synchronously BEFORE startViewTransition() is\n // called. The browser invokes updateCallback in a later task, but\n // router.subscribe (TRANSITION_SUCCESS) can fire before that. If we\n // captured `resolve` inside the callback, subscribe would see closeVT\n // still null and skip resolving — the deferred would hang for 4s\n // until the VT API aborts with TimeoutError.\n const deferred = new Promise<void>((resolve) => {\n closeVT = resolve;\n });\n\n signal.addEventListener(\n \"abort\",\n () => {\n if (successFired) {\n // Router's async path (#finishAsyncNavigation) aborts its own\n // controller in a finally block AFTER completeTransition (and\n // thus AFTER subscribe fired). This is cleanup, not\n // cancellation — VT is progressing normally, do nothing.\n return;\n }\n\n // Real cancellation (concurrent navigate, dispose). Resolve the\n // deferred so updateCallback can complete, skip the VT so no\n // stale animation leaks, and unblock the router if the abort\n // fires before updateCallback was invoked.\n resolveAndClear();\n currentVT?.skipTransition?.();\n resolveLeave();\n },\n { once: true },\n );\n\n try {\n currentVT = document.startViewTransition(() => {\n // Resolving here unblocks the router at the moment the browser\n // enters updateCallback — by spec, old DOM snapshot is captured\n // before this callback runs. Router now proceeds through\n // activation guards and setState; the VT animation waits on\n // `deferred`, which is resolved from router.subscribe after a\n // task-queue tick (see NOTE on setTimeout below).\n resolveLeave();\n\n return deferred;\n });\n } catch {\n // Defensive: spec says startViewTransition doesn't throw under\n // normal conditions, but Chromium has had edge cases (detached\n // document, extension interference). Clean up and unblock router.\n resolveAndClear();\n resolveLeave();\n }\n });\n });\n\n const offSuccess = router.subscribe(() => {\n const resolver = closeVT;\n\n successFired = true;\n closeVT = null;\n\n if (resolver === null) {\n currentVT = null;\n } else {\n // CRITICAL: CANNOT use requestAnimationFrame here. When the router\n // takes the async path (leave returned a Promise), subscribe fires\n // AFTER the browser has already transitioned VT into the\n // \"update-callback-called\" phase. In that phase Chromium sets\n // rendering suppression to true, which ALSO blocks rAF callbacks.\n // rAF would never fire → deferred never resolves → browser aborts\n // vt.ready with TimeoutError after 4s (observed in Chromium).\n //\n // setTimeout runs on the task queue independent of the rendering\n // pipeline, so it fires regardless of suppression. React's scheduler\n // uses MessageChannel tasks, which are queued before our setTimeout,\n // so the new DOM is committed by the time our callback runs.\n setTimeout(() => {\n resolver();\n currentVT = null;\n }, 0);\n }\n });\n\n return {\n destroy: () => {\n offLeave();\n offSuccess();\n currentVT?.skipTransition?.();\n currentVT = null;\n resolveAndClear();\n },\n };\n}\n","import type {\n NavigationOptions,\n Params,\n Router,\n State,\n} from \"@real-router/core\";\n\nexport function shouldNavigate(evt: MouseEvent): boolean {\n return (\n evt.button === 0 &&\n !evt.metaKey &&\n !evt.altKey &&\n !evt.ctrlKey &&\n !evt.shiftKey\n );\n}\n\n// Matches a single percent-escape triple (`%` + two hex digits). Used as\n// the \"already-encoded\" probe in `encodeFragmentInline` below — see the\n// idempotency rationale there.\nconst PERCENT_ESCAPE_PROBE = /%[\\dA-Fa-f]{2}/;\n\n/**\n * RFC 3986 fragment encoding: preserve sub-delims (`&`, `=`, `?`, `:`),\n * encode space, `%`, control chars, non-ASCII via encodeURI; defensively\n * escape `#` (encodeURI does not). Mirrors `encodeHashFragment` in\n * `shared/browser-env/url-context.ts` — duplicated here because the\n * shared/dom-utils symlink graph does not reach shared/browser-env.\n *\n * **Idempotency for pre-encoded input (audit-2026-05-17 §5 MEDIUM E.1).**\n * The doc-comment on `<Link hash>` says the value is a \"decoded fragment\n * without leading #\". But realistic consumers copy hashes out of\n * `location.hash` (which is percent-encoded) and pass them back, so the\n * naive `encodeURI(\"%20\")` would double-encode into `\"%2520\"` and break\n * anchor lookup. We detect a percent-escape triple in the input and, if\n * present, decode + re-encode for idempotency. Malformed `%XX` (e.g.\n * `\"%2\"` or `\"%ZZ\"`) makes `decodeURIComponent` throw — in that case we\n * fall through to plain `encodeURI`, which never throws.\n */\nfunction encodeFragmentInline(decoded: string): string {\n if (PERCENT_ESCAPE_PROBE.test(decoded)) {\n try {\n const roundtrip = decodeURIComponent(decoded);\n\n return encodeURI(roundtrip).replaceAll(\"#\", \"%23\");\n } catch {\n // Malformed `%XX` — fall through to the plain encoding path.\n // encodeURI does not throw on malformed escapes; it treats the\n // `%` as a literal and percent-encodes it (`%2` → `%252`).\n }\n }\n\n return encodeURI(decoded).replaceAll(\"#\", \"%23\");\n}\n\ntype BuildUrlFn = (\n name: string,\n params: Params,\n options?: { hash?: string },\n) => string | undefined;\n\n/**\n * Builds an href for a `<Link>` element.\n *\n * - Prefers the URL plugin's `buildUrl` (browser-plugin, navigation-plugin,\n * hash-plugin) when present.\n * - Falls back to `router.buildPath` for runtimes without a URL plugin\n * (memory-plugin, console UIs, NativeScript). In that fallback the hash\n * is appended manually so the rendered href is still correct.\n * - The optional 4th argument is an options object so the contract stays\n * extensible. The `hash` option is a decoded fragment without leading \"#\";\n * `<Link hash=\"#section\">` is accepted defensively (leading \"#\" stripped).\n * Frozen API: previous 3-arg call sites continue to work unchanged.\n */\nexport function buildHref(\n router: Router,\n routeName: string,\n routeParams: Params,\n options?: { hash?: string },\n): string | undefined {\n try {\n const rawHash = options?.hash;\n let normHash: string | undefined;\n\n if (rawHash !== undefined) {\n normHash = rawHash.startsWith(\"#\") ? rawHash.slice(1) : rawHash;\n }\n\n const buildUrl = router.buildUrl as BuildUrlFn | undefined;\n\n if (buildUrl) {\n const url = buildUrl(\n routeName,\n routeParams,\n normHash === undefined ? undefined : { hash: normHash },\n );\n\n // Accept only non-empty strings. The BuildUrlFn type contract is\n // `string | undefined`, but defensive against:\n // - `\"\"` (empty string) → would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - `null` (type-contract violation) → would render `<a href={null}>`,\n // stringified to `\"null\"` in some renderers.\n // Either case falls through to the `router.buildPath` fallback below.\n if (typeof url === \"string\" && url.length > 0) {\n return url;\n }\n }\n\n const path = router.buildPath(routeName, routeParams);\n\n // Symmetric to the buildUrl guard above (#S1 audit, Invariant 12).\n // `router.buildPath` is typed `string`, but defends against:\n // - `\"\"` (empty string) — would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - non-string type-contract violations from custom path-matchers.\n // Both yield `undefined` (renderer drops the attribute) with a warning.\n if (typeof path !== \"string\" || path.length === 0) {\n console.error(\n `[real-router] Route \"${routeName}\" yielded an empty path. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n\n return normHash ? `${path}#${encodeFragmentInline(normHash)}` : path;\n } catch {\n console.error(\n `[real-router] Route \"${routeName}\" is not defined. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n}\n\n/**\n * `<Link>` click-handler navigation helper (#532).\n *\n * Wraps `router.navigate(name, params, opts)` with same-route different-hash\n * detection: when the consumer clicks a hash-bearing Link that targets the\n * current route with the same params but a different fragment, core's\n * SAME_STATES check would otherwise reject the navigation. The helper adds\n * `force: true` and `hashChange: true` automatically — subscribers can then\n * disambiguate via `state.context.url.hashChanged`.\n *\n * For pure programmatic same-route hash-only navigation, callers are\n * documented to pass `{ force: true }` themselves; the auto-bypass here is\n * a UX convenience for `<Link hash>` that all 6 framework adapters share.\n */\n/**\n * Local extended-options type. Adapters that depend only on `@real-router/core`\n * (without a URL plugin) do not see the `NavigationOptions` augmentation that\n * declares `hash` / `hashChange`. Casting to this widened type inside the\n * helper keeps shared/dom-utils self-contained — adapters do not need to\n * augment NavigationOptions themselves to consume `<Link hash>`.\n */\ntype HashAwareNavigationOptions = NavigationOptions & {\n hash?: string;\n hashChange?: boolean;\n};\n\nexport function navigateWithHash(\n router: Router,\n routeName: string,\n routeParams: Params,\n hash: string | undefined,\n extraOptions?: NavigationOptions,\n): Promise<State> {\n const opts: HashAwareNavigationOptions = { ...extraOptions };\n\n if (hash !== undefined) {\n opts.hash = hash;\n }\n\n const current = router.getState();\n\n if (\n current?.name === routeName &&\n shallowEqual(current.params, routeParams)\n ) {\n const currentHash =\n (current.context as { url?: { hash?: string } } | undefined)?.url?.hash ??\n \"\";\n const newHash = hash ?? currentHash;\n\n if (currentHash !== newHash) {\n opts.force = true;\n opts.hashChange = true;\n }\n }\n\n return router.navigate(routeName, routeParams, opts);\n}\n\n// Match-any-whitespace regex shared across calls. RegExp literals at\n// call-site recompile in some engines; lifting it avoids that microcost\n// for the slow-path branch.\nconst WHITESPACE_PROBE = /\\s/;\nconst WHITESPACE_SPLIT = /\\S+/g;\n\nfunction parseTokens(value: string | undefined): string[] {\n if (!value) {\n return [];\n }\n\n // Hot-path fast-path (audit-2026-05-17 §8b #1): >99% of active-class\n // inputs at `<Link>` emit are single-token strings like `\"active\"` or\n // `\"is-current\"` — no whitespace, no leading/trailing pad. Skip the\n // regex match and Array result allocation: a literal `[value]` works\n // because the slow-path `match(/\\S+/g)` would return exactly `[value]`\n // for the same input. PBT lock: linkUtils.properties.ts Invariant 13.\n if (!WHITESPACE_PROBE.test(value)) {\n return [value];\n }\n\n return value.match(WHITESPACE_SPLIT) ?? [];\n}\n\nexport function buildActiveClassName(\n isActive: boolean,\n activeClassName: string | undefined,\n baseClassName: string | undefined,\n): string | undefined {\n if (isActive && activeClassName) {\n const activeTokens = parseTokens(activeClassName);\n\n if (activeTokens.length === 0) {\n return baseClassName ?? undefined;\n }\n if (!baseClassName) {\n return activeTokens.join(\" \");\n }\n\n const baseTokens = parseTokens(baseClassName);\n const seen = new Set(baseTokens);\n\n for (const token of activeTokens) {\n if (!seen.has(token)) {\n seen.add(token);\n baseTokens.push(token);\n }\n }\n\n return baseTokens.join(\" \");\n }\n\n return baseClassName ?? undefined;\n}\n\n/**\n * One-level structural equality using `Object.is` per key.\n *\n * **String-keyed properties only (Mini-sprint E.3 — audit-5 §4.2 #3).**\n * Implementation walks `Object.keys()` which by spec returns only\n * enumerable own STRING keys. Symbol-keyed properties — created via\n * `obj[Symbol(\"brand\")] = value` or `{ [Symbol(...)]: value }` — are\n * NOT compared. Two records that differ only in a Symbol-keyed value\n * will compare as equal.\n *\n * This is intentional: route params and Link options are documented as\n * string-keyed primitives (string | number | boolean) — Symbol-keyed\n * metadata (e.g. brand markers, private state) doesn't belong in a\n * cache-key comparison. Switching to `Reflect.ownKeys()` would extend\n * the contract to symbols at the cost of one extra allocation per call\n * (Reflect.ownKeys composes string-keys + symbol-keys arrays). If a\n * consumer relies on symbol-keyed metadata for navigation\n * disambiguation, they should encode it into a string key instead.\n *\n * Mirrors React's `shallowEqual` (packages/shared/shallowEqual.js) in\n * both the string-keys-only semantics and the `hasOwnProperty` guard\n * below.\n */\nexport function shallowEqual(\n prev: object | undefined,\n next: object | undefined,\n): boolean {\n if (Object.is(prev, next)) {\n return true;\n }\n if (!prev || !next) {\n return false;\n }\n\n const prevKeys = Object.keys(prev);\n\n if (prevKeys.length !== Object.keys(next).length) {\n return false;\n }\n\n const prevRecord = prev as Record<string, unknown>;\n const nextRecord = next as Record<string, unknown>;\n\n for (const key of prevKeys) {\n // hasOwnProperty guard: without it, a key missing in `next` reads as\n // `undefined` and falsely matches `prev[key] === undefined`. Same shape\n // as React's shallowEqual (packages/shared/shallowEqual.js).\n if (\n !Object.prototype.hasOwnProperty.call(next, key) ||\n !Object.is(prevRecord[key], nextRecord[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function applyLinkA11y(element: HTMLElement | null | undefined): void {\n if (!element) {\n return;\n }\n\n // Cross-realm safety (audit-2026-05-17 §5 HIGH #4):\n // `instanceof HTMLAnchorElement` compares against the constructor from\n // the CURRENT realm. An element created in a different window (iframe\n // contentDocument, micro-frontend, embedded widget) fails the check\n // even when it IS a real anchor — the helper would then inject\n // role=\"link\" + tabindex=\"0\" on top of native anchor semantics,\n // breaking screen reader output (\"link link\") and focus order.\n //\n // tagName is realm-agnostic and is uppercase for HTML-namespaced\n // elements in any document. SVG `<a>` has lowercase tagName plus a\n // different prototype (SVGAElement) — skipping it here is wrong by\n // accident: SVG anchors don't have keyboard activation semantics the\n // helper would add. But they also don't reach this helper in\n // practice (router Link components emit HTML anchors). Lock the\n // uppercase compare to keep the contract narrow.\n const tag = element.tagName;\n\n if (tag === \"A\" || tag === \"BUTTON\") {\n return;\n }\n if (!element.hasAttribute(\"role\")) {\n element.setAttribute(\"role\", \"link\");\n }\n if (!element.hasAttribute(\"tabindex\")) {\n element.setAttribute(\"tabindex\", \"0\");\n }\n}\n","import { createActiveRouteSource } from \"@real-router/sources\";\nimport { useMemo, useSyncExternalStore } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { Params } from \"@real-router/core\";\n\nexport function useIsActiveRoute(\n routeName: string,\n params?: Params,\n strict = false,\n ignoreQueryParams = true,\n hash?: string,\n): boolean {\n const router = useRouter();\n\n // createActiveRouteSource is per-router + canonical-args cached in\n // @real-router/sources, so passing params by reference is safe — equivalent\n // param shapes hit the same cache entry regardless of key order. The\n // `hash` argument (#532) is part of the cache key when defined: a Link\n // pointing to `/settings#account` shares its source only with other\n // consumers using the same routeName + params + hash.\n //\n // The useMemo wrap skips `canonicalJson(params)` + cache lookup on every\n // render when all primitive deps and the `params` reference are stable —\n // the common case once memo()+shallowEqual has bailed out further up\n // (or when the parent re-renders for a non-Link reason). For inline\n // `params={{id:1}}` the dep changes per render and the lookup still\n // runs, but that path was already the slow path before this memo.\n // exactOptionalPropertyTypes forbids `{ hash: undefined }` literally, so\n // we conditionally spread the key only when the caller passed a value.\n const store = useMemo(\n () =>\n createActiveRouteSource(router, routeName, params, {\n strict,\n ignoreQueryParams,\n ...(hash !== undefined && { hash }),\n }),\n [router, routeName, params, strict, ignoreQueryParams, hash],\n );\n\n return useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n}\n","import { createDismissableError } from \"@real-router/sources\";\nimport {\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\n\nimport { useRouter } from \"../hooks/useRouter\";\n\nimport type { RouterError, State } from \"@real-router/core\";\nimport type { ReactElement, ReactNode } from \"react\";\n\nexport interface RouterErrorBoundaryProps {\n readonly children: ReactNode;\n readonly fallback: (error: RouterError, resetError: () => void) => ReactNode;\n readonly onError?: (\n error: RouterError,\n toRoute: State | null,\n fromRoute: State | null,\n ) => void;\n}\n\nexport function RouterErrorBoundary({\n children,\n fallback,\n onError,\n}: RouterErrorBoundaryProps): ReactElement {\n const router = useRouter();\n // Per-router cached in @real-router/sources — the WeakMap lookup is cheap,\n // but useMemo avoids it entirely on stable-router re-renders (the common\n // case for boundaries mounted in app shells).\n const store = useMemo(() => createDismissableError(router), [router]);\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n\n const onErrorRef = useRef(onError);\n\n // \"Latest ref\" pattern shared with useRouteEnter/useRouteExit: sync the\n // callback to the ref via useLayoutEffect (synchronous, post-render,\n // pre-paint) so the snapshot effect below reads the freshest callback\n // without listing `onError` as a dep — and StrictMode's double-effect\n // pass writes the same value twice harmlessly.\n useLayoutEffect(() => {\n onErrorRef.current = onError;\n });\n\n useEffect(() => {\n if (snapshot.error) {\n onErrorRef.current?.(\n snapshot.error,\n snapshot.toRoute,\n snapshot.fromRoute,\n );\n }\n // eslint-disable-next-line @eslint-react/exhaustive-deps -- onError tracked via ref, snapshot fields accessed inside callback\n }, [snapshot.version]);\n\n return (\n <>\n {children}\n {snapshot.error ? fallback(snapshot.error, snapshot.resetError) : null}\n </>\n );\n}\n","import { useContext } from \"react\";\n\nimport { NavigatorContext } from \"../context\";\n\nimport type { Navigator } from \"@real-router/core\";\n\nexport const useNavigator = (): Navigator => {\n const navigator = useContext(NavigatorContext);\n\n if (!navigator) {\n throw new Error(\"useNavigator must be used within a RouterProvider\");\n }\n\n return navigator;\n};\n","import { getPluginApi } from \"@real-router/core/api\";\nimport { getRouteUtils } from \"@real-router/route-utils\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { RouteUtils } from \"@real-router/route-utils\";\n\n/**\n * Returns a pre-computed {@link RouteUtils} instance for the current router.\n *\n * `getRouteUtils` is WeakMap-cached per `RouteTreeNode` inside\n * `@real-router/route-utils`, so the same router always returns the same\n * `RouteUtils` instance across renders — no local cache needed in the adapter.\n *\n * @returns RouteUtils instance with pre-computed chains and siblings\n *\n * @example\n * ```tsx\n * const utils = useRouteUtils();\n *\n * utils.getChain(\"users.profile\");\n * // → [\"users\", \"users.profile\"]\n *\n * utils.getSiblings(\"users\");\n * // → [\"admin\"]\n *\n * utils.isDescendantOf(\"users.profile\", \"users\");\n * // → true\n * ```\n */\nexport const useRouteUtils = (): RouteUtils => {\n const router = useRouter();\n\n return getRouteUtils(getPluginApi(router).getTree());\n};\n","import { getTransitionSource } from \"@real-router/sources\";\nimport { useSyncExternalStore } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { RouterTransitionSnapshot } from \"@real-router/sources\";\n\nexport function useRouterTransition(): RouterTransitionSnapshot {\n const router = useRouter();\n const store = getTransitionSource(router);\n\n return useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n}\n","import { getNavigator } from \"@real-router/core\";\nimport { createRouteSource } from \"@real-router/sources\";\nimport { useEffect, useMemo, useSyncExternalStore } from \"react\";\n\nimport { NavigatorContext, RouteContext, RouterContext } from \"./context\";\nimport {\n createRouteAnnouncer,\n createScrollRestoration,\n createScrollSpy,\n createViewTransitions,\n} from \"./dom-utils\";\n\nimport type { ScrollRestorationOptions, ScrollSpyOptions } from \"./dom-utils\";\nimport type { Router } from \"@real-router/core\";\nimport type { FC, ReactNode } from \"react\";\n\nexport interface RouteProviderProps {\n router: Router;\n children: ReactNode;\n announceNavigation?: boolean;\n scrollRestoration?: ScrollRestorationOptions;\n scrollSpy?: ScrollSpyOptions;\n viewTransitions?: boolean;\n}\n\nexport const RouterProvider: FC<RouteProviderProps> = ({\n router,\n children,\n announceNavigation,\n scrollRestoration,\n scrollSpy,\n viewTransitions,\n}) => {\n useEffect(() => {\n if (!announceNavigation) {\n return;\n }\n\n const announcer = createRouteAnnouncer(router);\n\n return () => {\n announcer.destroy();\n };\n }, [announceNavigation, router]);\n\n // Primitive deps so inline `{ mode: \"restore\" }` doesn't thrash on every\n // render. scrollContainer is a getter invoked lazily on every event inside\n // the utility — swapping its reference doesn't change the resolved element,\n // so we intentionally omit it from deps to keep inline getters stable.\n const srMode = scrollRestoration?.mode;\n const srAnchor = scrollRestoration?.anchorScrolling;\n const srBehavior = scrollRestoration?.behavior;\n const srStorageKey = scrollRestoration?.storageKey;\n const srEnabled = scrollRestoration !== undefined;\n\n useEffect(() => {\n if (!srEnabled) {\n return;\n }\n\n const sr = createScrollRestoration(router, {\n mode: srMode,\n anchorScrolling: srAnchor,\n behavior: srBehavior,\n storageKey: srStorageKey,\n // srEnabled check above guarantees scrollRestoration is defined.\n scrollContainer: scrollRestoration.scrollContainer,\n });\n\n return () => {\n sr.destroy();\n };\n // scrollRestoration (for scrollContainer) omitted — see comment above.\n // eslint-disable-next-line @eslint-react/exhaustive-deps\n }, [router, srEnabled, srMode, srAnchor, srBehavior, srStorageKey]);\n\n const spySelector = scrollSpy?.selector;\n const spyRootMargin = scrollSpy?.rootMargin;\n const spyEnabled =\n scrollSpy !== undefined && spySelector !== undefined && spySelector !== \"\";\n\n useEffect(() => {\n if (!spyEnabled) {\n return;\n }\n\n const spy = createScrollSpy(router, {\n selector: spySelector,\n rootMargin: spyRootMargin,\n scrollContainer: scrollSpy.scrollContainer,\n });\n\n return () => {\n spy.destroy();\n };\n // scrollSpy (for scrollContainer) omitted — same rationale as\n // scrollRestoration above: getter is invoked lazily inside the utility,\n // identity changes don't affect resolution.\n // eslint-disable-next-line @eslint-react/exhaustive-deps\n }, [router, spyEnabled, spySelector, spyRootMargin]);\n\n useEffect(() => {\n if (!viewTransitions) {\n return;\n }\n\n const vt = createViewTransitions(router);\n\n return () => {\n vt.destroy();\n };\n }, [router, viewTransitions]);\n\n const navigator = useMemo(() => getNavigator(router), [router]);\n\n // useSyncExternalStore manages the router subscription lifecycle:\n // subscribe connects to router on first listener, unsubscribes on last.\n // This is Strict Mode safe — no useEffect cleanup needed.\n const store = useMemo(() => createRouteSource(router), [router]);\n // Use snapshot reference directly. createRouteSource via stabilizeState\n // returns the SAME snapshot reference when route.path is unchanged, so\n // useMemo below sees stable deps for idempotent navigations and\n // RouteContext consumers do not re-render.\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot, // SSR: router returns same state on server and client\n );\n\n const routeContextValue = useMemo(\n () => ({\n navigator,\n route: snapshot.route,\n previousRoute: snapshot.previousRoute,\n }),\n [navigator, snapshot],\n );\n\n return (\n <RouterContext.Provider value={router}>\n <NavigatorContext.Provider value={navigator}>\n <RouteContext.Provider value={routeContextValue}>\n {children}\n </RouteContext.Provider>\n </NavigatorContext.Provider>\n </RouterContext.Provider>\n );\n};\n"],"mappings":"0OAMA,MAAa,MAA0B,CACrC,IAAM,GAAA,EAAA,EAAA,YAAoBA,EAAAA,CAAa,EAEvC,GAAI,CAAC,EACH,MAAU,MAAM,gDAAgD,EAGlE,OAAO,CACT,ECNA,SAAgB,EAAa,EAAgC,CAC3D,IAAM,EAAS,EAAU,EAEnB,GAAA,EAAA,EAAA,cAAA,EAAA,EAAA,uBACwB,EAAQ,CAAQ,EAC5C,CAAC,EAAQ,CAAQ,CACnB,EAKM,GAAA,EAAA,EAAA,sBACJ,EAAM,UACN,EAAM,YACN,EAAM,WACR,EAGM,GAAA,EAAA,EAAA,cAAyB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AA,cAAA,EAAA,EAAA,cAAuC,CAAM,EAAG,CAAC,CAAM,CAAC,EAKxD,GAAA,EAAA,EAAA,cAAA,EAAA,EAAA,mBAAwC,CAAM,EAAG,CAAC,CAAM,CAAC,EAKzD,GAAA,EAAA,EAAA,sBACJ,EAAM,UACN,EAAM,YACN,EAAM,WACR,EAEM,GAAA,EAAA,EAAA,cACG,CACL,YACA,MAAO,EAAS,MAChB,cAAe,EAAS,aAC1B,GACA,CAAC,EAAW,CAAQ,CACtB,EAEA,OACE,EAAA,EAAA,KAACC,EAAAA,EAAc,SAAf,CAAwB,MAAO,YAC7B,EAAA,EAAA,KAACC,EAAAA,EAAiB,SAAlB,CAA2B,MAAO,YAChC,EAAA,EAAA,KAACC,EAAAA,EAAa,SAAd,CAAuB,MAAO,EAC3B,UACoB,CAAA,CACE,CAAA,CACL,CAAA,CAE5B"}
@@ -0,0 +1,109 @@
1
+ import { r as LinkProps } from "./RouterErrorBoundary-3UhUelqY.js";
2
+ import { FC, ReactNode } from "react";
3
+ import { NavigationOptions, Params, Router, State } from "@real-router/core";
4
+
5
+ //#region src/components/Link.d.ts
6
+ declare const Link: FC<LinkProps>;
7
+ //#endregion
8
+ //#region ../../shared/dom-utils/scroll-restore.d.ts
9
+ type ScrollRestorationMode = "restore" | "top" | "native";
10
+ interface ScrollRestorationOptions {
11
+ mode?: ScrollRestorationMode | undefined;
12
+ anchorScrolling?: boolean | undefined;
13
+ scrollContainer?: (() => HTMLElement | null) | undefined;
14
+ /**
15
+ * Scroll behavior passed to `scrollTo({ behavior })` and
16
+ * `scrollIntoView({ behavior })`.
17
+ *
18
+ * - `"auto"` (default) — browser-defined, usually instant.
19
+ * - `"instant"` — explicit instant jump (no animation).
20
+ * - `"smooth"` — animated transition. Note: smooth restore on back/traverse
21
+ * can feel disorienting if the user expects to land at the saved position
22
+ * immediately. Recommended for `mode: "top"` or anchor scroll only.
23
+ *
24
+ * See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/ScrollToOptions/behavior).
25
+ */
26
+ behavior?: ScrollBehavior | undefined;
27
+ /**
28
+ * sessionStorage key used to persist saved scroll positions. Default:
29
+ * `"real-router:scroll"`. Override only when multiple independent
30
+ * `RouterProvider` instances share the same document and you need to
31
+ * isolate their scroll stores (e.g. micro-frontends, embedded widgets,
32
+ * or testing). For a single app with one provider the default is fine.
33
+ */
34
+ storageKey?: string | undefined;
35
+ }
36
+ //#endregion
37
+ //#region ../../shared/dom-utils/scroll-spy.d.ts
38
+ /**
39
+ * Router-coordinated scroll spy (#575).
40
+ *
41
+ * On `IntersectionObserver` notifications the utility picks the topmost
42
+ * visible anchor inside the configured scroll container and emits a forced
43
+ * same-route transition with `{ hash, replace: true, force: true, hashChange:
44
+ * true }` through `router.navigate(...)`. The URL plugin
45
+ * (`@real-router/browser-plugin` or `@real-router/navigation-plugin`) updates
46
+ * `state.context.url.hash` so sibling hash-aware `<Link hash>` re-highlights
47
+ * via the standard `createActiveRouteSource` pipeline.
48
+ *
49
+ * **Anti-flicker gates** (RFC §5.2):
50
+ * 1. `getTransitionSource(router).getSnapshot().isTransitioning` — skip emits
51
+ * while a transition is in-flight (re-entrant lock).
52
+ * 2. `coolingDown` — set on a user-driven hash transition (e.g. `<Link hash>`
53
+ * click + smooth `scrollIntoView`). Cleared on `scrollend` or after a
54
+ * 500ms safety timeout. Spy's own emits are excluded via the synchronous
55
+ * `selfEmitting` flag — required so the spy doesn't rate-limit itself.
56
+ *
57
+ * **Self-healing** (RFC §7.3): if the initial URL contains a hash without a
58
+ * matching `id` (e.g. `/page#nonexistent`), the first IO event emitted right
59
+ * after observe()-ing picks the topmost real anchor and corrects the URL.
60
+ *
61
+ * **Hash-only transition pipeline cost** (RFC §5.3): for same-route same-
62
+ * params hash-only navigations, `getTransitionPath` returns empty
63
+ * `toDeactivate` / `toActivate` arrays, so `runGuards` is a no-op. The only
64
+ * work is the URL plugin's `onTransitionSuccess` write and the
65
+ * `getTransitionSource` flip — cheap.
66
+ *
67
+ * **Architecture**: decomposed into 4 private subsystem closure factories
68
+ * (`createUrlPluginDetector`, `createCooldown`, `createDebouncer`,
69
+ * `createObserverPair`). The main `createScrollSpy` wires them together
70
+ * around the shared `silenced` / `destroyed` / `selfEmitting` flags and the
71
+ * `flush()` emit logic. Each subsystem owns its state + cleanup; `destroy()`
72
+ * delegates to each. See section banners below.
73
+ *
74
+ * @returns A `ScrollSpy` handle whose `destroy()` is idempotent.
75
+ */
76
+ interface ScrollSpyOptions {
77
+ /**
78
+ * CSS selector for anchor candidates. Empty string `""` or `undefined`
79
+ * disables the spy (returns a NOOP handle). Common values:
80
+ * `"[id]"`, `"[id]:is(h1,h2,h3)"`, `"section[id]"`.
81
+ */
82
+ selector: string;
83
+ /**
84
+ * `IntersectionObserver` `rootMargin`. Default
85
+ * `"-20% 0px -60% 0px"` — an anchor is considered "active" once it crosses
86
+ * into the top 20 % of the viewport (or scroll container).
87
+ */
88
+ rootMargin?: string | undefined;
89
+ /**
90
+ * Lazy getter for the scrollable container. Resolved on every event.
91
+ * `null` (or missing getter) falls back to the window viewport
92
+ * (`root: null` on the `IntersectionObserver`).
93
+ */
94
+ scrollContainer?: (() => HTMLElement | null) | undefined;
95
+ }
96
+ //#endregion
97
+ //#region src/RouterProvider.d.ts
98
+ interface RouteProviderProps {
99
+ router: Router;
100
+ children: ReactNode;
101
+ announceNavigation?: boolean;
102
+ scrollRestoration?: ScrollRestorationOptions;
103
+ scrollSpy?: ScrollSpyOptions;
104
+ viewTransitions?: boolean;
105
+ }
106
+ declare const RouterProvider: FC<RouteProviderProps>;
107
+ //#endregion
108
+ export { Link as n, RouterProvider as t };
109
+ //# sourceMappingURL=RouterProvider-lgNarto1.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RouterProvider-lgNarto1.d.ts","names":[],"sources":["../../src/components/Link.tsx","../../../../shared/dom-utils/scroll-restore.ts","../../../../shared/dom-utils/scroll-spy.ts","../../src/RouterProvider.tsx"],"mappings":";;;;;cAkHa,IAAA,EAAM,EAAE,CAAC,SAAA;;;KChGV,qBAAA;AAAA,UAEK,wBAAA;EACf,IAAA,GAAO,qBAAA;EACP,eAAA;EACA,eAAA,UAAyB,WAAA;ED2FyC;;;AAArC;;;;AChG/B;;;;AAAiC;EAkB/B,QAAA,GAAW,cAAA;EAhB4B;;;;;;;EAwBvC,UAAA;AAAA;;;;;;;ADsEF;;;;AAA+B;;;;AChG/B;;;;AAAiC;AAEjC;;;;;;;;;;;;;;;;;AAwBY;;;;UCFK,gBAAA;EAAgB;;;;;EAM/B,QAAA;EAcyB;;AAAW;;;EAPpC,UAAA;ECvCe;;;;;ED8Cf,eAAA,UAAyB,WAAW;AAAA;;;UC9CrB,kBAAA;EACf,MAAA,EAAQ,MAAA;EACR,QAAA,EAAU,SAAA;EACV,kBAAA;EACA,iBAAA,GAAoB,wBAAA;EACpB,SAAA,GAAY,gBAAA;EACZ,eAAA;AAAA;AAAA,cAGW,cAAA,EAAgB,EAAE,CAAC,kBAAA"}
@@ -1,2 +1,2 @@
1
- const e=require(`./useRoute-Dudo2K_0.js`);let t=require(`react`),n=require(`react/jsx-runtime`);function r({children:e,fallback:n=null}){let[r,i]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{i(!0)},[]),r?e:n}function i({children:e,fallback:n=null}){let[r,i]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{i(!0)},[]),r?n:e}function a(t){let{route:n}=e.t();return n.context.ssrDataDeferred?.[t]??e.i}function o({fallback:e,children:r}){return(0,n.jsx)(t.Suspense,{fallback:e,children:r})}const s=(0,t.createContext)(null);function c({sink:e,children:t}){return(0,n.jsx)(s.Provider,{value:e,children:t})}function l({code:e}){let n=(0,t.useContext)(s);return n&&(n.code=e),null}function u(){return{code:void 0}}Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return u}});
2
- //# sourceMappingURL=createHttpStatusSink-D_6IiR5E.js.map
1
+ const e=require("./useRoute-D2vAzKWM.js");let t=require("react"),n=require("react/jsx-runtime");function r({children:e,fallback:n=null}){let[r,i]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{i(!0)},[]),r?e:n}function i({children:e,fallback:n=null}){let[r,i]=(0,t.useState)(!1);return(0,t.useEffect)(()=>{i(!0)},[]),r?n:e}function a(t){let{route:n}=e.t();return n.context.ssrDataDeferred?.[t]??e.i}function o({fallback:e,children:r}){return(0,n.jsx)(t.Suspense,{fallback:e,children:r})}const s=(0,t.createContext)(null);function c({sink:e,children:t}){return(0,n.jsx)(s.Provider,{value:e,children:t})}function l({code:e}){let n=(0,t.useContext)(s);return n&&(n.code=e),null}function u(){return{code:void 0}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return u}});
2
+ //# sourceMappingURL=createHttpStatusSink-ChfBL87y.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"createHttpStatusSink-D_6IiR5E.js","names":["useRoute","NEVER_PROMISE","Suspense"],"sources":["../../src/components/ClientOnly.tsx","../../src/components/ServerOnly.tsx","../../src/hooks/useDeferred.tsx","../../src/components/Streamed.tsx","../../src/components/HttpStatusProvider.tsx","../../src/components/HttpStatusCode.tsx","../../src/utils/createHttpStatusSink.ts"],"sourcesContent":["import { useEffect, useState } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface ClientOnlyProps {\n readonly children: ReactNode;\n readonly fallback?: ReactNode;\n}\n\nexport function ClientOnly({\n children,\n fallback = null,\n}: ClientOnlyProps): ReactNode {\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n // SSR/hydration boundary: server emits the fallback branch, client matches\n // it on first paint, then this effect flips state to swap in the children.\n // The intentional re-render is what makes the markup match across renders.\n // eslint-disable-next-line @eslint-react/set-state-in-effect -- intentional post-hydration swap\n setMounted(true);\n }, []);\n\n return mounted ? children : fallback;\n}\n","import { useEffect, useState } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface ServerOnlyProps {\n readonly children: ReactNode;\n readonly fallback?: ReactNode;\n}\n\nexport function ServerOnly({\n children,\n fallback = null,\n}: ServerOnlyProps): ReactNode {\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n // SSR/hydration boundary: server emits the children branch, client matches\n // it on first paint, then this effect flips state to swap in the fallback\n // (or hide entirely). The intentional re-render keeps markup consistent\n // across renders.\n // eslint-disable-next-line @eslint-react/set-state-in-effect -- intentional post-hydration swap\n setMounted(true);\n }, []);\n\n return mounted ? fallback : children;\n}\n","import { NEVER_PROMISE } from \"../constants\";\nimport { useRoute } from \"./useRoute\";\n\ninterface DeferredContext {\n ssrDataDeferred?: Record<string, Promise<unknown>>;\n}\n\n/**\n * Read a deferred promise published by `defer({ deferred: { <key>: Promise } })`\n * inside an SSR data loader.\n *\n * - **Server render**: returns the actual loader-returned promise. Combine\n * with `<Suspense>` + `use(promise)` for native streaming via React 19's\n * `renderToReadableStream`.\n * - **Post-hydration**: returns a registry-backed promise; the inline\n * `<script>__rrDefer__(\"key\", json)</script>` tags emitted by the server\n * stream resolve it. `use()` returns synchronously once the registry\n * settles.\n * - **Unknown key**: returns a never-resolving promise — Suspense boundary\n * stays in fallback. This surfaces consumer/loader key drift as a visible\n * loading state instead of a silent runtime error.\n *\n * The hook subscribes to `RouteContext`, so it re-runs on every navigation.\n * Promise reference identity is stable across renders within the same\n * navigation — `use()` will not re-suspend on rerenders.\n */\nexport function useDeferred<T = unknown>(key: string): Promise<T> {\n const { route } = useRoute();\n const context = route.context as DeferredContext;\n const deferred = context.ssrDataDeferred;\n const promise = deferred?.[key];\n\n return (promise ?? NEVER_PROMISE) as Promise<T>;\n}\n","import { Suspense } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface StreamedProps {\n /** Shown while any descendant `use(promise)` / `<Await>` is pending. */\n readonly fallback: ReactNode;\n readonly children: ReactNode;\n}\n\n/**\n * Cross-adapter alias for `<Suspense fallback={…}>`. Pairs with `<Await>`\n * for symmetry with `<Streamed>` boundaries in the SvelteKit / Solid\n * deferred-data conventions.\n *\n * ```tsx\n * <Streamed fallback={<Spinner />}>\n * <Await<Review[]> name=\"reviews\">\n * {(reviews) => <ReviewList items={reviews} />}\n * </Await>\n * </Streamed>\n * ```\n *\n * The component is a thin wrapper around React's native `<Suspense>` — no\n * additional behaviour. Use plain `<Suspense>` directly if you don't need\n * the cross-framework naming alignment.\n */\nexport function Streamed({ fallback, children }: StreamedProps): ReactNode {\n return <Suspense fallback={fallback}>{children}</Suspense>;\n}\n","import { createContext } from \"react\";\n\nimport type { HttpStatusSink } from \"../utils/createHttpStatusSink\";\nimport type { ReactNode } from \"react\";\n\nexport const HttpStatusContext = createContext<HttpStatusSink | null>(null);\n\nexport interface HttpStatusProviderProps {\n readonly sink: HttpStatusSink;\n readonly children: ReactNode;\n}\n\nexport function HttpStatusProvider({\n sink,\n children,\n}: HttpStatusProviderProps): ReactNode {\n // `<HttpStatusContext.Provider value>` (not the React 19 `<HttpStatusContext value>`\n // shorthand) — same component file is exported via `/legacy/ssr` for React 18\n // consumers, where the shorthand throws \"Element type is invalid: expected\n // a string but got: object\".\n return (\n <HttpStatusContext.Provider value={sink}>\n {children}\n </HttpStatusContext.Provider>\n );\n}\n","import { useContext } from \"react\";\n\nimport { HttpStatusContext } from \"./HttpStatusProvider\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface HttpStatusCodeProps {\n /** HTTP status to apply to the response. Common values: 404, 410, 451, 503. */\n readonly code: number;\n}\n\n/**\n * Render-time HTTP status declaration. Mount inside a route component (typical\n * use case: a glob `*` route's NotFound page) when the status is decided by\n * the rendered tree rather than a loader.\n *\n * Writes `code` to the nearest `<HttpStatusProvider>`'s sink during render and\n * returns `null`. With no provider mounted (the standard client-side case)\n * the component is a silent no-op — same component tree hydrates without\n * touching the DOM or warning about mismatches.\n *\n * Loader-driven errors (`LoaderNotFound` → 404, `LoaderRedirect` → 30x) keep\n * working as before; this component covers render-time decisions only.\n *\n * Last write wins when several `<HttpStatusCode />` instances mount in the\n * same render pass — sink reflects the last component that ran.\n *\n * ```tsx\n * // entry-server.tsx\n * import { renderToString } from \"react-dom/server\";\n * import { createHttpStatusSink, HttpStatusProvider } from \"@real-router/react/ssr\";\n *\n * const sink = createHttpStatusSink();\n * const html = renderToString(\n * <HttpStatusProvider sink={sink}>\n * <RouterProvider router={router}>\n * <App />\n * </RouterProvider>\n * </HttpStatusProvider>,\n * );\n * response.status(sink.code ?? 200).send(html);\n * ```\n *\n * **Streaming SSR (`renderToReadableStream`):** the response status MUST be\n * sent before the first body byte flushes. If `<HttpStatusCode />` is mounted\n * inside a late-resolving `<Suspense>` boundary, the sink write may happen\n * AFTER the headers are already on the wire — the override is then lost.\n * Either mount the component in the shell (above every `<Suspense>` that\n * could delay it) or `await stream.allReady` before reading `sink.code`\n * (which forfeits streaming benefits). For non-streaming SSR\n * (`renderToString`) there is no such ordering concern.\n *\n * **Valid `code` range:** Node's `res.end()` throws `Invalid status code` on\n * `NaN`, `0`, negative values, or values `> 999` — this surfaces as a 5xx /\n * dropped connection, not silent corruption. Pass a real HTTP status integer\n * (commonly 4xx/5xx; 100-999 is what Node accepts).\n */\nexport function HttpStatusCode({ code }: HttpStatusCodeProps): ReactNode {\n const sink = useContext(HttpStatusContext);\n\n if (sink) {\n sink.code = code;\n }\n\n return null;\n}\n","/**\n * Render-scoped HTTP status sink. Created per request on the server, passed to\n * `<HttpStatusProvider sink={...}>`, and read after `renderToString` /\n * `renderToReadableStream` to apply the value to the HTTP response.\n *\n * Last write wins: if the rendered tree mounts more than one\n * `<HttpStatusCode />`, the value reflects the last component that ran during\n * the render pass.\n *\n * No-op on the client — `<HttpStatusCode />` reads the optional context and\n * skips the write when no provider is mounted, so the same component tree can\n * be hydrated without changing behaviour.\n *\n * Constraints:\n * - **Per-request only.** Don't share a sink across requests; the rendered\n * tree mutates `code` in place. Module-level singletons leak status\n * between concurrent requests.\n * - **Don't `Object.freeze` the sink.** The component writes to `.code`;\n * freezing makes the assignment throw under ESM strict mode.\n */\nexport interface HttpStatusSink {\n code: number | undefined;\n}\n\nexport function createHttpStatusSink(): HttpStatusSink {\n return { code: undefined };\n}\n"],"mappings":"gGASA,SAAgB,EAAW,CACzB,WACA,WAAW,MACkB,CAC7B,GAAM,CAAC,EAAS,IAAA,EAAA,EAAA,UAAuB,EAAK,EAU5C,OARA,EAAA,EAAA,eAAgB,CAKd,EAAW,EAAI,CACjB,EAAG,CAAC,CAAC,EAEE,EAAU,EAAW,CAC9B,CCfA,SAAgB,EAAW,CACzB,WACA,WAAW,MACkB,CAC7B,GAAM,CAAC,EAAS,IAAA,EAAA,EAAA,UAAuB,EAAK,EAW5C,OATA,EAAA,EAAA,eAAgB,CAMd,EAAW,EAAI,CACjB,EAAG,CAAC,CAAC,EAEE,EAAU,EAAW,CAC9B,CCCA,SAAgB,EAAyB,EAAyB,CAChE,GAAM,CAAE,SAAUA,EAAAA,EAAS,EAK3B,OAJgB,EAAM,QACG,kBACE,IAERC,EAAAA,CACrB,CCNA,SAAgB,EAAS,CAAE,WAAU,YAAsC,CACzE,OAAO,EAAA,EAAA,KAACC,EAAAA,SAAD,CAAoB,WAAW,UAAmB,CAAA,CAC3D,CCxBA,MAAa,GAAA,EAAA,EAAA,eAAyD,IAAI,EAO1E,SAAgB,EAAmB,CACjC,OACA,YACqC,CAKrC,OACE,EAAA,EAAA,KAAC,EAAkB,SAAnB,CAA4B,MAAO,EAChC,UACyB,CAAA,CAEhC,CCgCA,SAAgB,EAAe,CAAE,QAAwC,CACvE,IAAM,GAAA,EAAA,EAAA,YAAkB,CAAiB,EAMzC,OAJI,IACF,EAAK,KAAO,GAGP,IACT,CCzCA,SAAgB,GAAuC,CACrD,MAAO,CAAE,KAAM,IAAA,EAAU,CAC3B"}
1
+ {"version":3,"file":"createHttpStatusSink-ChfBL87y.js","names":["useRoute","NEVER_PROMISE","Suspense"],"sources":["../../src/components/ClientOnly.tsx","../../src/components/ServerOnly.tsx","../../src/hooks/useDeferred.tsx","../../src/components/Streamed.tsx","../../src/components/HttpStatusProvider.tsx","../../src/components/HttpStatusCode.tsx","../../src/utils/createHttpStatusSink.ts"],"sourcesContent":["import { useEffect, useState } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface ClientOnlyProps {\n readonly children: ReactNode;\n readonly fallback?: ReactNode;\n}\n\nexport function ClientOnly({\n children,\n fallback = null,\n}: ClientOnlyProps): ReactNode {\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n // SSR/hydration boundary: server emits the fallback branch, client matches\n // it on first paint, then this effect flips state to swap in the children.\n // The intentional re-render is what makes the markup match across renders.\n // eslint-disable-next-line @eslint-react/set-state-in-effect -- intentional post-hydration swap\n setMounted(true);\n }, []);\n\n return mounted ? children : fallback;\n}\n","import { useEffect, useState } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface ServerOnlyProps {\n readonly children: ReactNode;\n readonly fallback?: ReactNode;\n}\n\nexport function ServerOnly({\n children,\n fallback = null,\n}: ServerOnlyProps): ReactNode {\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n // SSR/hydration boundary: server emits the children branch, client matches\n // it on first paint, then this effect flips state to swap in the fallback\n // (or hide entirely). The intentional re-render keeps markup consistent\n // across renders.\n // eslint-disable-next-line @eslint-react/set-state-in-effect -- intentional post-hydration swap\n setMounted(true);\n }, []);\n\n return mounted ? fallback : children;\n}\n","import { NEVER_PROMISE } from \"../constants\";\nimport { useRoute } from \"./useRoute\";\n\ninterface DeferredContext {\n ssrDataDeferred?: Record<string, Promise<unknown>>;\n}\n\n/**\n * Read a deferred promise published by `defer({ deferred: { <key>: Promise } })`\n * inside an SSR data loader.\n *\n * - **Server render**: returns the actual loader-returned promise. Combine\n * with `<Suspense>` + `use(promise)` for native streaming via React 19's\n * `renderToReadableStream`.\n * - **Post-hydration**: returns a registry-backed promise; the inline\n * `<script>__rrDefer__(\"key\", json)</script>` tags emitted by the server\n * stream resolve it. `use()` returns synchronously once the registry\n * settles.\n * - **Unknown key**: returns a never-resolving promise — Suspense boundary\n * stays in fallback. This surfaces consumer/loader key drift as a visible\n * loading state instead of a silent runtime error.\n *\n * The hook subscribes to `RouteContext`, so it re-runs on every navigation.\n * Promise reference identity is stable across renders within the same\n * navigation — `use()` will not re-suspend on rerenders.\n */\nexport function useDeferred<T = unknown>(key: string): Promise<T> {\n const { route } = useRoute();\n const context = route.context as DeferredContext;\n const deferred = context.ssrDataDeferred;\n const promise = deferred?.[key];\n\n return (promise ?? NEVER_PROMISE) as Promise<T>;\n}\n","import { Suspense } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface StreamedProps {\n /** Shown while any descendant `use(promise)` / `<Await>` is pending. */\n readonly fallback: ReactNode;\n readonly children: ReactNode;\n}\n\n/**\n * Cross-adapter alias for `<Suspense fallback={…}>`. Pairs with `<Await>`\n * for symmetry with `<Streamed>` boundaries in the SvelteKit / Solid\n * deferred-data conventions.\n *\n * ```tsx\n * <Streamed fallback={<Spinner />}>\n * <Await<Review[]> name=\"reviews\">\n * {(reviews) => <ReviewList items={reviews} />}\n * </Await>\n * </Streamed>\n * ```\n *\n * The component is a thin wrapper around React's native `<Suspense>` — no\n * additional behaviour. Use plain `<Suspense>` directly if you don't need\n * the cross-framework naming alignment.\n */\nexport function Streamed({ fallback, children }: StreamedProps): ReactNode {\n return <Suspense fallback={fallback}>{children}</Suspense>;\n}\n","import { createContext } from \"react\";\n\nimport type { HttpStatusSink } from \"../utils/createHttpStatusSink\";\nimport type { ReactNode } from \"react\";\n\nexport const HttpStatusContext = createContext<HttpStatusSink | null>(null);\n\nexport interface HttpStatusProviderProps {\n readonly sink: HttpStatusSink;\n readonly children: ReactNode;\n}\n\nexport function HttpStatusProvider({\n sink,\n children,\n}: HttpStatusProviderProps): ReactNode {\n // `<HttpStatusContext.Provider value>` (not the React 19 `<HttpStatusContext value>`\n // shorthand) — same component file is exported via `/legacy/ssr` for React 18\n // consumers, where the shorthand throws \"Element type is invalid: expected\n // a string but got: object\".\n return (\n <HttpStatusContext.Provider value={sink}>\n {children}\n </HttpStatusContext.Provider>\n );\n}\n","import { useContext } from \"react\";\n\nimport { HttpStatusContext } from \"./HttpStatusProvider\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface HttpStatusCodeProps {\n /** HTTP status to apply to the response. Common values: 404, 410, 451, 503. */\n readonly code: number;\n}\n\n/**\n * Render-time HTTP status declaration. Mount inside a route component (typical\n * use case: a glob `*` route's NotFound page) when the status is decided by\n * the rendered tree rather than a loader.\n *\n * Writes `code` to the nearest `<HttpStatusProvider>`'s sink during render and\n * returns `null`. With no provider mounted (the standard client-side case)\n * the component is a silent no-op — same component tree hydrates without\n * touching the DOM or warning about mismatches.\n *\n * Loader-driven errors (`LoaderNotFound` → 404, `LoaderRedirect` → 30x) keep\n * working as before; this component covers render-time decisions only.\n *\n * Last write wins when several `<HttpStatusCode />` instances mount in the\n * same render pass — sink reflects the last component that ran.\n *\n * ```tsx\n * // entry-server.tsx\n * import { renderToString } from \"react-dom/server\";\n * import { createHttpStatusSink, HttpStatusProvider } from \"@real-router/react/ssr\";\n *\n * const sink = createHttpStatusSink();\n * const html = renderToString(\n * <HttpStatusProvider sink={sink}>\n * <RouterProvider router={router}>\n * <App />\n * </RouterProvider>\n * </HttpStatusProvider>,\n * );\n * response.status(sink.code ?? 200).send(html);\n * ```\n *\n * **Streaming SSR (`renderToReadableStream`):** the response status MUST be\n * sent before the first body byte flushes. If `<HttpStatusCode />` is mounted\n * inside a late-resolving `<Suspense>` boundary, the sink write may happen\n * AFTER the headers are already on the wire — the override is then lost.\n * Either mount the component in the shell (above every `<Suspense>` that\n * could delay it) or `await stream.allReady` before reading `sink.code`\n * (which forfeits streaming benefits). For non-streaming SSR\n * (`renderToString`) there is no such ordering concern.\n *\n * **Valid `code` range:** Node's `res.end()` throws `Invalid status code` on\n * `NaN`, `0`, negative values, or values `> 999` — this surfaces as a 5xx /\n * dropped connection, not silent corruption. Pass a real HTTP status integer\n * (commonly 4xx/5xx; 100-999 is what Node accepts).\n */\nexport function HttpStatusCode({ code }: HttpStatusCodeProps): ReactNode {\n const sink = useContext(HttpStatusContext);\n\n if (sink) {\n sink.code = code;\n }\n\n return null;\n}\n","/**\n * Render-scoped HTTP status sink. Created per request on the server, passed to\n * `<HttpStatusProvider sink={...}>`, and read after `renderToString` /\n * `renderToReadableStream` to apply the value to the HTTP response.\n *\n * Last write wins: if the rendered tree mounts more than one\n * `<HttpStatusCode />`, the value reflects the last component that ran during\n * the render pass.\n *\n * No-op on the client — `<HttpStatusCode />` reads the optional context and\n * skips the write when no provider is mounted, so the same component tree can\n * be hydrated without changing behaviour.\n *\n * Constraints:\n * - **Per-request only.** Don't share a sink across requests; the rendered\n * tree mutates `code` in place. Module-level singletons leak status\n * between concurrent requests.\n * - **Don't `Object.freeze` the sink.** The component writes to `.code`;\n * freezing makes the assignment throw under ESM strict mode.\n */\nexport interface HttpStatusSink {\n code: number | undefined;\n}\n\nexport function createHttpStatusSink(): HttpStatusSink {\n return { code: undefined };\n}\n"],"mappings":"gGASA,SAAgB,EAAW,CACzB,WACA,WAAW,MACkB,CAC7B,GAAM,CAAC,EAAS,IAAA,EAAA,EAAA,UAAuB,EAAK,EAU5C,OARA,EAAA,EAAA,eAAgB,CAKd,EAAW,EAAI,CACjB,EAAG,CAAC,CAAC,EAEE,EAAU,EAAW,CAC9B,CCfA,SAAgB,EAAW,CACzB,WACA,WAAW,MACkB,CAC7B,GAAM,CAAC,EAAS,IAAA,EAAA,EAAA,UAAuB,EAAK,EAW5C,OATA,EAAA,EAAA,eAAgB,CAMd,EAAW,EAAI,CACjB,EAAG,CAAC,CAAC,EAEE,EAAU,EAAW,CAC9B,CCCA,SAAgB,EAAyB,EAAyB,CAChE,GAAM,CAAE,SAAUA,EAAAA,EAAS,EAK3B,OAJgB,EAAM,QACG,kBACE,IAERC,EAAAA,CACrB,CCNA,SAAgB,EAAS,CAAE,WAAU,YAAsC,CACzE,OAAO,EAAA,EAAA,KAACC,EAAAA,SAAD,CAAoB,WAAW,UAAmB,CAAA,CAC3D,CCxBA,MAAa,GAAA,EAAA,EAAA,eAAyD,IAAI,EAO1E,SAAgB,EAAmB,CACjC,OACA,YACqC,CAKrC,OACE,EAAA,EAAA,KAAC,EAAkB,SAAnB,CAA4B,MAAO,EAChC,UACyB,CAAA,CAEhC,CCgCA,SAAgB,EAAe,CAAE,QAAwC,CACvE,IAAM,GAAA,EAAA,EAAA,YAAkB,CAAiB,EAMzC,OAJI,IACF,EAAK,KAAO,GAGP,IACT,CCzCA,SAAgB,GAAuC,CACrD,MAAO,CAAE,KAAM,IAAA,EAAU,CAC3B"}