@real-router/react 0.31.46 → 0.31.48

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 (32) hide show
  1. package/dist/cjs/RouterProvider-CBhvbliH.js +2 -0
  2. package/dist/cjs/RouterProvider-CBhvbliH.js.map +1 -0
  3. package/dist/cjs/RouterProvider-iwUCDuSG.d.ts.map +1 -1
  4. package/dist/cjs/{RouterProviderCore-Dmp4Qf0f.js → RouterProviderCore-D92mrJ6j.js} +2 -2
  5. package/dist/cjs/RouterProviderCore-D92mrJ6j.js.map +1 -0
  6. package/dist/cjs/createHttpStatusSink-DT-Ec9Jq.js.map +1 -1
  7. package/dist/cjs/index.js +1 -1
  8. package/dist/cjs/index.js.map +1 -1
  9. package/dist/cjs/ink.d.ts +3 -3
  10. package/dist/cjs/ink.d.ts.map +1 -1
  11. package/dist/cjs/ink.js +1 -1
  12. package/dist/cjs/ink.js.map +1 -1
  13. package/dist/cjs/legacy.js +1 -1
  14. package/dist/cjs/ssr.js.map +1 -1
  15. package/dist/cjs/useRoute-D2vAzKWM.js.map +1 -1
  16. package/dist/esm/RouterProvider-CVcC8wop.d.mts.map +1 -1
  17. package/dist/esm/RouterProvider-DTse0TcY.mjs +2 -0
  18. package/dist/{cjs/RouterProvider-Cxn25HDw.js.map → esm/RouterProvider-DTse0TcY.mjs.map} +1 -1
  19. package/dist/esm/{RouterProviderCore-CKc1Kt2d.mjs → RouterProviderCore-D2YRnfAI.mjs} +2 -2
  20. package/dist/esm/RouterProviderCore-D2YRnfAI.mjs.map +1 -0
  21. package/dist/esm/index.mjs +1 -1
  22. package/dist/esm/index.mjs.map +1 -1
  23. package/dist/esm/ink.d.mts +3 -3
  24. package/dist/esm/ink.d.mts.map +1 -1
  25. package/dist/esm/ink.mjs +1 -1
  26. package/dist/esm/legacy.mjs +1 -1
  27. package/package.json +5 -5
  28. package/dist/cjs/RouterProvider-Cxn25HDw.js +0 -2
  29. package/dist/cjs/RouterProviderCore-Dmp4Qf0f.js.map +0 -1
  30. package/dist/esm/RouterProvider-CmEutabZ.mjs +0 -2
  31. package/dist/esm/RouterProvider-CmEutabZ.mjs.map +0 -1
  32. package/dist/esm/RouterProviderCore-CKc1Kt2d.mjs.map +0 -1
@@ -1,2 +1,2 @@
1
- import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,i as n,m as r,n as i,p as a,r as o}from"./RouterProviderCore-CKc1Kt2d.mjs";import{n as s,t as c}from"./RouterProvider-CmEutabZ.mjs";import{Activity as l,Children as u,Fragment as d,Suspense as f,isValidElement as p,useEffect as m,useLayoutEffect as h,useMemo as g,useRef as _,useState as v}from"react";import{UNKNOWN_ROUTE as y}from"@real-router/core";import{startsWithSegment as b}from"@real-router/route-utils";import{Fragment as x,jsx as S}from"react/jsx-runtime";import{createRouteEnterGate as C,guardLeaveListener as w}from"@real-router/sources";function T(e){return null}T.displayName=`RouteView.Match`;function E(e){return null}E.displayName=`RouteView.Self`;function D(e){return null}D.displayName=`RouteView.NotFound`;const O=new Set([T,E,D]);function k(e,t,n){return t===``?!1:n?e===t:b(e,t)}function A(e,t){u.forEach(e,e=>{p(e)&&(O.has(e.type)?t.push(e):A(e.props.children,t))})}function j(e,t,n,r,i){let a=i===void 0?e:S(f,{fallback:i,children:e});return n?S(l,{mode:r,children:a},t):S(d,{children:a},t)}function M(e,t){return e.type===D?(t.notFoundFound||=(t.notFoundChildren=e.props.children,!0),!0):e.type===E?(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0):!1}function N(e,t,n,r,i){let a=e.props,{segment:o,exact:s=!1,keepAlive:c=!1,fallback:l}=a,u=n?`${n}.${o}`:o;return!i&&k(t,u,s)?{rendered:j(a.children,u,c,`visible`,l),activatedName:u}:c&&r.has(u)?{rendered:j(a.children,u,c,`hidden`,l),activatedName:null}:{rendered:null,activatedName:null}}function P(e,t,n,r){if(r.selfFound&&t===n){e.push(j(r.selfChildren,`__route-view-self__`,!1,`visible`,r.selfFallback));return}t===y&&r.notFoundChildren!==null&&e.push(S(d,{children:r.notFoundChildren},`__route-view-not-found__`))}function F(e,t,n,r){let i={selfChildren:null,selfFallback:void 0,selfFound:!1,notFoundChildren:null,notFoundFound:!1},a=null,o=[];for(let s of e){if(M(s,i))continue;let e=N(s,t,n,r,a!==null);e.activatedName!==null&&(a=e.activatedName),e.rendered!==null&&o.push(e.rendered)}return a===null&&P(o,t,n,i),{rendered:o,activeMatchFound:a!==null,activatedName:a}}function I({nodeName:e,children:t}){let{route:n}=a(e),r=_(null);r.current??=new Set;let i=r.current,o=g(()=>{let e=[];return A(t,e),e},[t]),s=n?.name??null,{rendered:c,activatedName:l}=g(()=>{if(s===null)return{rendered:[],activatedName:null};let t=F(o,s,e,i);return{rendered:t.rendered,activatedName:t.activatedName}},[o,s,e,i]);return m(()=>{l!==null&&i.add(l)},[l,i]),c.length>0?S(x,{children:c}):null}I.displayName=`RouteView`;const L=Object.assign(I,{Match:T,Self:E,NotFound:D});function R(e,t){let n=r(),i=_(e),a=t?.skipSameRoute??!0;h(()=>{i.current=e}),m(()=>n.subscribeLeave(w(e=>i.current(e),{skipSameRoute:a})),[n,a])}function z(t,n){let{route:r,previousRoute:i}=e(),a=_(t),[o]=v(()=>C()),s=n?.skipSameRoute??!0;h(()=>{a.current=t}),m(()=>{let e=o(r,i,s);e&&a.current(e)},[o,r,i,s])}export{s as Link,L as RouteView,t as RouterErrorBoundary,c as RouterProvider,n as useNavigator,e as useRoute,z as useRouteEnter,R as useRouteExit,a as useRouteNode,o as useRouteUtils,r as useRouter,i as useRouterTransition};
1
+ import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,i as n,m as r,n as i,p as a,r as o}from"./RouterProviderCore-D2YRnfAI.mjs";import{n as s,t as c}from"./RouterProvider-DTse0TcY.mjs";import{Activity as l,Children as u,Fragment as d,Suspense as f,isValidElement as p,useEffect as m,useLayoutEffect as h,useMemo as g,useRef as _,useState as v}from"react";import{UNKNOWN_ROUTE as y}from"@real-router/core";import{startsWithSegment as b}from"@real-router/route-utils";import{Fragment as x,jsx as S}from"react/jsx-runtime";import{createRouteEnterGate as C,guardLeaveListener as w}from"@real-router/sources";function T(e){return null}T.displayName=`RouteView.Match`;function E(e){return null}E.displayName=`RouteView.Self`;function D(e){return null}D.displayName=`RouteView.NotFound`;const O=new Set([T,E,D]);function k(e,t,n){return t===``?!1:n?e===t:b(e,t)}function A(e,t){u.forEach(e,e=>{p(e)&&(O.has(e.type)?t.push(e):A(e.props.children,t))})}function j(e,t,n,r,i){let a=i===void 0?e:S(f,{fallback:i,children:e});return n?S(l,{mode:r,children:a},t):S(d,{children:a},t)}function M(e,t){return e.type===D?(t.notFoundFound||=(t.notFoundChildren=e.props.children,!0),!0):e.type===E&&(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0)}function N(e,t,n,r,i){let a=e.props,{segment:o,exact:s=!1,keepAlive:c=!1,fallback:l}=a,u=n?`${n}.${o}`:o;return!i&&k(t,u,s)?{rendered:j(a.children,u,c,`visible`,l),activatedName:u}:c&&r.has(u)?{rendered:j(a.children,u,c,`hidden`,l),activatedName:null}:{rendered:null,activatedName:null}}function P(e,t,n,r){if(r.selfFound&&t===n){e.push(j(r.selfChildren,`__route-view-self__`,!1,`visible`,r.selfFallback));return}t===y&&r.notFoundChildren!==null&&e.push(S(d,{children:r.notFoundChildren},`__route-view-not-found__`))}function F(e,t,n,r){let i={selfChildren:null,selfFallback:void 0,selfFound:!1,notFoundChildren:null,notFoundFound:!1},a=null,o=[];for(let s of e){if(M(s,i))continue;let e=N(s,t,n,r,a!==null);e.activatedName!==null&&(a=e.activatedName),e.rendered!==null&&o.push(e.rendered)}return a===null&&P(o,t,n,i),{rendered:o,activeMatchFound:a!==null,activatedName:a}}function I({nodeName:e,children:t}){let{route:n}=a(e),r=_(null);r.current??=new Set;let i=r.current,o=g(()=>{let e=[];return A(t,e),e},[t]),s=n?.name??null,{rendered:c,activatedName:l}=g(()=>{if(s===null)return{rendered:[],activatedName:null};let t=F(o,s,e,i);return{rendered:t.rendered,activatedName:t.activatedName}},[o,s,e,i]);return m(()=>{l!==null&&i.add(l)},[l,i]),c.length>0?S(x,{children:c}):null}I.displayName=`RouteView`;const L=Object.assign(I,{Match:T,Self:E,NotFound:D});function R(e,t){let n=r(),i=_(e),a=t?.skipSameRoute??!0;h(()=>{i.current=e}),m(()=>n.subscribeLeave(w(e=>i.current(e),{skipSameRoute:a})),[n,a])}function z(t,n){let{route:r,previousRoute:i}=e(),a=_(t),[o]=v(()=>C()),s=n?.skipSameRoute??!0;h(()=>{a.current=t}),m(()=>{let e=o(r,i,s);e&&a.current(e)},[o,r,i,s])}export{s as Link,L as RouteView,t as RouterErrorBoundary,c as RouterProvider,n as useNavigator,e as useRoute,z as useRouteEnter,R as useRouteExit,a as useRouteNode,o as useRouteUtils,r as useRouter,i as useRouterTransition};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/components/modern/RouteView/components.tsx","../../src/components/modern/RouteView/helpers.tsx","../../src/components/modern/RouteView/RouteView.tsx","../../src/hooks/useRouteExit.tsx","../../src/hooks/useRouteEnter.tsx"],"sourcesContent":["import type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\n\nexport function Match(_props: MatchProps): null {\n return null;\n}\n\nMatch.displayName = \"RouteView.Match\";\n\nexport function Self(_props: SelfProps): null {\n return null;\n}\n\nSelf.displayName = \"RouteView.Self\";\n\nexport function NotFound(_props: NotFoundProps): null {\n return null;\n}\n\nNotFound.displayName = \"RouteView.NotFound\";\n","import { UNKNOWN_ROUTE } from \"@real-router/core\";\nimport { startsWithSegment } from \"@real-router/route-utils\";\nimport { Activity, Children, Fragment, Suspense, isValidElement } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\n\nimport type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\nimport type { ReactElement, ReactNode } from \"react\";\n\nconst MARKER_TYPES: ReadonlySet<unknown> = new Set([Match, Self, NotFound]);\n\ninterface FallbackSlots {\n selfChildren: ReactNode;\n selfFallback: ReactNode | undefined;\n selfFound: boolean;\n notFoundChildren: ReactNode;\n notFoundFound: boolean;\n}\n\n// Fixed keys used by appendFallback to distinguish the Self / NotFound\n// render slots from user-supplied <Match> children. Match render slots key\n// off `fullSegmentName` instead — these two are the only synthetic keys.\nconst SELF_KEY = \"__route-view-self__\";\nconst NOT_FOUND_KEY = \"__route-view-not-found__\";\n\nfunction isSegmentMatch(\n routeName: string,\n fullSegmentName: string,\n exact: boolean,\n): boolean {\n if (fullSegmentName === \"\") {\n return false;\n }\n\n if (exact) {\n return routeName === fullSegmentName;\n }\n\n return startsWithSegment(routeName, fullSegmentName);\n}\n\nexport function collectElements(\n children: ReactNode,\n result: ReactElement[],\n): void {\n // Recurses into Fragment-like wrappers (anything that isn't Match / Self /\n // NotFound) to flatten the slot tree. No explicit depth guard: typical\n // RouteView shape is `<RouteView><Match/>...<NotFound/></RouteView>` —\n // depth ≤ 3 in real apps. A pathological hand-written tree of N Fragments\n // recurses N times; the call stack, not this function, is the bound.\n //\n // `Children.forEach` iterates without `Children.toArray`'s array allocation\n // and per-child clone-with-synthetic-key step. We don't read child.key here\n // (Match/Self/NotFound carry their own segment-derived keys further down),\n // so the cheaper iterator is functionally equivalent.\n // eslint-disable-next-line @eslint-react/no-children-for-each -- intentional: collectElements is a render-hot pipeline; toArray's array+key clone is wasteful here\n Children.forEach(children, (child) => {\n if (!isValidElement(child)) {\n return;\n }\n\n if (MARKER_TYPES.has(child.type)) {\n result.push(child);\n } else {\n collectElements(\n (child.props as { readonly children: ReactNode }).children,\n result,\n );\n }\n });\n}\n\nfunction renderSlotElement(\n slotChildren: ReactNode,\n key: string,\n keepAlive: boolean,\n mode: \"visible\" | \"hidden\",\n fallback?: ReactNode,\n): ReactElement {\n const content =\n fallback === undefined ? (\n slotChildren\n ) : (\n <Suspense fallback={fallback}>{slotChildren}</Suspense>\n );\n\n if (keepAlive) {\n return (\n <Activity mode={mode} key={key}>\n {content}\n </Activity>\n );\n }\n\n return <Fragment key={key}>{content}</Fragment>;\n}\n\nfunction recordFallback(child: ReactElement, slots: FallbackSlots): boolean {\n if (child.type === NotFound) {\n // First-wins: subsequent <NotFound> elements are ignored, symmetric with\n // <Self> below (#1220). Before this guard the assignment was unconditional\n // (last-wins), contradicting the documented Self-symmetric contract.\n if (!slots.notFoundFound) {\n slots.notFoundChildren = (child.props as NotFoundProps).children;\n slots.notFoundFound = true;\n }\n\n return true;\n }\n\n if (child.type === Self) {\n // First-wins: subsequent <Self> elements are ignored, mirroring NotFound.\n if (!slots.selfFound) {\n slots.selfChildren = (child.props as SelfProps).children;\n slots.selfFallback = (child.props as SelfProps).fallback;\n slots.selfFound = true;\n }\n\n return true;\n }\n\n return false;\n}\n\nfunction processMatch(\n child: ReactElement,\n routeName: string,\n nodeName: string,\n hasBeenActivated: ReadonlySet<string>,\n alreadyActive: boolean,\n): { rendered: ReactElement | null; activatedName: string | null } {\n const matchProps = child.props as MatchProps;\n const { segment, exact = false, keepAlive = false, fallback } = matchProps;\n const fullSegmentName = nodeName ? `${nodeName}.${segment}` : segment;\n const isActive =\n !alreadyActive && isSegmentMatch(routeName, fullSegmentName, exact);\n\n if (isActive) {\n // The keepAlive Set is NOT mutated here — RouteView commits the activation\n // in a post-render effect (#1251). Mutating during render coupled the pure\n // winner computation to a side effect (blocking memoization) and, under\n // concurrent rendering, a discarded render would leave a phantom entry that\n // later renders an un-committed match as a hidden keepAlive subtree.\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"visible\",\n fallback,\n ),\n activatedName: fullSegmentName,\n };\n }\n\n if (keepAlive && hasBeenActivated.has(fullSegmentName)) {\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"hidden\",\n fallback,\n ),\n activatedName: null,\n };\n }\n\n return { rendered: null, activatedName: null };\n}\n\nfunction appendFallback(\n rendered: ReactElement[],\n routeName: string,\n nodeName: string,\n slots: FallbackSlots,\n): void {\n if (slots.selfFound && routeName === nodeName) {\n rendered.push(\n renderSlotElement(\n slots.selfChildren,\n SELF_KEY,\n false,\n \"visible\",\n slots.selfFallback,\n ),\n );\n\n return;\n }\n\n if (routeName === UNKNOWN_ROUTE && slots.notFoundChildren !== null) {\n rendered.push(\n <Fragment key={NOT_FOUND_KEY}>{slots.notFoundChildren}</Fragment>,\n );\n }\n}\n\nexport function buildRenderList(\n elements: ReactElement[],\n routeName: string,\n nodeName: string,\n hasBeenActivated: ReadonlySet<string>,\n): {\n rendered: ReactElement[];\n activeMatchFound: boolean;\n activatedName: string | null;\n} {\n const slots: FallbackSlots = {\n selfChildren: null,\n selfFallback: undefined,\n selfFound: false,\n notFoundChildren: null,\n notFoundFound: false,\n };\n // The segment that activated this render, or null. Reported to the caller so\n // RouteView can commit it to the keepAlive Set post-render (#1251) — this pure\n // walk no longer mutates the Set. At most one match activates (first-wins via\n // the `alreadyActive` short-circuit), so a single name suffices.\n let activatedName: string | null = null;\n const rendered: ReactElement[] = [];\n\n for (const child of elements) {\n if (recordFallback(child, slots)) {\n continue;\n }\n\n const result = processMatch(\n child,\n routeName,\n nodeName,\n hasBeenActivated,\n activatedName !== null,\n );\n\n if (result.activatedName !== null) {\n activatedName = result.activatedName;\n }\n\n if (result.rendered !== null) {\n rendered.push(result.rendered);\n }\n }\n\n if (activatedName === null) {\n appendFallback(rendered, routeName, nodeName, slots);\n }\n\n return { rendered, activeMatchFound: activatedName !== null, activatedName };\n}\n","import { useEffect, useMemo, useRef } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\nimport { buildRenderList, collectElements } from \"./helpers\";\nimport { useRouteNode } from \"../../../hooks/useRouteNode\";\n\nimport type { RouteViewProps } from \"./types\";\nimport type { ReactElement } from \"react\";\n\nfunction RouteViewRoot({\n nodeName,\n children,\n}: Readonly<RouteViewProps>): ReactElement | null {\n const { route } = useRouteNode(nodeName);\n const hasBeenActivatedRef = useRef<Set<string> | null>(null);\n\n // eslint-disable-next-line @eslint-react/refs -- lazy init: assign once when null to avoid `new Set()` allocation on every render\n hasBeenActivatedRef.current ??= new Set();\n // eslint-disable-next-line @eslint-react/refs -- stable render cache; the ref is never reassigned after lazy init\n const hasBeenActivated = hasBeenActivatedRef.current;\n\n // Skip the Children.forEach + collectElements traversal when the children\n // reference is unchanged. The common SPA case is a stable JSX tree across\n // re-renders, so the cache hits on every render except the first.\n //\n // Streaming SSR caveat: with `renderToReadableStream`, React may invoke\n // RouteView multiple times across chunks with a fresh `children` reference\n // each time. The useMemo misses on each new render and the traversal runs\n // again — this is the expected SSR cost; the alternative would be build-\n // time codegen of the static route tree, which is out of scope here.\n const elements = useMemo(() => {\n const collected: ReactElement[] = [];\n\n collectElements(children, collected);\n\n return collected;\n }, [children]);\n\n const routeName = route?.name ?? null;\n\n // Memoize the render walk by its pure inputs. Previously `buildRenderList` ran\n // on EVERY render because `processMatch` mutated the keepAlive Set inline —\n // coupling the pure winner/`rendered` computation to a side effect, so a\n // parent re-render with no route change re-walked every Match and re-diffed\n // the identical output (preact, whose `buildRenderList` is a 3-arg pure\n // function, already memoizes here). The Set mutation now lives in the effect\n // below, so the walk memoizes on `[elements, routeName, nodeName]` too. #1251.\n const { rendered, activatedName } = useMemo(() => {\n if (routeName === null) {\n return { rendered: [] as ReactElement[], activatedName: null };\n }\n\n const result = buildRenderList(\n elements,\n routeName,\n nodeName,\n hasBeenActivated,\n );\n\n return { rendered: result.rendered, activatedName: result.activatedName };\n }, [elements, routeName, nodeName, hasBeenActivated]);\n\n // Commit the keepAlive activation AFTER render, not during it. A render that\n // React discards under concurrent rendering must not record an activation\n // that never committed — otherwise a later render would show that\n // never-mounted match as a hidden keepAlive subtree. Adding the same name\n // twice is a no-op, so the effect is safe to re-run.\n // `hasBeenActivated` is a ref-held Set (L15-20), mutated post-commit in this\n // effect — the concurrent-safe pattern #1251 established. @eslint-react's\n // experimental `immutability` rule (detection widened in v5.17) flags the ref\n // mutation and suggests state, which would defeat the ref's whole purpose\n // (re-render-free activation tracking). Intentional exception, scoped here.\n /* eslint-disable @eslint-react/immutability -- intentional post-commit ref-Set mutation, see #1251 */\n useEffect(() => {\n if (activatedName !== null) {\n hasBeenActivated.add(activatedName);\n }\n }, [activatedName, hasBeenActivated]);\n /* eslint-enable @eslint-react/immutability */\n\n if (rendered.length > 0) {\n return <>{rendered}</>;\n }\n\n return null;\n}\n\nRouteViewRoot.displayName = \"RouteView\";\n\nexport const RouteView = Object.assign(RouteViewRoot, {\n Match,\n Self,\n NotFound,\n});\n\nexport type {\n RouteViewProps,\n MatchProps as RouteViewMatchProps,\n SelfProps as RouteViewSelfProps,\n NotFoundProps as RouteViewNotFoundProps,\n} from \"./types\";\n","import { guardLeaveListener } from \"@real-router/sources\";\nimport { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteExitContext {\n /** The route being left. */\n route: State;\n /** The route being navigated to. */\n nextRoute: State;\n /**\n * AbortSignal that fires when this navigation is superseded by a later\n * one (rapid clicks). Already filtered: when the handler runs,\n * `signal.aborted` is guaranteed to be `false`. Use\n * `signal.addEventListener(\"abort\", cleanup, { once: true })` for\n * cleanup that must run on cancellation.\n */\n signal: AbortSignal;\n}\n\nexport interface UseRouteExitOptions {\n /**\n * Skip the handler when `route.name === nextRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`.\n */\n skipSameRoute?: boolean;\n}\n\nexport type RouteExitHandler = (\n context: RouteExitContext,\n) => void | Promise<void>;\n\n/**\n * Subscribe to the router's leave-window with the universal guards baked\n * in. Wraps `router.subscribeLeave` so consumers don't repeat the same\n * boilerplate every time:\n *\n * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`\n * when the handler would run (rapid navigation superseded a slower\n * one), the handler is skipped entirely. `signal.addEventListener(\n * \"abort\", ...)` does not fire retroactively, so without this guard\n * downstream cleanup would never trigger.\n * - **Same-route skip**: by default, `route.name === nextRoute.name`\n * short-circuits the handler — query-only navigations (sort, filter,\n * pagination) skip the work. Opt out with `skipSameRoute: false`.\n * - **Stable handler reference**: the handler can change identity on\n * every render without causing resubscription — internal ref keeps\n * the latest handler accessible to the long-lived subscription.\n *\n * Returns nothing — the subscription's lifecycle is bound to the\n * component's mount.\n *\n * If the handler returns a Promise, the router blocks on it. If the\n * Promise resolves, navigation proceeds. If it **rejects**, the router\n * rejects `navigate()` with the handler's **original error** and emits\n * `TRANSITION_ERROR` — it is NOT re-coded to `TRANSITION_CANCELLED`\n * (that arises only when the navigation's `signal` aborts: a superseding\n * navigation, `stop()`, `dispose()`, or an external `opts.signal`).\n *\n * **Reentrancy — no synchronous `navigate()` from the handler.** The handler\n * runs inside the transition's leave-dispatch window, so calling\n * `router.navigate(...)` (or `navigateToDefault` / `navigateToState` /\n * `navigateToNotFound`) **synchronously** in the handler body throws\n * `REENTRANT_NAVIGATION` — core bans reentrant navigation from a transition\n * listener (RFC navigation-cancellation-unification §4). To redirect on exit,\n * defer past the sync dispatch: `await` your exit work first, or\n * `queueMicrotask(() => router.navigate(...))`. A navigate issued after the\n * handler's first `await` runs once the transition settles and is allowed.\n * (Guards — `canDeactivate` — are the intended place to *block* or gate a\n * departure; `useRouteExit` is for side effects, not redirection.)\n *\n * @example Animation\n * ```tsx\n * const ref = useRef<HTMLDivElement>(null);\n *\n * useRouteExit(async ({ signal }) => {\n * const el = ref.current;\n * if (!el) return;\n * el.classList.add(\"fade-out\");\n * const cleanup = () => el.classList.remove(\"fade-out\");\n * signal.addEventListener(\"abort\", cleanup, { once: true });\n * try {\n * el.getBoundingClientRect(); // style flush\n * await Promise.allSettled(el.getAnimations().map((a) => a.finished));\n * } finally {\n * cleanup();\n * }\n * });\n * ```\n *\n * @example Auto-save form draft\n * ```tsx\n * useRouteExit(async ({ signal }) => {\n * if (formState.dirty) await api.saveDraft(formState, { signal });\n * });\n * ```\n *\n * @example Cancel inflight requests\n * ```tsx\n * useRouteExit(() => {\n * inflightController.abort();\n * });\n * ```\n *\n * @example Library-coordinated exit (motion / framer-motion)\n * ```tsx\n * const exitResolverRef = useRef<(() => void) | null>(null);\n *\n * useRouteExit(({ signal }) => {\n * return new Promise<void>((resolve) => {\n * exitResolverRef.current = resolve;\n * signal.addEventListener(\"abort\", () => resolve(), { once: true });\n * });\n * });\n *\n * const onExitComplete = () => exitResolverRef.current?.();\n * // pass onExitComplete to <AnimatePresence>\n * ```\n *\n * @example Detecting that you are leaving a subtree\n * ```tsx\n * const inProducts = (name: string) =>\n * name === \"products\" || name.startsWith(\"products.\");\n *\n * useRouteExit(({ route, nextRoute }) => {\n * if (inProducts(route.name) && !inProducts(nextRoute.name)) {\n * // leaving the products subtree entirely — flush product-related caches\n * productCache.clear();\n * }\n * });\n * ```\n *\n * ⚠ Do NOT read `nextRoute.transition` here. `nextRoute` is the PENDING target,\n * and the pipeline gives it the neutral default — empty `segments`, optional\n * flags `undefined` — so the example this replaced read `[]` and `undefined`\n * whatever the navigation was. (It threw outright until real-router#1976\n * attached the field.) The real metadata is written at the COMMIT: read it in\n * `router.subscribe`, `onTransitionSuccess`, or `getState()`.\n */\nexport function useRouteExit(\n handler: RouteExitHandler,\n options?: UseRouteExitOptions,\n): void {\n const router = useRouter();\n const handlerRef = useRef(handler);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler accessible to the subscription without\n // resubscribing on every render — the subscription registers the\n // wrapper once and dispatches to whatever ref points to.\n // useLayoutEffect (synchronous, post-render, pre-paint) updates the\n // ref before the browser can dispatch any router events that could\n // observe a stale closure.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n // The same-route + reentrant-abort guards and the Promise passthrough\n // live in the shared listener (@real-router/sources, #1435). The ref-thunk\n // keeps the latest handler reachable from the long-lived subscription\n // without resubscribing on every render.\n return router.subscribeLeave(\n guardLeaveListener((context) => handlerRef.current(context), {\n skipSameRoute,\n }),\n );\n }, [router, skipSameRoute]);\n}\n","import { createRouteEnterGate } from \"@real-router/sources\";\nimport { useEffect, useLayoutEffect, useRef, useState } from \"react\";\n\nimport { useRoute } from \"./useRoute\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteEnterContext {\n /** The route that was just activated. */\n route: State;\n /** The route that was active immediately before this navigation. */\n previousRoute: State;\n}\n\nexport type RouteEnterHandler = (context: RouteEnterContext) => void;\n\nexport interface UseRouteEnterOptions {\n /**\n * Skip the handler when `route.name === previousRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`. Symmetric with `useRouteExit`'s same-name option.\n */\n skipSameRoute?: boolean;\n}\n\n/**\n * Fire `handler` once when the component mounts as a result of a\n * navigation. Mirror of `useRouteExit` for the entry side.\n *\n * What this hook covers that ad-hoc `useEffect` + `useRoute()` doesn't:\n *\n * - **Skip-initial**: handler is skipped when there is no\n * `previousRoute` (i.e. first-load mount). Most consumers want to\n * fire side effects only on real navigations, not on hydration.\n * - **Same-route skip** (default): handler is skipped when\n * `route.name === previousRoute.name`. Sort/filter/query-only\n * navigations re-run the effect (because `route` reference changes\n * in `useRoute`'s snapshot), but they are not \"entries\" in the\n * animation / analytics sense — the component instance has stayed\n * mounted throughout. Opt out with `skipSameRoute: false` when\n * the handler legitimately needs to fire on every navigation\n * (e.g. analytics tracking each query-param flip).\n * - **StrictMode double-mount immunity**: in dev, React's StrictMode\n * runs every effect twice to surface bugs. Without a guard,\n * analytics fire twice, animations restart, focus jumps. The hook\n * tracks the last-handled `route` reference and short-circuits the\n * second pass.\n * - **Latest-handler ref**: the handler can change identity on every\n * render without re-running the effect — the registered wrapper\n * dispatches to whatever `handlerRef.current` points to.\n * - **Mount-time `route` / `previousRoute` snapshot**: the handler\n * receives the values that were live at the moment of mount, not\n * the latest ones (which may have moved on if the user navigated\n * again before the effect drained).\n *\n * Race-safety: `useRoute()` is wired through `useSyncExternalStore` from\n * `@real-router/sources`, so by the time the new component's effect\n * runs, the snapshot is the post-commit one. This is the reason we can\n * read mount-time context from `useRoute()` instead of subscribing to\n * `router.subscribe` directly (which fires before React schedules a\n * re-render — the well-known race in distributed components).\n *\n * @example Direction-aware entry animation\n * ```tsx\n * useRouteEnter(({ route }) => {\n * const direction = route.context.browser?.direction;\n * ref.current?.classList.add(\n * direction === \"back\" ? \"slide-from-left\" : \"slide-from-right\",\n * );\n * });\n * ```\n *\n * @example Source-aware focus management\n * ```tsx\n * useRouteEnter(({ route }) => {\n * if (route.context.browser?.source === \"navigate\") {\n * headingRef.current?.focus();\n * }\n * });\n * ```\n *\n * @example Analytics page-enter event (skip-initial built-in)\n * ```tsx\n * useRouteEnter(({ route, previousRoute }) => {\n * analytics.track(\"page_enter\", {\n * route: route.name,\n * from: previousRoute.name,\n * });\n * });\n * ```\n *\n * @example Reading rich transition metadata via `route.transition`\n * ```tsx\n * useRouteEnter(({ route }) => {\n * // route.transition: TransitionMeta — populated by core for every state\n * // ⚠ NOT `transition.redirected` — the router never sets it (it only ever\n * // carries what a caller passed as `{ redirected: true }`), so branching on\n * // it here is silently dead for a `forwardTo` or a guard redirect.\n * // `from` needs no check: this hook does not fire without one.\n * showToast(`Arrived from ${route.transition.from}`);\n * if (route.transition.segments.activated.includes(\"products\")) {\n * // products subtree just became active (could be products or\n * // products.detail). Useful for subtree-scoped side effects.\n * }\n * });\n * ```\n */\nexport function useRouteEnter(\n handler: RouteEnterHandler,\n options?: UseRouteEnterOptions,\n): void {\n const { route, previousRoute } = useRoute();\n const handlerRef = useRef(handler);\n // The canonical enter-guard set + `lastHandledRoute` dedupe live in the\n // shared gate (@real-router/sources, #1435). Created once via useState's\n // lazy initializer so its dedupe state is stable across StrictMode's effect\n // re-runs — `skipSameRoute` is threaded per-call, so an options flip never\n // forces a fresh gate (which would reset the dedupe). `useState`, not a ref:\n // the gate must be created once and stay stable, and a ref write during\n // render is disallowed (@eslint-react/refs); the gate is never re-set, so no\n // re-render is triggered. The gate owns skip-initial / same-route /\n // StrictMode-dedupe / the `!previousRoute` guard — the sole defense of the\n // non-nullable `RouteEnterContext.previousRoute` contract (#1218 PC1/PC2).\n const [gate] = useState(() => createRouteEnterGate());\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler reference accessible without re-running\n // the effect. useLayoutEffect (synchronous, post-render, pre-paint)\n // updates the ref before the effect can read it.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n const context = gate(route, previousRoute, skipSameRoute);\n\n if (context) {\n handlerRef.current(context);\n }\n }, [gate, route, previousRoute, skipSameRoute]);\n}\n"],"mappings":"imBAEA,SAAgB,EAAM,EAA0B,CAC9C,OAAO,IACT,CAEA,EAAM,YAAc,kBAEpB,SAAgB,EAAK,EAAyB,CAC5C,OAAO,IACT,CAEA,EAAK,YAAc,iBAEnB,SAAgB,EAAS,EAA6B,CACpD,OAAO,IACT,CAEA,EAAS,YAAc,qBCTvB,MAAM,EAAqC,IAAI,IAAI,CAAC,EAAO,EAAM,CAAQ,CAAC,EAgB1E,SAAS,EACP,EACA,EACA,EACS,CAST,OARI,IAAoB,GACf,GAGL,EACK,IAAc,EAGhB,EAAkB,EAAW,CAAe,CACrD,CAEA,SAAgB,EACd,EACA,EACM,CAYN,EAAS,QAAQ,EAAW,GAAU,CAC/B,EAAe,CAAK,IAIrB,EAAa,IAAI,EAAM,IAAI,EAC7B,EAAO,KAAK,CAAK,EAEjB,EACG,EAAM,MAA2C,SAClD,CACF,EAEJ,CAAC,CACH,CAEA,SAAS,EACP,EACA,EACA,EACA,EACA,EACc,CACd,IAAM,EACJ,IAAa,IAAA,GACX,EAEA,EAAC,EAAD,CAAoB,WAAW,SAAA,CAAuB,CAAA,EAW1D,OARI,EAEA,EAAC,EAAD,CAAgB,OACb,SAAA,CACO,EAFiB,CAEjB,EAIP,EAAC,EAAD,CAAA,SAAqB,CAAkB,EAAxB,CAAwB,CAChD,CAEA,SAAS,EAAe,EAAqB,EAA+B,CAwB1E,OAvBI,EAAM,OAAS,GAI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,EACM,CACN,GAAM,CAAE,QAAO,iBAAkB,EAAS,EACpC,EAAa,EAAO,CAAO,EAW3B,CAAC,GAAQ,MAAe,EAAqB,CAAC,EAC9C,EAAgB,GAAS,eAAiB,GAKhD,MAAsB,CACpB,EAAW,QAAU,CACvB,CAAC,EAED,MAAgB,CACd,IAAM,EAAU,EAAK,EAAO,EAAe,CAAa,EAEpD,GACF,EAAW,QAAQ,CAAO,CAE9B,EAAG,CAAC,EAAM,EAAO,EAAe,CAAa,CAAC,CAChD"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/components/modern/RouteView/components.tsx","../../src/components/modern/RouteView/helpers.tsx","../../src/components/modern/RouteView/RouteView.tsx","../../src/hooks/useRouteExit.tsx","../../src/hooks/useRouteEnter.tsx"],"sourcesContent":["import type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\n\nexport function Match(_props: MatchProps): null {\n return null;\n}\n\nMatch.displayName = \"RouteView.Match\";\n\nexport function Self(_props: SelfProps): null {\n return null;\n}\n\nSelf.displayName = \"RouteView.Self\";\n\nexport function NotFound(_props: NotFoundProps): null {\n return null;\n}\n\nNotFound.displayName = \"RouteView.NotFound\";\n","import { UNKNOWN_ROUTE } from \"@real-router/core\";\nimport { startsWithSegment } from \"@real-router/route-utils\";\nimport { Activity, Children, Fragment, Suspense, isValidElement } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\n\nimport type { MatchProps, NotFoundProps, SelfProps } from \"./types\";\nimport type { ReactElement, ReactNode } from \"react\";\n\nconst MARKER_TYPES: ReadonlySet<unknown> = new Set([Match, Self, NotFound]);\n\ninterface FallbackSlots {\n selfChildren: ReactNode;\n selfFallback: ReactNode | undefined;\n selfFound: boolean;\n notFoundChildren: ReactNode;\n notFoundFound: boolean;\n}\n\n// Fixed keys used by appendFallback to distinguish the Self / NotFound\n// render slots from user-supplied <Match> children. Match render slots key\n// off `fullSegmentName` instead — these two are the only synthetic keys.\nconst SELF_KEY = \"__route-view-self__\";\nconst NOT_FOUND_KEY = \"__route-view-not-found__\";\n\nfunction isSegmentMatch(\n routeName: string,\n fullSegmentName: string,\n exact: boolean,\n): boolean {\n if (fullSegmentName === \"\") {\n return false;\n }\n\n if (exact) {\n return routeName === fullSegmentName;\n }\n\n return startsWithSegment(routeName, fullSegmentName);\n}\n\nexport function collectElements(\n children: ReactNode,\n result: ReactElement[],\n): void {\n // Recurses into Fragment-like wrappers (anything that isn't Match / Self /\n // NotFound) to flatten the slot tree. No explicit depth guard: typical\n // RouteView shape is `<RouteView><Match/>...<NotFound/></RouteView>` —\n // depth ≤ 3 in real apps. A pathological hand-written tree of N Fragments\n // recurses N times; the call stack, not this function, is the bound.\n //\n // `Children.forEach` iterates without `Children.toArray`'s array allocation\n // and per-child clone-with-synthetic-key step. We don't read child.key here\n // (Match/Self/NotFound carry their own segment-derived keys further down),\n // so the cheaper iterator is functionally equivalent.\n // eslint-disable-next-line @eslint-react/no-children-for-each -- intentional: collectElements is a render-hot pipeline; toArray's array+key clone is wasteful here\n Children.forEach(children, (child) => {\n if (!isValidElement(child)) {\n return;\n }\n\n if (MARKER_TYPES.has(child.type)) {\n result.push(child);\n } else {\n collectElements(\n (child.props as { readonly children: ReactNode }).children,\n result,\n );\n }\n });\n}\n\nfunction renderSlotElement(\n slotChildren: ReactNode,\n key: string,\n keepAlive: boolean,\n mode: \"visible\" | \"hidden\",\n fallback?: ReactNode,\n): ReactElement {\n const content =\n fallback === undefined ? (\n slotChildren\n ) : (\n <Suspense fallback={fallback}>{slotChildren}</Suspense>\n );\n\n if (keepAlive) {\n return (\n <Activity mode={mode} key={key}>\n {content}\n </Activity>\n );\n }\n\n return <Fragment key={key}>{content}</Fragment>;\n}\n\nfunction recordFallback(child: ReactElement, slots: FallbackSlots): boolean {\n if (child.type === NotFound) {\n // First-wins: subsequent <NotFound> elements are ignored, symmetric with\n // <Self> below (#1220). Before this guard the assignment was unconditional\n // (last-wins), contradicting the documented Self-symmetric contract.\n if (!slots.notFoundFound) {\n slots.notFoundChildren = (child.props as NotFoundProps).children;\n slots.notFoundFound = true;\n }\n\n return true;\n }\n\n if (child.type === Self) {\n // First-wins: subsequent <Self> elements are ignored, mirroring NotFound.\n if (!slots.selfFound) {\n slots.selfChildren = (child.props as SelfProps).children;\n slots.selfFallback = (child.props as SelfProps).fallback;\n slots.selfFound = true;\n }\n\n return true;\n }\n\n return false;\n}\n\nfunction processMatch(\n child: ReactElement,\n routeName: string,\n nodeName: string,\n hasBeenActivated: ReadonlySet<string>,\n alreadyActive: boolean,\n): { rendered: ReactElement | null; activatedName: string | null } {\n const matchProps = child.props as MatchProps;\n const { segment, exact = false, keepAlive = false, fallback } = matchProps;\n const fullSegmentName = nodeName ? `${nodeName}.${segment}` : segment;\n const isActive =\n !alreadyActive && isSegmentMatch(routeName, fullSegmentName, exact);\n\n if (isActive) {\n // The keepAlive Set is NOT mutated here — RouteView commits the activation\n // in a post-render effect (#1251). Mutating during render coupled the pure\n // winner computation to a side effect (blocking memoization) and, under\n // concurrent rendering, a discarded render would leave a phantom entry that\n // later renders an un-committed match as a hidden keepAlive subtree.\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"visible\",\n fallback,\n ),\n activatedName: fullSegmentName,\n };\n }\n\n if (keepAlive && hasBeenActivated.has(fullSegmentName)) {\n return {\n rendered: renderSlotElement(\n matchProps.children,\n fullSegmentName,\n keepAlive,\n \"hidden\",\n fallback,\n ),\n activatedName: null,\n };\n }\n\n return { rendered: null, activatedName: null };\n}\n\nfunction appendFallback(\n rendered: ReactElement[],\n routeName: string,\n nodeName: string,\n slots: FallbackSlots,\n): void {\n if (slots.selfFound && routeName === nodeName) {\n rendered.push(\n renderSlotElement(\n slots.selfChildren,\n SELF_KEY,\n false,\n \"visible\",\n slots.selfFallback,\n ),\n );\n\n return;\n }\n\n if (routeName === UNKNOWN_ROUTE && slots.notFoundChildren !== null) {\n rendered.push(\n <Fragment key={NOT_FOUND_KEY}>{slots.notFoundChildren}</Fragment>,\n );\n }\n}\n\nexport function buildRenderList(\n elements: ReactElement[],\n routeName: string,\n nodeName: string,\n hasBeenActivated: ReadonlySet<string>,\n): {\n rendered: ReactElement[];\n activeMatchFound: boolean;\n activatedName: string | null;\n} {\n const slots: FallbackSlots = {\n selfChildren: null,\n selfFallback: undefined,\n selfFound: false,\n notFoundChildren: null,\n notFoundFound: false,\n };\n // The segment that activated this render, or null. Reported to the caller so\n // RouteView can commit it to the keepAlive Set post-render (#1251) — this pure\n // walk no longer mutates the Set. At most one match activates (first-wins via\n // the `alreadyActive` short-circuit), so a single name suffices.\n let activatedName: string | null = null;\n const rendered: ReactElement[] = [];\n\n for (const child of elements) {\n if (recordFallback(child, slots)) {\n continue;\n }\n\n const result = processMatch(\n child,\n routeName,\n nodeName,\n hasBeenActivated,\n activatedName !== null,\n );\n\n if (result.activatedName !== null) {\n activatedName = result.activatedName;\n }\n\n if (result.rendered !== null) {\n rendered.push(result.rendered);\n }\n }\n\n if (activatedName === null) {\n appendFallback(rendered, routeName, nodeName, slots);\n }\n\n return { rendered, activeMatchFound: activatedName !== null, activatedName };\n}\n","import { useEffect, useMemo, useRef } from \"react\";\n\nimport { Match, NotFound, Self } from \"./components\";\nimport { buildRenderList, collectElements } from \"./helpers\";\nimport { useRouteNode } from \"../../../hooks/useRouteNode\";\n\nimport type { RouteViewProps } from \"./types\";\nimport type { ReactElement } from \"react\";\n\nfunction RouteViewRoot({\n nodeName,\n children,\n}: Readonly<RouteViewProps>): ReactElement | null {\n const { route } = useRouteNode(nodeName);\n const hasBeenActivatedRef = useRef<Set<string> | null>(null);\n\n // eslint-disable-next-line @eslint-react/refs -- lazy init: assign once when null to avoid `new Set()` allocation on every render\n hasBeenActivatedRef.current ??= new Set();\n // eslint-disable-next-line @eslint-react/refs -- stable render cache; the ref is never reassigned after lazy init\n const hasBeenActivated = hasBeenActivatedRef.current;\n\n // Skip the Children.forEach + collectElements traversal when the children\n // reference is unchanged. The common SPA case is a stable JSX tree across\n // re-renders, so the cache hits on every render except the first.\n //\n // Streaming SSR caveat: with `renderToReadableStream`, React may invoke\n // RouteView multiple times across chunks with a fresh `children` reference\n // each time. The useMemo misses on each new render and the traversal runs\n // again — this is the expected SSR cost; the alternative would be build-\n // time codegen of the static route tree, which is out of scope here.\n const elements = useMemo(() => {\n const collected: ReactElement[] = [];\n\n collectElements(children, collected);\n\n return collected;\n }, [children]);\n\n const routeName = route?.name ?? null;\n\n // Memoize the render walk by its pure inputs. Previously `buildRenderList` ran\n // on EVERY render because `processMatch` mutated the keepAlive Set inline —\n // coupling the pure winner/`rendered` computation to a side effect, so a\n // parent re-render with no route change re-walked every Match and re-diffed\n // the identical output (preact, whose `buildRenderList` is a 3-arg pure\n // function, already memoizes here). The Set mutation now lives in the effect\n // below, so the walk memoizes on `[elements, routeName, nodeName]` too. #1251.\n const { rendered, activatedName } = useMemo(() => {\n if (routeName === null) {\n return { rendered: [] as ReactElement[], activatedName: null };\n }\n\n const result = buildRenderList(\n elements,\n routeName,\n nodeName,\n hasBeenActivated,\n );\n\n return { rendered: result.rendered, activatedName: result.activatedName };\n }, [elements, routeName, nodeName, hasBeenActivated]);\n\n // Commit the keepAlive activation AFTER render, not during it. A render that\n // React discards under concurrent rendering must not record an activation\n // that never committed — otherwise a later render would show that\n // never-mounted match as a hidden keepAlive subtree. Adding the same name\n // twice is a no-op, so the effect is safe to re-run.\n // `hasBeenActivated` is a ref-held Set (L15-20), mutated post-commit in this\n // effect — the concurrent-safe pattern #1251 established. @eslint-react's\n // experimental `immutability` rule (detection widened in v5.17) flags the ref\n // mutation and suggests state, which would defeat the ref's whole purpose\n // (re-render-free activation tracking). Intentional exception, scoped here.\n /* eslint-disable @eslint-react/immutability -- intentional post-commit ref-Set mutation, see #1251 */\n useEffect(() => {\n if (activatedName !== null) {\n hasBeenActivated.add(activatedName);\n }\n }, [activatedName, hasBeenActivated]);\n /* eslint-enable @eslint-react/immutability */\n\n if (rendered.length > 0) {\n return <>{rendered}</>;\n }\n\n return null;\n}\n\nRouteViewRoot.displayName = \"RouteView\";\n\nexport const RouteView = Object.assign(RouteViewRoot, {\n Match,\n Self,\n NotFound,\n});\n\nexport type {\n RouteViewProps,\n MatchProps as RouteViewMatchProps,\n SelfProps as RouteViewSelfProps,\n NotFoundProps as RouteViewNotFoundProps,\n} from \"./types\";\n","import { guardLeaveListener } from \"@real-router/sources\";\nimport { useEffect, useLayoutEffect, useRef } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteExitContext {\n /** The route being left. */\n route: State;\n /** The route being navigated to. */\n nextRoute: State;\n /**\n * AbortSignal that fires when this navigation is superseded by a later\n * one (rapid clicks). Already filtered: when the handler runs,\n * `signal.aborted` is guaranteed to be `false`. Use\n * `signal.addEventListener(\"abort\", cleanup, { once: true })` for\n * cleanup that must run on cancellation.\n */\n signal: AbortSignal;\n}\n\nexport interface UseRouteExitOptions {\n /**\n * Skip the handler when `route.name === nextRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`.\n */\n skipSameRoute?: boolean;\n}\n\nexport type RouteExitHandler = (\n context: RouteExitContext,\n) => void | Promise<void>;\n\n/**\n * Subscribe to the router's leave-window with the universal guards baked\n * in. Wraps `router.subscribeLeave` so consumers don't repeat the same\n * boilerplate every time:\n *\n * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`\n * when the handler would run (rapid navigation superseded a slower\n * one), the handler is skipped entirely. `signal.addEventListener(\n * \"abort\", ...)` does not fire retroactively, so without this guard\n * downstream cleanup would never trigger.\n * - **Same-route skip**: by default, `route.name === nextRoute.name`\n * short-circuits the handler — query-only navigations (sort, filter,\n * pagination) skip the work. Opt out with `skipSameRoute: false`.\n * - **Stable handler reference**: the handler can change identity on\n * every render without causing resubscription — internal ref keeps\n * the latest handler accessible to the long-lived subscription.\n *\n * Returns nothing — the subscription's lifecycle is bound to the\n * component's mount.\n *\n * If the handler returns a Promise, the router blocks on it. If the\n * Promise resolves, navigation proceeds. If it **rejects**, the router\n * rejects `navigate()` with the handler's **original error** and emits\n * `TRANSITION_ERROR` — it is NOT re-coded to `TRANSITION_CANCELLED`\n * (that arises only when the navigation's `signal` aborts: a superseding\n * navigation, `stop()`, `dispose()`, or an external `opts.signal`).\n *\n * **Reentrancy — no synchronous `navigate()` from the handler.** The handler\n * runs inside the transition's leave-dispatch window, so calling\n * `router.navigate(...)` (or `navigateToDefault` / `navigateToState` /\n * `navigateToNotFound`) **synchronously** in the handler body throws\n * `REENTRANT_NAVIGATION` — core bans reentrant navigation from a transition\n * listener (RFC navigation-cancellation-unification §4). To redirect on exit,\n * defer past the sync dispatch: `await` your exit work first, or\n * `queueMicrotask(() => router.navigate(...))`. A navigate issued after the\n * handler's first `await` runs once the transition settles and is allowed.\n * (Guards — `canDeactivate` — are the intended place to *block* or gate a\n * departure; `useRouteExit` is for side effects, not redirection.)\n *\n * @example Animation\n * ```tsx\n * const ref = useRef<HTMLDivElement>(null);\n *\n * useRouteExit(async ({ signal }) => {\n * const el = ref.current;\n * if (!el) return;\n * el.classList.add(\"fade-out\");\n * const cleanup = () => el.classList.remove(\"fade-out\");\n * signal.addEventListener(\"abort\", cleanup, { once: true });\n * try {\n * el.getBoundingClientRect(); // style flush\n * await Promise.allSettled(el.getAnimations().map((a) => a.finished));\n * } finally {\n * cleanup();\n * }\n * });\n * ```\n *\n * @example Auto-save form draft\n * ```tsx\n * useRouteExit(async ({ signal }) => {\n * if (formState.dirty) await api.saveDraft(formState, { signal });\n * });\n * ```\n *\n * @example Cancel inflight requests\n * ```tsx\n * useRouteExit(() => {\n * inflightController.abort();\n * });\n * ```\n *\n * @example Library-coordinated exit (motion / framer-motion)\n * ```tsx\n * const exitResolverRef = useRef<(() => void) | null>(null);\n *\n * useRouteExit(({ signal }) => {\n * return new Promise<void>((resolve) => {\n * exitResolverRef.current = resolve;\n * signal.addEventListener(\"abort\", () => resolve(), { once: true });\n * });\n * });\n *\n * const onExitComplete = () => exitResolverRef.current?.();\n * // pass onExitComplete to <AnimatePresence>\n * ```\n *\n * @example Detecting that you are leaving a subtree\n * ```tsx\n * const inProducts = (name: string) =>\n * name === \"products\" || name.startsWith(\"products.\");\n *\n * useRouteExit(({ route, nextRoute }) => {\n * if (inProducts(route.name) && !inProducts(nextRoute.name)) {\n * // leaving the products subtree entirely — flush product-related caches\n * productCache.clear();\n * }\n * });\n * ```\n *\n * ⚠ Do NOT read `nextRoute.transition` here. `nextRoute` is the PENDING target,\n * and the pipeline gives it the neutral default — empty `segments`, optional\n * flags `undefined` — so the example this replaced read `[]` and `undefined`\n * whatever the navigation was. (It threw outright until real-router#1976\n * attached the field.) The real metadata is written at the COMMIT: read it in\n * `router.subscribe`, `onTransitionSuccess`, or `getState()`.\n */\nexport function useRouteExit(\n handler: RouteExitHandler,\n options?: UseRouteExitOptions,\n): void {\n const router = useRouter();\n const handlerRef = useRef(handler);\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler accessible to the subscription without\n // resubscribing on every render — the subscription registers the\n // wrapper once and dispatches to whatever ref points to.\n // useLayoutEffect (synchronous, post-render, pre-paint) updates the\n // ref before the browser can dispatch any router events that could\n // observe a stale closure.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n // The same-route + reentrant-abort guards and the Promise passthrough\n // live in the shared listener (@real-router/sources, #1435). The ref-thunk\n // keeps the latest handler reachable from the long-lived subscription\n // without resubscribing on every render.\n return router.subscribeLeave(\n guardLeaveListener((context) => handlerRef.current(context), {\n skipSameRoute,\n }),\n );\n }, [router, skipSameRoute]);\n}\n","import { createRouteEnterGate } from \"@real-router/sources\";\nimport { useEffect, useLayoutEffect, useRef, useState } from \"react\";\n\nimport { useRoute } from \"./useRoute\";\n\nimport type { State } from \"@real-router/core\";\n\nexport interface RouteEnterContext {\n /** The route that was just activated. */\n route: State;\n /** The route that was active immediately before this navigation. */\n previousRoute: State;\n}\n\nexport type RouteEnterHandler = (context: RouteEnterContext) => void;\n\nexport interface UseRouteEnterOptions {\n /**\n * Skip the handler when `route.name === previousRoute.name`\n * (sort/filter/query-only navigations on the same route). Default:\n * `true`. Symmetric with `useRouteExit`'s same-name option.\n */\n skipSameRoute?: boolean;\n}\n\n/**\n * Fire `handler` once when the component mounts as a result of a\n * navigation. Mirror of `useRouteExit` for the entry side.\n *\n * What this hook covers that ad-hoc `useEffect` + `useRoute()` doesn't:\n *\n * - **Skip-initial**: handler is skipped when there is no\n * `previousRoute` (i.e. first-load mount). Most consumers want to\n * fire side effects only on real navigations, not on hydration.\n * - **Same-route skip** (default): handler is skipped when\n * `route.name === previousRoute.name`. Sort/filter/query-only\n * navigations re-run the effect (because `route` reference changes\n * in `useRoute`'s snapshot), but they are not \"entries\" in the\n * animation / analytics sense — the component instance has stayed\n * mounted throughout. Opt out with `skipSameRoute: false` when\n * the handler legitimately needs to fire on every navigation\n * (e.g. analytics tracking each query-param flip).\n * - **StrictMode double-mount immunity**: in dev, React's StrictMode\n * runs every effect twice to surface bugs. Without a guard,\n * analytics fire twice, animations restart, focus jumps. The hook\n * tracks the last-handled `route` reference and short-circuits the\n * second pass.\n * - **Latest-handler ref**: the handler can change identity on every\n * render without re-running the effect — the registered wrapper\n * dispatches to whatever `handlerRef.current` points to.\n * - **Mount-time `route` / `previousRoute` snapshot**: the handler\n * receives the values that were live at the moment of mount, not\n * the latest ones (which may have moved on if the user navigated\n * again before the effect drained).\n *\n * Race-safety: `useRoute()` is wired through `useSyncExternalStore` from\n * `@real-router/sources`, so by the time the new component's effect\n * runs, the snapshot is the post-commit one. This is the reason we can\n * read mount-time context from `useRoute()` instead of subscribing to\n * `router.subscribe` directly (which fires before React schedules a\n * re-render — the well-known race in distributed components).\n *\n * @example Direction-aware entry animation\n * ```tsx\n * useRouteEnter(({ route }) => {\n * const direction = route.context.browser?.direction;\n * ref.current?.classList.add(\n * direction === \"back\" ? \"slide-from-left\" : \"slide-from-right\",\n * );\n * });\n * ```\n *\n * @example Source-aware focus management\n * ```tsx\n * useRouteEnter(({ route }) => {\n * if (route.context.browser?.source === \"navigate\") {\n * headingRef.current?.focus();\n * }\n * });\n * ```\n *\n * @example Analytics page-enter event (skip-initial built-in)\n * ```tsx\n * useRouteEnter(({ route, previousRoute }) => {\n * analytics.track(\"page_enter\", {\n * route: route.name,\n * from: previousRoute.name,\n * });\n * });\n * ```\n *\n * @example Reading rich transition metadata via `route.transition`\n * ```tsx\n * useRouteEnter(({ route }) => {\n * // route.transition: TransitionMeta — populated by core for every state\n * // ⚠ NOT `transition.redirected` — the router never sets it (it only ever\n * // carries what a caller passed as `{ redirected: true }`), so branching on\n * // it here is silently dead for a `forwardTo` or a guard redirect.\n * // `from` needs no check: this hook does not fire without one.\n * showToast(`Arrived from ${route.transition.from}`);\n * if (route.transition.segments.activated.includes(\"products\")) {\n * // products subtree just became active (could be products or\n * // products.detail). Useful for subtree-scoped side effects.\n * }\n * });\n * ```\n */\nexport function useRouteEnter(\n handler: RouteEnterHandler,\n options?: UseRouteEnterOptions,\n): void {\n const { route, previousRoute } = useRoute();\n const handlerRef = useRef(handler);\n // The canonical enter-guard set + `lastHandledRoute` dedupe live in the\n // shared gate (@real-router/sources, #1435). Created once via useState's\n // lazy initializer so its dedupe state is stable across StrictMode's effect\n // re-runs — `skipSameRoute` is threaded per-call, so an options flip never\n // forces a fresh gate (which would reset the dedupe). `useState`, not a ref:\n // the gate must be created once and stay stable, and a ref write during\n // render is disallowed (@eslint-react/refs); the gate is never re-set, so no\n // re-render is triggered. The gate owns skip-initial / same-route /\n // StrictMode-dedupe / the `!previousRoute` guard — the sole defense of the\n // non-nullable `RouteEnterContext.previousRoute` contract (#1218 PC1/PC2).\n const [gate] = useState(() => createRouteEnterGate());\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // Keep the latest handler reference accessible without re-running\n // the effect. useLayoutEffect (synchronous, post-render, pre-paint)\n // updates the ref before the effect can read it.\n useLayoutEffect(() => {\n handlerRef.current = handler;\n });\n\n useEffect(() => {\n const context = gate(route, previousRoute, skipSameRoute);\n\n if (context) {\n handlerRef.current(context);\n }\n }, [gate, route, previousRoute, skipSameRoute]);\n}\n"],"mappings":"imBAEA,SAAgB,EAAM,EAA0B,CAC9C,OAAO,IACT,CAEA,EAAM,YAAc,kBAEpB,SAAgB,EAAK,EAAyB,CAC5C,OAAO,IACT,CAEA,EAAK,YAAc,iBAEnB,SAAgB,EAAS,EAA6B,CACpD,OAAO,IACT,CAEA,EAAS,YAAc,qBCTvB,MAAM,EAAqC,IAAI,IAAI,CAAC,EAAO,EAAM,CAAQ,CAAC,EAgB1E,SAAS,EACP,EACA,EACA,EACS,CAST,OARI,IAAoB,GACf,GAGL,EACK,IAAc,EAGhB,EAAkB,EAAW,CAAe,CACrD,CAEA,SAAgB,EACd,EACA,EACM,CAYN,EAAS,QAAQ,EAAW,GAAU,CAC/B,EAAe,CAAK,IAIrB,EAAa,IAAI,EAAM,IAAI,EAC7B,EAAO,KAAK,CAAK,EAEjB,EACG,EAAM,MAA2C,SAClD,CACF,EAEJ,CAAC,CACH,CAEA,SAAS,EACP,EACA,EACA,EACA,EACA,EACc,CACd,IAAM,EACJ,IAAa,IAAA,GACX,EAEA,EAAC,EAAD,CAAoB,WAAW,SAAA,CAAuB,CAAA,EAW1D,OARI,EAEA,EAAC,EAAD,CAAgB,OACb,SAAA,CACO,EAFiB,CAEjB,EAIP,EAAC,EAAD,CAAA,SAAqB,CAAkB,EAAxB,CAAwB,CAChD,CAEA,SAAS,EAAe,EAAqB,EAA+B,CAwB1E,OAvBI,EAAM,OAAS,GAIjB,AAEE,EAAM,iBADN,EAAM,iBAAoB,EAAM,MAAwB,SAClC,IAGjB,IAGL,EAAM,OAAS,IAEjB,AAGE,EAAM,aAFN,EAAM,aAAgB,EAAM,MAAoB,SAChD,EAAM,aAAgB,EAAM,MAAoB,SAC9B,IAGb,GAIX,CAEA,SAAS,EACP,EACA,EACA,EACA,EACA,EACiE,CACjE,IAAM,EAAa,EAAM,MACnB,CAAE,UAAS,QAAQ,GAAO,YA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EAAO,EAAe,CAAa,CAAC,CAChD"}
@@ -32,10 +32,10 @@ interface InkRouterProviderProps {
32
32
  }
33
33
  //#endregion
34
34
  //#region src/components/InkLink.d.ts
35
- declare const InkLink: FC<InkLinkProps>;
35
+ export declare const InkLink: FC<InkLinkProps>;
36
36
  //#endregion
37
37
  //#region src/components/InkRouterProvider.d.ts
38
- declare const InkRouterProvider: FC<InkRouterProviderProps>;
38
+ export declare const InkRouterProvider: FC<InkRouterProviderProps>;
39
39
  //#endregion
40
- export { InkLink, type InkLinkProps, InkRouterProvider, type InkRouterProviderProps, type Navigator, RouterErrorBoundary, type RouterErrorBoundaryProps, type RouterTransitionSnapshot, useNavigator, useRoute, useRouteNode, useRouteUtils, useRouter, useRouterTransition };
40
+ export { type InkLinkProps, type InkRouterProviderProps, type Navigator, RouterErrorBoundary, type RouterErrorBoundaryProps, type RouterTransitionSnapshot, useNavigator, useRoute, useRouteNode, useRouteUtils, useRouter, useRouterTransition };
41
41
  //# sourceMappingURL=ink.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ink.d.mts","names":[],"sources":["../../src/ink-types.ts","../../src/components/InkLink.tsx","../../src/components/InkRouterProvider.tsx"],"mappings":";;;;;;UAQiB,aAAa,UAAU,SAAS;EAC/C;EACA,cAAc;;;;;EAKd,cAAc;EACd,eAAe;EACf;EACA;EACA,WAAW;EACX;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf,QAAQ;EACR,WAAW;;;;cC2HA,SAAS,GAAG;;;cCpJZ,mBAAmB,GAAG"}
1
+ {"version":3,"file":"ink.d.mts","names":[],"sources":["../../src/ink-types.ts","../../src/components/InkLink.tsx","../../src/components/InkRouterProvider.tsx"],"mappings":";;;;;;UAQiB,aAAa,UAAU,SAAS;EAC/C;EACA,cAAc;;;;;EAKd,cAAc;EACd,eAAe;EACf;EACA;EACA,WAAW;EACX;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf,QAAQ;EACR,WAAW;;;;qBC2HA,SAAS,GAAG;;;qBCpJZ,mBAAmB,GAAG"}
package/dist/esm/ink.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e,r as t,t as n}from"./useRoute-5MF3j-9P.mjs";import{a as r,d as i,i as a,m as o,n as s,o as c,p as l,r as u,t as d}from"./RouterProviderCore-CKc1Kt2d.mjs";import{memo as f}from"react";import{jsx as p}from"react/jsx-runtime";import{Text as m,useFocus as h,useInput as g}from"ink";function _(e,t,n,r,i){return e?n??r??i:t?r??i:i}function v(e,t){return e.routeName===t.routeName&&e.activeStrict===t.activeStrict&&e.ignoreQueryParams===t.ignoreQueryParams&&e.color===t.color&&e.activeColor===t.activeColor&&e.focusColor===t.focusColor&&e.inverse===t.inverse&&e.activeInverse===t.activeInverse&&e.focusInverse===t.focusInverse&&e.id===t.id&&e.autoFocus===t.autoFocus&&e.onSelect===t.onSelect&&e.children===t.children&&i(e.routeParams,t.routeParams)&&i(e.routeSearch,t.routeSearch)&&i(e.routeOptions,t.routeOptions)}const y=f(({routeName:n,routeParams:r,routeSearch:i,routeOptions:a=e,activeStrict:s=!1,ignoreQueryParams:l=!0,color:u,activeColor:d,focusColor:f,inverse:v,activeInverse:y,focusInverse:b,id:x,autoFocus:S,onSelect:C,children:w})=>{let T=o(),{isFocused:E}=h({...x!==void 0&&{id:x},...S!==void 0&&{autoFocus:S}}),D=c(n,r,i,s,l),O=r??t;g((e,t)=>{if(t.return){try{C?.()}catch(e){console.error(`[real-router] InkLink onSelect threw; proceeding with navigation.`,e)}T.navigate(n,O,i,a).catch(()=>{})}},{isActive:E});let k=_(E,D,f,d,u),A=_(E,D,b,y,v),j={};return k!==void 0&&(j.color=k),A!==void 0&&(j.inverse=A),p(m,{...j,children:w})},v);y.displayName=`InkLink`;const b=({router:e,children:t})=>p(d,{router:e,children:t});export{y as InkLink,b as InkRouterProvider,r as RouterErrorBoundary,a as useNavigator,n as useRoute,l as useRouteNode,u as useRouteUtils,o as useRouter,s as useRouterTransition};
1
+ import{n as e,r as t,t as n}from"./useRoute-5MF3j-9P.mjs";import{a as r,d as i,i as a,m as o,n as s,o as c,p as l,r as u,t as d}from"./RouterProviderCore-D2YRnfAI.mjs";import{memo as f}from"react";import{jsx as p}from"react/jsx-runtime";import{Text as m,useFocus as h,useInput as g}from"ink";function _(e,t,n,r,i){return e?n??r??i:t?r??i:i}function v(e,t){return e.routeName===t.routeName&&e.activeStrict===t.activeStrict&&e.ignoreQueryParams===t.ignoreQueryParams&&e.color===t.color&&e.activeColor===t.activeColor&&e.focusColor===t.focusColor&&e.inverse===t.inverse&&e.activeInverse===t.activeInverse&&e.focusInverse===t.focusInverse&&e.id===t.id&&e.autoFocus===t.autoFocus&&e.onSelect===t.onSelect&&e.children===t.children&&i(e.routeParams,t.routeParams)&&i(e.routeSearch,t.routeSearch)&&i(e.routeOptions,t.routeOptions)}const y=f(({routeName:n,routeParams:r,routeSearch:i,routeOptions:a=e,activeStrict:s=!1,ignoreQueryParams:l=!0,color:u,activeColor:d,focusColor:f,inverse:v,activeInverse:y,focusInverse:b,id:x,autoFocus:S,onSelect:C,children:w})=>{let T=o(),{isFocused:E}=h({...x!==void 0&&{id:x},...S!==void 0&&{autoFocus:S}}),D=c(n,r,i,s,l),O=r??t;g((e,t)=>{if(t.return){try{C?.()}catch(e){console.error(`[real-router] InkLink onSelect threw; proceeding with navigation.`,e)}T.navigate(n,O,i,a).catch(()=>{})}},{isActive:E});let k=_(E,D,f,d,u),A=_(E,D,b,y,v),j={};return k!==void 0&&(j.color=k),A!==void 0&&(j.inverse=A),p(m,{...j,children:w})},v);y.displayName=`InkLink`;const b=({router:e,children:t})=>p(d,{router:e,children:t});export{y as InkLink,b as InkRouterProvider,r as RouterErrorBoundary,a as useNavigator,n as useRoute,l as useRouteNode,u as useRouteUtils,o as useRouter,s as useRouterTransition};
2
2
  //# sourceMappingURL=ink.mjs.map
@@ -1 +1 @@
1
- import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,i as n,m as r,n as i,p as a,r as o}from"./RouterProviderCore-CKc1Kt2d.mjs";import{n as s,t as c}from"./RouterProvider-CmEutabZ.mjs";export{s as Link,t as RouterErrorBoundary,c as RouterProvider,n as useNavigator,e as useRoute,a as useRouteNode,o as useRouteUtils,r as useRouter,i as useRouterTransition};
1
+ import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,i as n,m as r,n as i,p as a,r as o}from"./RouterProviderCore-D2YRnfAI.mjs";import{n as s,t as c}from"./RouterProvider-DTse0TcY.mjs";export{s as Link,t as RouterErrorBoundary,c as RouterProvider,n as useNavigator,e as useRoute,a as useRouteNode,o as useRouteUtils,r as useRouter,i as useRouterTransition};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@real-router/react",
3
- "version": "0.31.46",
3
+ "version": "0.31.48",
4
4
  "type": "commonjs",
5
5
  "description": "React integration for Real-Router",
6
6
  "main": "./dist/cjs/index.js",
@@ -115,19 +115,19 @@
115
115
  "license": "MIT",
116
116
  "sideEffects": false,
117
117
  "dependencies": {
118
- "@real-router/core": "^0.126.1",
118
+ "@real-router/core": "^0.126.6",
119
119
  "@real-router/route-utils": "^0.3.1",
120
- "@real-router/sources": "^0.14.30"
120
+ "@real-router/sources": "^0.14.32"
121
121
  },
122
122
  "devDependencies": {
123
+ "@real-router/browser-plugin": "^0.22.12",
123
124
  "@testing-library/dom": "~10.4.1",
124
125
  "@testing-library/jest-dom": "~6.9.1",
125
126
  "@testing-library/react": "~16.3.2",
126
127
  "@testing-library/user-event": "~14.6.1",
127
128
  "ink": "7.1.1",
128
129
  "ink-testing-library": "4.0.0",
129
- "vitest-react-profiler": "1.12.0",
130
- "@real-router/browser-plugin": "^0.22.12"
130
+ "vitest-react-profiler": "1.12.0"
131
131
  },
132
132
  "peerDependencies": {
133
133
  "@types/react": ">=18.0.0",
@@ -1,2 +0,0 @@
1
- const e=require("./useRoute-D2vAzKWM.js"),t=require("./RouterProviderCore-Dmp4Qf0f.js");let n=require("react"),r=require("react/jsx-runtime"),i=require("@real-router/sources");const a=`data-real-router-announcer`,o=Object.freeze({destroy:()=>{}});let s=0,c=0;function l(e,t){if(typeof document>`u`)return o;let n=t?.prefix??`Navigated to `,r=t?.getAnnouncementText,i=!0,a=!1,l=!1,m=``,h=null,g,{element:_,generation:v}=u();s+=1;let y=(e,t)=>{m=e,clearTimeout(g),_.textContent=e,g=setTimeout(()=>{_.textContent=``,m=``},7e3),p(t)},b=setTimeout(()=>{if(a=!0,h!==null&&!l){let e=h;h=null,y(e,document.querySelector(`h1`))}},100),x=e.subscribe(({route:e})=>{if(i){i=!1;return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(l)return;let t=document.querySelector(`h1`),i=f(e,n,r,t);if(!(!i||i===m)){if(!a){h=i;return}y(i,t)}})})});return{destroy(){l||(l=!0,x(),clearTimeout(g),clearTimeout(b),v===c&&(--s,s===0&&d(_)))}}}function u(){let e=document.querySelector(`[${a}]`);if(e)return{element:e,generation:c};s=0,c+=1;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(a,``),(document.body??document.documentElement).prepend(t),{element:t,generation:c}}function d(e){e.remove()}function f(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 p(e){e&&(e.hasAttribute(`tabindex`)||e.setAttribute(`tabindex`,`-1`),e.focus({preventScroll:!0}))}const m=Object.create,h=Object.keys,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),t=e?JSON.parse(e):void 0;s=Object.assign(m(null),t)}catch{s=m(null)}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(_)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()},h=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)},_=!1,v=!1,b=!0,x=e=>{try{return y(e)}catch{return v||(v=!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}},S=e.subscribe(({route:e,previousRoute:t})=>{let r=e.context.navigation;if(t&&b){let e=x(t);e!==null&&l(e,d())}b=!1,requestAnimationFrame(()=>{if(!_){if(b=!0,n===`top`){h(e);return}if(e.transition?.reload||r?.navigationType===`reload`){let t=x(e);p(t===null?0:c()[t]??0);return}if(r?.direction===`back`||r?.navigationType===`traverse`){let t=x(e);p(t===null?0:c()[t]??0);return}e.transition?.replace||r?.navigationType===`replace`||h(e)}})}),C=()=>{let t=e.getState();if(t){let e=x(t);e!==null&&l(e,d())}};return globalThis.addEventListener(`pagehide`,C),{destroy:()=>{_=!0,S(),globalThis.removeEventListener(`pagehide`,C);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,...e.search})}`;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=m(null),n=h(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=e=>{if(!a()){for(let t of e)s.set(t.target,t);r()}},d=e=>new IntersectionObserver(u,{root:e,rootMargin:t,threshold:0}),f=n(),p=d(f),m=()=>{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)&&(p.observe(e),o.add(e))}},h={childList:!0,subtree:!0,attributes:!0,attributeFilter:[`id`]},g=null,_=()=>{for(let e of o)e.isConnected||(p.unobserve(e),o.delete(e),s.delete(e));let e=n();e!==f&&(f=e,p.disconnect(),p=d(e),o.clear(),s.clear(),g?.disconnect(),g?.observe(e??document.body,h)),m()};return m(),g=new MutationObserver(()=>{l!==null&&clearTimeout(l),l=setTimeout(()=>{l=null,_()},250)}),g.observe(f??document.body,h),{pending:s,isContainerDetached:()=>f!==null&&!f.isConnected,reconcile:_,destroy(){p.disconnect(),g.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`,a=t.scrollContainer,o=()=>a?.()??null,s=!1,c=!1,l=!1,u=()=>c||s,d=null,f=(0,i.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)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,r.search,i).catch(()=>{}).finally(()=>{l=!1})};let _=e.subscribe(({route:e})=>{l||(g.isContainerDetached()&&g.reconcile(),C(e)?.hashChanged&&m.start())});return{destroy(){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;if(r=!0,t=null,e===null)n=null;else{let t=n;setTimeout(()=>{e(),n===t&&(n=null)},0)}});return{destroy:()=>{a(),o(),n?.skipTransition?.(),n=null,i()}}}function M(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.d(e.routeParams,n.routeParams)&&t.d(e.routeSearch,n.routeSearch)&&t.d(e.to,n.to)&&t.d(e.routeOptions,n.routeOptions)}const N=(0,n.memo)(({routeName:i,routeParams:a,routeSearch:o,to:s,routeOptions:c=e.n,className:l,activeClassName:u=`active`,activeStrict:d=!1,ignoreQueryParams:f=!0,hash:p,onClick:m,target:h,children:g,..._})=>{let v=t.m(),{name:y,params:b,search:x}=t.u(s,i??``,a,o),S=t.o(y,b,x,d,f,p),C=b??e.r,w=t.c(v,y,C,x,p),T=e=>{if(m){try{m(e)}catch(e){console.error(`[real-router] A <Link> onClick handler threw; navigation is unaffected.`,e)}if(e.defaultPrevented)return}!t.f(e.nativeEvent)||h===`_blank`||(e.preventDefault(),t.l(v,y,C,x,p,c).catch(()=>{}))},E=(0,n.useMemo)(()=>t.s(S,u,l),[S,u,l]);return(0,r.jsx)(`a`,{..._,href:w,className:E,onClick:T,children:g})},M);N.displayName=`Link`;const P=({router:e,children:i,announceNavigation:a,scrollRestoration:o,scrollSpy:s,viewTransitions:c})=>{let u=a!==void 0&&a!==!1,d=typeof a==`object`?a:void 0,f=d?.prefix;(0,n.useEffect)(()=>{if(!u)return;let t=l(e,d);return()=>{t.destroy()}},[e,u,f]);let p=o?.mode,m=o?.anchorScrolling,h=o?.behavior,g=o?.storageKey,v=o!==void 0;(0,n.useEffect)(()=>{if(!v)return;let t=_(e,{mode:p,anchorScrolling:m,behavior:h,storageKey:g,scrollContainer:o.scrollContainer});return()=>{t.destroy()}},[e,v,p,m,h,g]);let y=s?.selector,b=s?.rootMargin,x=s!==void 0&&y!==void 0&&y!==``;return(0,n.useEffect)(()=>{if(!x)return;let t=k(e,{selector:y,rootMargin:b,scrollContainer:s.scrollContainer});return()=>{t.destroy()}},[e,x,y,b]),(0,n.useEffect)(()=>{if(!c)return;let t=j(e);return()=>{t.destroy()}},[e,c]),(0,r.jsx)(t.t,{router:e,children:i})};Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return P}});
2
- //# sourceMappingURL=RouterProvider-Cxn25HDw.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"RouterProviderCore-Dmp4Qf0f.js","names":["RouterContext","NavigatorContext","RouterContext","NavigatorContext","RouteContext"],"sources":["../../src/hooks/useRouter.tsx","../../src/hooks/useRouteNode.tsx","../../../../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/RouterProviderCore.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 {\n NavigationOptions,\n NavigationTarget,\n Params,\n Router,\n SearchParams,\n State,\n} from \"@real-router/core\";\n\n/**\n * Intrinsics captured at module load (#1971).\n *\n * ⚑ These DECIDE — they answer \"what is on this object\" for a value this module\n * did not build. Read off the live global they can be re-pointed after boot, and\n * `shared/` is the half where that fails OPEN: measured in `browser-env`, a\n * re-pointed `getPrototypeOf` admits a `Date` into `state.params` and a\n * re-pointed `keys` skips option validation entirely.\n *\n * ⚠ Capture narrows the window from \"any time after boot\" to \"before this module\n * loads\". It does not close it (#1798).\n */\nconst objectKeys = Object.keys;\n\n/**\n * Resolved navigation channels for a `<Link>` — the single `{ name, params,\n * search }` shape every adapter feeds into `buildHref` / `navigateWithHash` /\n * the active-route source, regardless of which prop form the consumer used.\n */\nexport interface ResolvedLinkTarget {\n name: string;\n params: Params | undefined;\n search: SearchParams | undefined;\n}\n\n/**\n * Collapses a `<Link>`'s two prop forms (RFC-4 M2 B2, #1548) into one channel\n * triple:\n *\n * - **Descriptor** — `to={{ name, params?, search? }}` (a `NavigationTarget`).\n * - **Channel props** — `routeName` + `routeParams?` + `routeSearch?`.\n *\n * The forms are mutually exclusive: the TS union on each adapter's `LinkProps`\n * rejects mixing them at compile time, and this helper is the runtime backstop —\n * when `to` is present it **wins**, and a `dev`-visible `console.warn` fires if\n * channel props were also supplied (a JS consumer, an object spread, or an\n * adapter without a strict union can still slip both through). `routeOptions` /\n * `hash` are separate props under BOTH forms (hash is not part of\n * `NavigationTarget` — #532), so they are resolved by the caller, not here.\n */\nexport function resolveLinkTarget(\n to: NavigationTarget | undefined,\n routeName: string,\n routeParams: Params | undefined,\n routeSearch: SearchParams | undefined,\n): ResolvedLinkTarget {\n if (to !== undefined) {\n if (\n routeName !== \"\" ||\n routeParams !== undefined ||\n routeSearch !== undefined\n ) {\n console.warn(\n \"[real-router] <Link> received both `to` and channel props \" +\n \"(routeName / routeParams / routeSearch). `to` wins; the channel \" +\n \"props are ignored. Use one form or the other.\",\n );\n }\n\n return { name: to.name, params: to.params, search: to.search };\n }\n\n return { name: routeName, params: routeParams, search: routeSearch };\n}\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/**\n * RFC 3986 fragment encoding: preserve sub-delims (`&`, `=`, `?`, `:`),\n * encode space, `%`, control chars, non-ASCII via encodeURI; defensively\n * escape `#` (encodeURI does not). Kept BYTE-FOR-BYTE identical to\n * `encodeHashFragment` in `shared/browser-env/url-context.ts` — duplicated\n * because the shared/dom-utils symlink graph does not reach shared/browser-env;\n * a sync test (`link-utils` functional suite) asserts the two stay identical.\n *\n * **STRICTLY-DECODED contract (#1211 / D1=A).** The `<Link hash>` value is a\n * DECODED fragment (no leading `#`) and is encoded verbatim. This OVERTURNS\n * audit-2026-05-17 §5 E.1 — the earlier percent-escape probe (decode + re-encode\n * for copy-from-`location.hash` tolerance) is REMOVED, so both the adapter and\n * the plugin layer obey one contract: `<Link hash=\"a%20b\">` renders `#a%2520b`\n * (the literal fragment `a%20b`) under every runtime. Consumers who want the\n * fragment `a b` pass `hash=\"a b\"`; passing raw `location.hash` (percent-encoded)\n * is no longer supported — it was the source of the plugin↔adapter divergence.\n */\nfunction encodeFragmentInline(decoded: string): string {\n return encodeURI(decoded).replaceAll(\"#\", \"%23\");\n}\n\ntype BuildUrlFn = (\n name: string,\n params: Params,\n search?: SearchParams,\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 the decoded hash fragment (no leading \"#\";\n * `<Link hash=\"#section\">` is accepted defensively — leading \"#\" stripped),\n * passed positionally to mirror `navigateWithHash(router, name, params, hash)`\n * (#1442). Previous 3-arg call sites continue to work unchanged.\n */\nexport function buildHref(\n router: Router,\n routeName: string,\n routeParams: Params,\n routeSearch?: SearchParams,\n hash?: string,\n): string | undefined {\n try {\n let normHash: string | undefined;\n\n if (hash !== undefined) {\n normHash = hash.startsWith(\"#\") ? hash.slice(1) : hash;\n }\n\n const buildUrl = router.buildUrl as BuildUrlFn | undefined;\n\n if (buildUrl) {\n const url = buildUrl(\n routeName,\n routeParams,\n // Query channel at position 3 (RFC-4 M2 / #1548) — from the `routeSearch`\n // prop; hash options at position 4. `undefined` when the link has no\n // `routeSearch` (its query, if any, still rides in routeParams).\n routeSearch,\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, routeSearch);\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, search, opts)` — the query channel took\n * slot 3 in RFC-4 M2 (#1548) — 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 routeSearch: SearchParams | undefined,\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 // What the navigation gets — the caller's `routeSearch` unless the bypass\n // below substitutes it (#1925).\n let navigatedSearch = routeSearch;\n\n if (current !== undefined) {\n // ONE expression, asked ONCE and navigated with under the bypass (#1925).\n // The predicate's answer is only as good as the value it answered ABOUT, so\n // the two must be the same value — a second copy of this expression would\n // let them drift apart with nothing to catch it. The name is what keeps\n // them in agreement structurally rather than by convention.\n const sameLocationSearch = routeSearch ?? current.search;\n\n // \"Does this link point at where we already are?\" is a question the router\n // owns, and asking it here by hand got two things wrong at once (#1555).\n //\n // The hand-rolled version compared with `Object.is` per key, so a link\n // writing `routeSearch={{ page: \"2\" }}` never matched a state parsed from\n // `?page=2`, where the value is the NUMBER 2 — the bypass silently did not\n // fire, core rejected the navigation as SAME_STATES, and `<Link hash>`\n // looked dead. The predicate carries the provenance-tolerant comparison\n // (#1554) that makes the two forms equal because they print the same URL.\n //\n // It also compared the caller's whole `routeParams` bag against\n // `state.params`, which stopped meaning anything once the channels split\n // (#1548) — the predicate applies the channel rule instead of re-deriving\n // it.\n //\n // `strictEquality: true` — a link to a PARENT route is a different\n // location, so the hierarchical arm must not match. `ignoreQueryParams:\n // false` — the query is part of the location here; ignoring it would fire\n // the bypass across a real query change and let `force: true` smuggle it\n // through as a hash change.\n if (\n router.isActiveRoute(\n routeName,\n routeParams,\n sameLocationSearch,\n true,\n false,\n )\n ) {\n const currentHash =\n (current.context as { url?: { hash?: string } } | undefined)?.url\n ?.hash ?? \"\";\n const newHash = hash ?? currentHash;\n\n if (currentHash !== newHash) {\n opts.force = true;\n opts.hashChange = true;\n\n // Reaching here means the predicate answered \"this is where we already\n // are, only the fragment differs\", and `force` + `hashChange` announce\n // exactly that. The bare `routeSearch` would say \"no query\" rather than\n // \"unchanged\" — on `/docs?tab=api` a fragment link would land on\n // `/docs`, moving the location it just announced as unmoved. Same slot,\n // same conclusion as `scroll-spy.ts`, which re-navigates with both\n // channels of the CURRENT state.\n //\n // ⚠ Only under the bypass. Without it the helper claims no sameness, so\n // `<Link routeName=\"docs\">` means `/docs` — substituting there would\n // turn a real navigation into a no-op. An explicit `routeSearch={{}}`\n // still clears the query, because `{}` is not nullish. Both pinned by\n // the #1925 suite.\n navigatedSearch = sameLocationSearch;\n }\n }\n }\n\n // Query channel at position 3 (RFC-4 M2 / #1548); opts at position 4.\n return router.navigate(routeName, routeParams, navigatedSearch, 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\n// `value` is always a truthy class string: both call sites narrow it first\n// (`if (isActive && activeClassName)` / `if (!baseClassName) return …`), so the\n// former `if (!value) return []` guard was unreachable dead code (#809).\nfunction parseTokens(value: string): string[] {\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 continue;\n }\n\n seen.add(token);\n baseTokens.push(token);\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 = objectKeys(prev);\n const nextKeys = objectKeys(next);\n\n if (prevKeys.length !== nextKeys.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 // ⚑ Membership is decided from the LIST the count produced, never from a\n // second question put to the record (#2064; #1815 settled the same question\n // for `recordsShallowEqual` in core). `Object.keys` is own AND enumerable\n // while `hasOwnProperty` is own only — and on a Proxy it is whatever the\n // `getOwnPropertyDescriptor` trap answers.\n //\n // ⚠ `key in next`, `Object.hasOwn` and `propertyIsEnumerable` are the same\n // family, and none of them is the fix: each leaves a cell of this file's\n // own suites red. `lint:membership` is the ratchet over the class.\n //\n // The second array is free: the count already built it and threw it away.\n if (\n !nextKeys.includes(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 { createActiveSource } from \"@real-router/sources\";\nimport { useMemo, useSyncExternalStore } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { Params, SearchParams } from \"@real-router/core\";\n\nexport function useIsActiveRoute(\n routeName: string,\n params?: Params,\n search?: SearchParams,\n strict = false,\n ignoreQueryParams = true,\n hash?: string,\n): boolean {\n const router = useRouter();\n\n // The fast/slow decision — and the `routeName !== \"\"` guard that keeps\n // `useIsActiveRoute(\"\")` in sync with `router.isActiveRoute(\"\")` (a misused\n // empty name matches nothing, #1427) — lives in the shared `createActiveSource`\n // builder, so every adapter resolves active state identically (#1248 landed the\n // fast path inline here; #1427 folded it into the shared builder). The `useMemo`\n // wrap skips the branch + `canonicalJson(params)` + cache lookup on every render\n // when all deps (including the `params` reference) are stable.\n const store = useMemo(\n () =>\n createActiveSource(\n router,\n routeName,\n params,\n search,\n strict,\n ignoreQueryParams,\n hash,\n ),\n [router, routeName, params, search, 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, primeErrorSource } from \"@real-router/sources\";\nimport { useEffect, useMemo, useSyncExternalStore } from \"react\";\n\nimport { NavigatorContext, RouteContext, RouterContext } from \"./context\";\n\nimport type { Router } from \"@real-router/core\";\nimport type { FC, ReactNode } from \"react\";\n\nexport interface RouterProviderCoreProps {\n router: Router;\n children: ReactNode;\n}\n\n/**\n * DOM-free provider core: router / route / navigator contexts plus the\n * `useSyncExternalStore` subscription wiring, with **no** dom-utils dependency.\n *\n * Split out of `RouterProvider` (#800) so the terminal `/ink` entry can compose\n * only this: `InkRouterProvider` renders `RouterProviderCore` directly, keeping\n * the scroll-spy / view-transitions / announcer / scroll-restore factories — all\n * structurally unreachable in a terminal — out of the chunk reachable from\n * `dist/esm/ink.mjs`. The DOM-aware `RouterProvider` wraps this core and layers\n * the opt-in DOM-feature effects on top.\n */\nexport const RouterProviderCore: FC<RouterProviderCoreProps> = ({\n router,\n children,\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 //\n // Activity note (#765): that same first-listener/last-listener contract means\n // a Provider mounted UNDER a React <Activity> / keepAlive boundary drops its\n // subscription while hidden, so a navigation that lands during the hidden\n // window is not observed live. createRouteSource RECONCILES on re-subscribe —\n // when the first listener re-attaches on re-show it re-reads router.getState()\n // — so the re-shown Provider renders the CURRENT route, not a stale snapshot.\n // Mounting RouterProvider at the app root (above any Activity boundary) stays\n // the recommended composition: it keeps the subscription live throughout\n // instead of relying on the reconnect catch-up. See the \"RouterProvider under\n // <Activity>\" gotcha in CLAUDE.md and the P1 regression in\n // tests/integration/reactive-lifecycle.test.tsx.\n const store = useMemo(() => createRouteSource(router), [router]);\n\n // #778 P2: eagerly create the per-router error source so a navigation error\n // that fires BEFORE a RouterErrorBoundary mounts (a lazy app shell, a failed\n // boot navigation) is still captured. The boundary's createDismissableError\n // reuses this cached source and catches up (#765); without it the error source\n // is created lazily on boundary mount — after the error — and never sees it.\n useEffect(() => {\n primeErrorSource(router);\n }, [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,WAAA,CAAoBA,EAAAA,CAAa,EAEvC,GAAI,CAAC,EACH,MAAU,MAAM,gDAAgD,EAGlE,OAAO,CACT,ECNA,SAAgB,EAAa,EAAgC,CAC3D,IAAM,EAAS,EAAU,EAEnB,GAAA,EAAA,EAAA,QAAA,MAAA,EAAA,EAAA,sBAAA,CACwB,EAAQ,CAAQ,EAC5C,CAAC,EAAQ,CAAQ,CACnB,EAKM,GAAA,EAAA,EAAA,qBAAA,CACJ,EAAM,UACN,EAAM,YACN,EAAM,WACR,EAGM,GAAA,EAAA,EAAA,aAAA,CAAyB,CAAM,EAErC,OAAA,EAAA,EAAA,QAAA,MACuB,CACnB,YACA,MAAO,EAAS,MAChB,cAAe,EAAS,aAC1B,GACA,CAAC,EAAW,CAAQ,CACtB,CACF,CCfA,MAAM,EAAa,OAAO,KA4B1B,SAAgB,EACd,EACA,EACA,EACA,EACoB,CAiBpB,OAhBI,IAAO,IAAA,GAgBJ,CAAE,KAAM,EAAW,OAAQ,EAAa,OAAQ,CAAY,IAd/D,IAAc,IACd,IAAgB,IAAA,IAChB,IAAgB,IAAA,KAEhB,QAAQ,KACN,yKAGF,EAGK,CAAE,KAAM,EAAG,KAAM,OAAQ,EAAG,OAAQ,OAAQ,EAAG,MAAO,EAIjE,CAEA,SAAgB,EAAe,EAA0B,CACvD,OACE,EAAI,SAAW,GACf,CAAC,EAAI,SACL,CAAC,EAAI,QACL,CAAC,EAAI,SACL,CAAC,EAAI,QAET,CAmBA,SAAS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AAgB,EACd,EAAA,EAAA,iBAAA,CAAiB,CAAM,CACzB,EAAG,CAAC,CAAM,CAAC,EAKX,IAAM,GAAA,EAAA,EAAA,qBAAA,CACJ,EAAM,UACN,EAAM,YACN,EAAM,WACR,EAEM,GAAA,EAAA,EAAA,QAAA,MACG,CACL,YACA,MAAO,EAAS,MAChB,cAAe,EAAS,aAC1B,GACA,CAAC,EAAW,CAAQ,CACtB,EAEA,OACE,EAAA,EAAA,IAAA,CAACC,EAAAA,EAAc,SAAf,CAAwB,MAAO,EAC7B,UAAA,EAAA,EAAA,IAAA,CAACC,EAAAA,EAAiB,SAAlB,CAA2B,MAAO,EAChC,UAAA,EAAA,EAAA,IAAA,CAACC,EAAAA,EAAa,SAAd,CAAuB,MAAO,EAC3B,UACoB,CAAA,CACE,CAAA,CACL,CAAA,CAE5B"}
@@ -1,2 +0,0 @@
1
- import{n as e,r as t}from"./useRoute-5MF3j-9P.mjs";import{c as n,d as r,f as i,l as a,m as o,o as s,s as c,t as l,u}from"./RouterProviderCore-CKc1Kt2d.mjs";import{memo as d,useEffect as f,useMemo as p}from"react";import{jsx as m}from"react/jsx-runtime";import{getTransitionSource as h}from"@real-router/sources";const g=`data-real-router-announcer`,_=Object.freeze({destroy:()=>{}});let v=0,y=0;function b(e,t){if(typeof document>`u`)return _;let n=t?.prefix??`Navigated to `,r=t?.getAnnouncementText,i=!0,a=!1,o=!1,s=``,c=null,l,{element:u,generation:d}=x();v+=1;let f=(e,t)=>{s=e,clearTimeout(l),u.textContent=e,l=setTimeout(()=>{u.textContent=``,s=``},7e3),w(t)},p=setTimeout(()=>{if(a=!0,c!==null&&!o){let e=c;c=null,f(e,document.querySelector(`h1`))}},100),m=e.subscribe(({route:e})=>{if(i){i=!1;return}requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(o)return;let t=document.querySelector(`h1`),i=C(e,n,r,t);if(!(!i||i===s)){if(!a){c=i;return}f(i,t)}})})});return{destroy(){o||(o=!0,m(),clearTimeout(l),clearTimeout(p),d===y&&(--v,v===0&&S(u)))}}}function x(){let e=document.querySelector(`[${g}]`);if(e)return{element:e,generation:y};v=0,y+=1;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(g,``),(document.body??document.documentElement).prepend(t),{element:t,generation:y}}function S(e){e.remove()}function C(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 w(e){e&&(e.hasAttribute(`tabindex`)||e.setAttribute(`tabindex`,`-1`),e.focus({preventScroll:!0}))}const T=Object.create,E=Object.keys,D=Object.freeze({destroy:()=>{}});function O(e,t){if(globalThis.window===void 0)return D;let n=t?.mode??`restore`;if(n===`native`)return D;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),t=e?JSON.parse(e):void 0;s=Object.assign(T(null),t)}catch{s=T(null)}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,g=!1,_=!0,v=e=>{try{return A(e)}catch{return g||(g=!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}},y=e.subscribe(({route:e,previousRoute:t})=>{let r=e.context.navigation;if(t&&_){let e=v(t);e!==null&&l(e,d())}_=!1,requestAnimationFrame(()=>{if(!h){if(_=!0,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)}})}),b=()=>{let t=e.getState();if(t){let e=v(t);e!==null&&l(e,d())}};return globalThis.addEventListener(`pagehide`,b),{destroy:()=>{h=!0,y(),globalThis.removeEventListener(`pagehide`,b);try{history.scrollRestoration=u}catch{}}}}const k=new WeakMap;function A(e){let t=k.get(e);if(t!==void 0)return t;let n=`${e.name}:${j({...e.params,...e.search})}`;return k.set(e,n),n}function j(e){return JSON.stringify(e,M)}function M(e,t){if(typeof t==`function`)return`<fn>`;if(typeof t==`symbol`)return`<sym>`;if(typeof t==`object`&&t&&!Array.isArray(t)){let e=T(null),n=E(t).sort((e,t)=>e.localeCompare(t));for(let r of n)e[r]=t[r];return e}return t}const N=Object.freeze({destroy:()=>{}}),P=e=>e.context?.url,F=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},I=(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}}},L=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()}}},R=(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)}}},z=(e,t,n,r,i,a)=>{let o=new Set,s=new Map,c=!1,l=null,u=e=>{if(!a()){for(let t of e)s.set(t.target,t);r()}},d=e=>new IntersectionObserver(u,{root:e,rootMargin:t,threshold:0}),f=n(),p=d(f),m=()=>{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)&&(p.observe(e),o.add(e))}},h={childList:!0,subtree:!0,attributes:!0,attributeFilter:[`id`]},g=null,_=()=>{for(let e of o)e.isConnected||(p.unobserve(e),o.delete(e),s.delete(e));let e=n();e!==f&&(f=e,p.disconnect(),p=d(e),o.clear(),s.clear(),g?.disconnect(),g?.observe(e??document.body,h)),m()};return m(),g=new MutationObserver(()=>{l!==null&&clearTimeout(l),l=setTimeout(()=>{l=null,_()},250)}),g.observe(f??document.body,h),{pending:s,isContainerDetached:()=>f!==null&&!f.isConnected,reconcile:_,destroy(){p.disconnect(),g.disconnect(),l!==null&&(clearTimeout(l),l=null),o.clear(),s.clear()}}};function B(e,t){if(typeof document>`u`||typeof IntersectionObserver>`u`)return N;let{selector:n}=t;if(!n)return N;let r=t.rootMargin??`-20% 0px -60% 0px`,i=t.scrollContainer,a=()=>i?.()??null,o=!1,s=!1,c=!1,l=()=>s||o,u=null,d=h(e),f=I(e,()=>{s=!0}),p=L(a),m=R(()=>{u?.()},150),g=z(n,r,a,()=>{m.schedule()},()=>{s||(s=!0,console.warn(`[real-router] scroll-spy: invalid selector "${n}". Disabling.`))},l);u=()=>{if(o||s){g.pending.clear();return}if(d.getSnapshot().isTransitioning||p.active)return;let t=F(g.pending.values());if(g.pending.clear(),!t)return;let n=t.target.id;if(!n)return;let r=e.getState();if(!r||n===P(r)?.hash)return;let i={hash:n,replace:!0,force:!0,hashChange:!0};c=!0,e.navigate(r.name,r.params,r.search,i).catch(()=>{}).finally(()=>{c=!1})};let _=e.subscribe(({route:e})=>{c||(g.isContainerDetached()&&g.reconcile(),P(e)?.hashChanged&&p.start())});return{destroy(){o=!0,_(),g.destroy(),m.destroy(),p.destroy(),f.destroy()}}}const V=Object.freeze({destroy:()=>{}});function H(e){if(typeof document>`u`||typeof document.startViewTransition!=`function`)return V;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;if(r=!0,t=null,e===null)n=null;else{let t=n;setTimeout(()=>{e(),n===t&&(n=null)},0)}});return{destroy:()=>{a(),o(),n?.skipTransition?.(),n=null,i()}}}function U(e,t){return e.routeName===t.routeName&&e.className===t.className&&e.activeClassName===t.activeClassName&&e.activeStrict===t.activeStrict&&e.ignoreQueryParams===t.ignoreQueryParams&&e.onClick===t.onClick&&e.target===t.target&&e.style===t.style&&e.children===t.children&&e.hash===t.hash&&r(e.routeParams,t.routeParams)&&r(e.routeSearch,t.routeSearch)&&r(e.to,t.to)&&r(e.routeOptions,t.routeOptions)}const W=d(({routeName:r,routeParams:l,routeSearch:d,to:f,routeOptions:h=e,className:g,activeClassName:_=`active`,activeStrict:v=!1,ignoreQueryParams:y=!0,hash:b,onClick:x,target:S,children:C,...w})=>{let T=o(),{name:E,params:D,search:O}=u(f,r??``,l,d),k=s(E,D,O,v,y,b),A=D??t,j=n(T,E,A,O,b),M=e=>{if(x){try{x(e)}catch(e){console.error(`[real-router] A <Link> onClick handler threw; navigation is unaffected.`,e)}if(e.defaultPrevented)return}!i(e.nativeEvent)||S===`_blank`||(e.preventDefault(),a(T,E,A,O,b,h).catch(()=>{}))},N=p(()=>c(k,_,g),[k,_,g]);return m(`a`,{...w,href:j,className:N,onClick:M,children:C})},U);W.displayName=`Link`;const G=({router:e,children:t,announceNavigation:n,scrollRestoration:r,scrollSpy:i,viewTransitions:a})=>{let o=n!==void 0&&n!==!1,s=typeof n==`object`?n:void 0,c=s?.prefix;f(()=>{if(!o)return;let t=b(e,s);return()=>{t.destroy()}},[e,o,c]);let u=r?.mode,d=r?.anchorScrolling,p=r?.behavior,h=r?.storageKey,g=r!==void 0;f(()=>{if(!g)return;let t=O(e,{mode:u,anchorScrolling:d,behavior:p,storageKey:h,scrollContainer:r.scrollContainer});return()=>{t.destroy()}},[e,g,u,d,p,h]);let _=i?.selector,v=i?.rootMargin,y=i!==void 0&&_!==void 0&&_!==``;return f(()=>{if(!y)return;let t=B(e,{selector:_,rootMargin:v,scrollContainer:i.scrollContainer});return()=>{t.destroy()}},[e,y,_,v]),f(()=>{if(!a)return;let t=H(e);return()=>{t.destroy()}},[e,a]),m(l,{router:e,children:t})};export{W as n,G as t};
2
- //# sourceMappingURL=RouterProvider-CmEutabZ.mjs.map