@real-router/react 0.28.21 → 0.28.23

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RouterProviderCore-CwOqpEA2.mjs","names":[],"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 Params,\n Router,\n State,\n} from \"@real-router/core\";\n\nexport function shouldNavigate(evt: MouseEvent): boolean {\n return (\n evt.button === 0 &&\n !evt.metaKey &&\n !evt.altKey &&\n !evt.ctrlKey &&\n !evt.shiftKey\n );\n}\n\n/**\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 options?: { hash?: string },\n) => string | undefined;\n\n/**\n * Builds an href for a `<Link>` element.\n *\n * - Prefers the URL plugin's `buildUrl` (browser-plugin, navigation-plugin,\n * hash-plugin) when present.\n * - Falls back to `router.buildPath` for runtimes without a URL plugin\n * (memory-plugin, console UIs, NativeScript). In that fallback the hash\n * is appended manually so the rendered href is still correct.\n * - The optional 4th argument is an options object so the contract stays\n * extensible. The `hash` option is a decoded fragment without leading \"#\";\n * `<Link hash=\"#section\">` is accepted defensively (leading \"#\" stripped).\n * Frozen API: previous 3-arg call sites continue to work unchanged.\n */\nexport function buildHref(\n router: Router,\n routeName: string,\n routeParams: Params,\n options?: { hash?: string },\n): string | undefined {\n try {\n const rawHash = options?.hash;\n let normHash: string | undefined;\n\n if (rawHash !== undefined) {\n normHash = rawHash.startsWith(\"#\") ? rawHash.slice(1) : rawHash;\n }\n\n const buildUrl = router.buildUrl as BuildUrlFn | undefined;\n\n if (buildUrl) {\n const url = buildUrl(\n routeName,\n routeParams,\n normHash === undefined ? undefined : { hash: normHash },\n );\n\n // Accept only non-empty strings. The BuildUrlFn type contract is\n // `string | undefined`, but defensive against:\n // - `\"\"` (empty string) → would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - `null` (type-contract violation) → would render `<a href={null}>`,\n // stringified to `\"null\"` in some renderers.\n // Either case falls through to the `router.buildPath` fallback below.\n if (typeof url === \"string\" && url.length > 0) {\n return url;\n }\n }\n\n const path = router.buildPath(routeName, routeParams);\n\n // Symmetric to the buildUrl guard above (#S1 audit, Invariant 12).\n // `router.buildPath` is typed `string`, but defends against:\n // - `\"\"` (empty string) — would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - non-string type-contract violations from custom path-matchers.\n // Both yield `undefined` (renderer drops the attribute) with a warning.\n if (typeof path !== \"string\" || path.length === 0) {\n console.error(\n `[real-router] Route \"${routeName}\" yielded an empty path. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n\n return normHash ? `${path}#${encodeFragmentInline(normHash)}` : path;\n } catch {\n console.error(\n `[real-router] Route \"${routeName}\" is not defined. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n}\n\n/**\n * `<Link>` click-handler navigation helper (#532).\n *\n * Wraps `router.navigate(name, params, opts)` with same-route different-hash\n * detection: when the consumer clicks a hash-bearing Link that targets the\n * current route with the same params but a different fragment, core's\n * SAME_STATES check would otherwise reject the navigation. The helper adds\n * `force: true` and `hashChange: true` automatically — subscribers can then\n * disambiguate via `state.context.url.hashChanged`.\n *\n * For pure programmatic same-route hash-only navigation, callers are\n * documented to pass `{ force: true }` themselves; the auto-bypass here is\n * a UX convenience for `<Link hash>` that all 6 framework adapters share.\n */\n/**\n * Local extended-options type. Adapters that depend only on `@real-router/core`\n * (without a URL plugin) do not see the `NavigationOptions` augmentation that\n * declares `hash` / `hashChange`. Casting to this widened type inside the\n * helper keeps shared/dom-utils self-contained — adapters do not need to\n * augment NavigationOptions themselves to consume `<Link hash>`.\n */\ntype HashAwareNavigationOptions = NavigationOptions & {\n hash?: string;\n hashChange?: boolean;\n};\n\nexport function navigateWithHash(\n router: Router,\n routeName: string,\n routeParams: Params,\n hash: string | undefined,\n extraOptions?: NavigationOptions,\n): Promise<State> {\n const opts: HashAwareNavigationOptions = { ...extraOptions };\n\n if (hash !== undefined) {\n opts.hash = hash;\n }\n\n const current = router.getState();\n\n if (\n current?.name === routeName &&\n shallowEqual(current.params, routeParams)\n ) {\n const currentHash =\n (current.context as { url?: { hash?: string } } | undefined)?.url?.hash ??\n \"\";\n const newHash = hash ?? currentHash;\n\n if (currentHash !== newHash) {\n opts.force = true;\n opts.hashChange = true;\n }\n }\n\n return router.navigate(routeName, routeParams, opts);\n}\n\n// Match-any-whitespace regex shared across calls. RegExp literals at\n// call-site recompile in some engines; lifting it avoids that microcost\n// for the slow-path branch.\nconst WHITESPACE_PROBE = /\\s/;\nconst WHITESPACE_SPLIT = /\\S+/g;\n\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 = Object.keys(prev);\n\n if (prevKeys.length !== Object.keys(next).length) {\n return false;\n }\n\n const prevRecord = prev as Record<string, unknown>;\n const nextRecord = next as Record<string, unknown>;\n\n for (const key of prevKeys) {\n // hasOwnProperty guard: without it, a key missing in `next` reads as\n // `undefined` and falsely matches `prev[key] === undefined`. Same shape\n // as React's shallowEqual (packages/shared/shallowEqual.js).\n if (\n !Object.prototype.hasOwnProperty.call(next, key) ||\n !Object.is(prevRecord[key], nextRecord[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function applyLinkA11y(element: HTMLElement | null | undefined): void {\n if (!element) {\n return;\n }\n\n // Cross-realm safety (audit-2026-05-17 §5 HIGH #4):\n // `instanceof HTMLAnchorElement` compares against the constructor from\n // the CURRENT realm. An element created in a different window (iframe\n // contentDocument, micro-frontend, embedded widget) fails the check\n // even when it IS a real anchor — the helper would then inject\n // role=\"link\" + tabindex=\"0\" on top of native anchor semantics,\n // breaking screen reader output (\"link link\") and focus order.\n //\n // tagName is realm-agnostic and is uppercase for HTML-namespaced\n // elements in any document. SVG `<a>` has lowercase tagName plus a\n // different prototype (SVGAElement) — skipping it here is wrong by\n // accident: SVG anchors don't have keyboard activation semantics the\n // helper would add. But they also don't reach this helper in\n // practice (router Link components emit HTML anchors). Lock the\n // uppercase compare to keep the contract narrow.\n const tag = element.tagName;\n\n if (tag === \"A\" || tag === \"BUTTON\") {\n return;\n }\n if (!element.hasAttribute(\"role\")) {\n element.setAttribute(\"role\", \"link\");\n }\n if (!element.hasAttribute(\"tabindex\")) {\n element.setAttribute(\"tabindex\", \"0\");\n }\n}\n","import { createActiveSource } from \"@real-router/sources\";\nimport { useMemo, useSyncExternalStore } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { Params } from \"@real-router/core\";\n\nexport function useIsActiveRoute(\n routeName: string,\n params?: Params,\n strict = false,\n ignoreQueryParams = true,\n hash?: string,\n): boolean {\n const router = useRouter();\n\n // 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 strict,\n ignoreQueryParams,\n hash,\n ),\n [router, routeName, params, strict, ignoreQueryParams, hash],\n );\n\n return useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n}\n","import { createDismissableError } from \"@real-router/sources\";\nimport {\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\n\nimport { useRouter } from \"../hooks/useRouter\";\n\nimport type { RouterError, State } from \"@real-router/core\";\nimport type { ReactElement, ReactNode } from \"react\";\n\nexport interface RouterErrorBoundaryProps {\n readonly children: ReactNode;\n readonly fallback: (error: RouterError, resetError: () => void) => ReactNode;\n readonly onError?: (\n error: RouterError,\n toRoute: State | null,\n fromRoute: State | null,\n ) => void;\n}\n\nexport function RouterErrorBoundary({\n children,\n fallback,\n onError,\n}: RouterErrorBoundaryProps): ReactElement {\n const router = useRouter();\n // Per-router cached in @real-router/sources — the WeakMap lookup is cheap,\n // but useMemo avoids it entirely on stable-router re-renders (the common\n // case for boundaries mounted in app shells).\n const store = useMemo(() => createDismissableError(router), [router]);\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n\n const onErrorRef = useRef(onError);\n\n // \"Latest ref\" pattern shared with useRouteEnter/useRouteExit: sync the\n // callback to the ref via useLayoutEffect (synchronous, post-render,\n // pre-paint) so the snapshot effect below reads the freshest callback\n // without listing `onError` as a dep — and StrictMode's double-effect\n // pass writes the same value twice harmlessly.\n useLayoutEffect(() => {\n onErrorRef.current = onError;\n });\n\n useEffect(() => {\n if (snapshot.error) {\n onErrorRef.current?.(\n snapshot.error,\n snapshot.toRoute,\n snapshot.fromRoute,\n );\n }\n // eslint-disable-next-line @eslint-react/exhaustive-deps -- onError tracked via ref, snapshot fields accessed inside callback\n }, [snapshot.version]);\n\n return (\n <>\n {children}\n {snapshot.error ? fallback(snapshot.error, snapshot.resetError) : null}\n </>\n );\n}\n","import { useContext } from \"react\";\n\nimport { NavigatorContext } from \"../context\";\n\nimport type { Navigator } from \"@real-router/core\";\n\nexport const useNavigator = (): Navigator => {\n const navigator = useContext(NavigatorContext);\n\n if (!navigator) {\n throw new Error(\"useNavigator must be used within a RouterProvider\");\n }\n\n return navigator;\n};\n","import { getPluginApi } from \"@real-router/core/api\";\nimport { getRouteUtils } from \"@real-router/route-utils\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { RouteUtils } from \"@real-router/route-utils\";\n\n/**\n * Returns a pre-computed {@link RouteUtils} instance for the current router.\n *\n * `getRouteUtils` is WeakMap-cached per `RouteTreeNode` inside\n * `@real-router/route-utils`, so the same router always returns the same\n * `RouteUtils` instance across renders — no local cache needed in the adapter.\n *\n * @returns RouteUtils instance with pre-computed chains and siblings\n *\n * @example\n * ```tsx\n * const utils = useRouteUtils();\n *\n * utils.getChain(\"users.profile\");\n * // → [\"users\", \"users.profile\"]\n *\n * utils.getSiblings(\"users\");\n * // → [\"admin\"]\n *\n * utils.isDescendantOf(\"users.profile\", \"users\");\n * // → true\n * ```\n */\nexport const useRouteUtils = (): RouteUtils => {\n const router = useRouter();\n\n return getRouteUtils(getPluginApi(router).getTree());\n};\n","import { getTransitionSource } from \"@real-router/sources\";\nimport { useSyncExternalStore } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { RouterTransitionSnapshot } from \"@real-router/sources\";\n\nexport function useRouterTransition(): RouterTransitionSnapshot {\n const router = useRouter();\n const store = getTransitionSource(router);\n\n return useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n}\n","import { getNavigator } from \"@real-router/core\";\nimport { createRouteSource, 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":"0kBAMA,MAAa,MAA0B,CACrC,IAAM,EAAS,EAAW,CAAa,EAEvC,GAAI,CAAC,EACH,MAAU,MAAM,gDAAgD,EAGlE,OAAO,CACT,ECNA,SAAgB,EAAa,EAAgC,CAC3D,IAAM,EAAS,EAAU,EAEnB,EAAQ,MACN,EAAsB,EAAQ,CAAQ,EAC5C,CAAC,EAAQ,CAAQ,CACnB,EAKM,EAAW,EACf,EAAM,UACN,EAAM,YACN,EAAM,WACR,EAGM,EAAY,EAAa,CAAM,EAErC,OAAO,OACgB,CACnB,YACA,MAAO,EAAS,MAChB,cAAe,EAAS,aAC1B,GACA,CAAC,EAAW,CAAQ,CACtB,CACF,CC7BA,SAAgB,EAAe,EAA0B,CACvD,OACE,EAAI,SAAW,GACf,CAAC,EAAI,SACL,CAAC,EAAI,QACL,CAAC,EAAI,SACL,CAAC,EAAI,QAET,CAmBA,SAAS,EAAqB,EAAyB,CACrD,OAAO,UAAU,CAAO,CAAC,CAAC,WAAW,IAAK,KAAK,CACjD,CAqBA,SAAgB,EACd,EACA,EACA,EACA,EACoB,CACpB,GAAI,CACF,IAAM,EAAU,GAAS,KACrB,EAEA,IAAY,IAAA,KACd,EAAW,EAAQ,WAAW,GAAG,EAAI,EAAQ,MAAM,CAAC,EAAI,GAG1D,IAAM,EAAW,EAAO,SAExB,GAAI,EAAU,CACZ,IAAM,EAAM,EACV,EACA,EACA,IAAa,IAAA,GAAY,IAAA,GAAY,CAAE,K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,EAE7C,GAAI,CAAC,EACH,MAAU,MAAM,mDAAmD,EAGrE,OAAO,CACT,ECgBa,MAGJ,EAAc,EAFN,EAEwB,CAAC,CAAC,CAAC,QAAQ,CAAC,EC1BrD,SAAgB,GAAgD,CAE9D,IAAM,EAAQ,EADC,EACwB,CAAC,EAExC,OAAO,EACL,EAAM,UACN,EAAM,YACN,EAAM,WACR,CACF,CCSA,MAAa,GAAmD,CAC9D,SACA,cACI,CACJ,IAAM,EAAY,MAAc,EAAa,CAAM,EAAG,CAAC,CAAM,CAAC,EAiBxD,EAAQ,MAAc,EAAkB,CAAM,EAAG,CAAC,CAAM,CAAC,EAO/D,MAAgB,CACd,EAAiB,CAAM,CACzB,EAAG,CAAC,CAAM,CAAC,EAKX,IAAM,EAAW,EACf,EAAM,UACN,EAAM,YACN,EAAM,WACR,EAEM,EAAoB,OACjB,CACL,YACA,MAAO,EAAS,MAChB,cAAe,EAAS,aAC1B,GACA,CAAC,EAAW,CAAQ,CACtB,EAEA,OACE,EAAC,EAAc,SAAf,CAAwB,MAAO,WAC7B,EAAC,EAAiB,SAAlB,CAA2B,MAAO,WAChC,EAAC,EAAa,SAAd,CAAuB,MAAO,EAC3B,UACoB,CAAA,CACE,CAAA,CACL,CAAA,CAE5B"}
@@ -1,2 +1,2 @@
1
- import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,f as n,i as r,n as i,p as a,r as o}from"./RouterProviderCore-BIxREXzN.mjs";import{n as s,t as c}from"./RouterProvider-CU-5Tr1j.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 _}from"react";import{UNKNOWN_ROUTE as v}from"@real-router/core";import{startsWithSegment as y}from"@real-router/route-utils";import{Fragment as b,jsx as x}from"react/jsx-runtime";function S(e){return null}S.displayName=`RouteView.Match`;function C(e){return null}C.displayName=`RouteView.Self`;function w(e){return null}w.displayName=`RouteView.NotFound`;const T=new Set([S,C,w]);function E(e,t,n){return t===``?!1:n?e===t:y(e,t)}function D(e,t){u.forEach(e,e=>{p(e)&&(T.has(e.type)?t.push(e):D(e.props.children,t))})}function O(e,t,n,r,i){let a=i===void 0?e:x(f,{fallback:i,children:e});return n?x(l,{mode:r,children:a},t):x(d,{children:a},t)}function k(e,t){return e.type===w?(t.notFoundFound||=(t.notFoundChildren=e.props.children,!0),!0):e.type===C?(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0):!1}function A(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&&E(t,u,s)?{rendered:O(a.children,u,c,`visible`,l),activatedName:u}:c&&r.has(u)?{rendered:O(a.children,u,c,`hidden`,l),activatedName:null}:{rendered:null,activatedName:null}}function j(e,t,n,r){if(r.selfFound&&t===n){e.push(O(r.selfChildren,`__route-view-self__`,!1,`visible`,r.selfFallback));return}t===v&&r.notFoundChildren!==null&&e.push(x(d,{children:r.notFoundChildren},`__route-view-not-found__`))}function M(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(k(s,i))continue;let e=A(s,t,n,r,a!==null);e.activatedName!==null&&(a=e.activatedName),e.rendered!==null&&o.push(e.rendered)}return a===null&&j(o,t,n,i),{rendered:o,activeMatchFound:a!==null,activatedName:a}}function N({nodeName:e,children:t}){let{route:r}=n(e),i=_(null);i.current??=new Set;let a=i.current,o=g(()=>{let e=[];return D(t,e),e},[t]),s=r?.name??null,{rendered:c,activatedName:l}=g(()=>{if(s===null)return{rendered:[],activatedName:null};let t=M(o,s,e,a);return{rendered:t.rendered,activatedName:t.activatedName}},[o,s,e,a]);return m(()=>{l!==null&&a.add(l)},[l,a]),c.length>0?x(b,{children:c}):null}N.displayName=`RouteView`;const P=Object.assign(N,{Match:S,Self:C,NotFound:w});function F(e,t){let n=a(),r=_(e),i=t?.skipSameRoute??!0;h(()=>{r.current=e}),m(()=>n.subscribeLeave(({route:e,nextRoute:t,signal:n})=>{if(!(i&&e.name===t.name)&&!n.aborted)return r.current({route:e,nextRoute:t,signal:n})}),[n,i])}function I(t,n){let{route:r,previousRoute:i}=e(),a=_(t),o=_(null),s=n?.skipSameRoute??!0;h(()=>{a.current=t}),m(()=>{r.transition.from&&(s&&r.transition.from===r.name||o.current!==r&&i&&(o.current=r,a.current({route:r,previousRoute:i})))},[r,i,s])}export{s as Link,P as RouteView,t as RouterErrorBoundary,c as RouterProvider,r as useNavigator,e as useRoute,I as useRouteEnter,F as useRouteExit,n as useRouteNode,o as useRouteUtils,a as useRouter,i as useRouterTransition};
1
+ import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,f as n,i as r,n as i,p as a,r as o}from"./RouterProviderCore-CwOqpEA2.mjs";import{n as s,t as c}from"./RouterProvider-CAYdWGdy.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 _}from"react";import{UNKNOWN_ROUTE as v}from"@real-router/core";import{startsWithSegment as y}from"@real-router/route-utils";import{Fragment as b,jsx as x}from"react/jsx-runtime";function S(e){return null}S.displayName=`RouteView.Match`;function C(e){return null}C.displayName=`RouteView.Self`;function w(e){return null}w.displayName=`RouteView.NotFound`;const T=new Set([S,C,w]);function E(e,t,n){return t===``?!1:n?e===t:y(e,t)}function D(e,t){u.forEach(e,e=>{p(e)&&(T.has(e.type)?t.push(e):D(e.props.children,t))})}function O(e,t,n,r,i){let a=i===void 0?e:x(f,{fallback:i,children:e});return n?x(l,{mode:r,children:a},t):x(d,{children:a},t)}function k(e,t){return e.type===w?(t.notFoundFound||=(t.notFoundChildren=e.props.children,!0),!0):e.type===C?(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0):!1}function A(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&&E(t,u,s)?{rendered:O(a.children,u,c,`visible`,l),activatedName:u}:c&&r.has(u)?{rendered:O(a.children,u,c,`hidden`,l),activatedName:null}:{rendered:null,activatedName:null}}function j(e,t,n,r){if(r.selfFound&&t===n){e.push(O(r.selfChildren,`__route-view-self__`,!1,`visible`,r.selfFallback));return}t===v&&r.notFoundChildren!==null&&e.push(x(d,{children:r.notFoundChildren},`__route-view-not-found__`))}function M(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(k(s,i))continue;let e=A(s,t,n,r,a!==null);e.activatedName!==null&&(a=e.activatedName),e.rendered!==null&&o.push(e.rendered)}return a===null&&j(o,t,n,i),{rendered:o,activeMatchFound:a!==null,activatedName:a}}function N({nodeName:e,children:t}){let{route:r}=n(e),i=_(null);i.current??=new Set;let a=i.current,o=g(()=>{let e=[];return D(t,e),e},[t]),s=r?.name??null,{rendered:c,activatedName:l}=g(()=>{if(s===null)return{rendered:[],activatedName:null};let t=M(o,s,e,a);return{rendered:t.rendered,activatedName:t.activatedName}},[o,s,e,a]);return m(()=>{l!==null&&a.add(l)},[l,a]),c.length>0?x(b,{children:c}):null}N.displayName=`RouteView`;const P=Object.assign(N,{Match:S,Self:C,NotFound:w});function F(e,t){let n=a(),r=_(e),i=t?.skipSameRoute??!0;h(()=>{r.current=e}),m(()=>n.subscribeLeave(({route:e,nextRoute:t,signal:n})=>{if(!(i&&e.name===t.name)&&!n.aborted)return r.current({route:e,nextRoute:t,signal:n})}),[n,i])}function I(t,n){let{route:r,previousRoute:i}=e(),a=_(t),o=_(null),s=n?.skipSameRoute??!0;h(()=>{a.current=t}),m(()=>{r.transition.from&&(s&&r.transition.from===r.name||o.current!==r&&i&&(o.current=r,a.current({route:r,previousRoute:i})))},[r,i,s])}export{s as Link,P as RouteView,t as RouterErrorBoundary,c as RouterProvider,r as useNavigator,e as useRoute,I as useRouteEnter,F as useRouteExit,n as useRouteNode,o as useRouteUtils,a as useRouter,i as useRouterTransition};
2
2
  //# sourceMappingURL=index.mjs.map
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,f as i,i as a,n as o,o as s,p as c,r as l,t as u,u as d}from"./RouterProviderCore-BIxREXzN.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&&d(e.routeParams,t.routeParams)&&d(e.routeOptions,t.routeOptions)}const y=f(({routeName:n,routeParams:r,routeOptions:i=e,activeStrict:a=!1,ignoreQueryParams:o=!0,color:l,activeColor:u,focusColor:d,inverse:f,activeInverse:v,focusInverse:y,id:b,autoFocus:x,onSelect:S,children:C})=>{let w=c(),{isFocused:T}=h({...b!==void 0&&{id:b},...x!==void 0&&{autoFocus:x}}),E=s(n,r,a,o),D=r??t;g((e,t)=>{if(t.return){try{S?.()}catch(e){console.error(`[real-router] InkLink onSelect threw; proceeding with navigation.`,e)}w.navigate(n,D,i).catch(()=>{})}},{isActive:T});let O=_(T,E,d,u,l),k=_(T,E,y,v,f),A={};return O!==void 0&&(A.color=O),k!==void 0&&(A.inverse=k),p(m,{...A,children:C})},v);y.displayName=`InkLink`;const b=({router:e,children:t})=>p(u,{router:e,children:t});export{y as InkLink,b as InkRouterProvider,r as RouterErrorBoundary,a as useNavigator,n as useRoute,i as useRouteNode,l as useRouteUtils,c as useRouter,o as useRouterTransition};
1
+ import{n as e,r as t,t as n}from"./useRoute-5MF3j-9P.mjs";import{a as r,f as i,i as a,n as o,o as s,p as c,r as l,t as u,u as d}from"./RouterProviderCore-CwOqpEA2.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&&d(e.routeParams,t.routeParams)&&d(e.routeOptions,t.routeOptions)}const y=f(({routeName:n,routeParams:r,routeOptions:i=e,activeStrict:a=!1,ignoreQueryParams:o=!0,color:l,activeColor:u,focusColor:d,inverse:f,activeInverse:v,focusInverse:y,id:b,autoFocus:x,onSelect:S,children:C})=>{let w=c(),{isFocused:T}=h({...b!==void 0&&{id:b},...x!==void 0&&{autoFocus:x}}),E=s(n,r,a,o),D=r??t;g((e,t)=>{if(t.return){try{S?.()}catch(e){console.error(`[real-router] InkLink onSelect threw; proceeding with navigation.`,e)}w.navigate(n,D,i).catch(()=>{})}},{isActive:T});let O=_(T,E,d,u,l),k=_(T,E,y,v,f),A={};return O!==void 0&&(A.color=O),k!==void 0&&(A.inverse=k),p(m,{...A,children:C})},v);y.displayName=`InkLink`;const b=({router:e,children:t})=>p(u,{router:e,children:t});export{y as InkLink,b as InkRouterProvider,r as RouterErrorBoundary,a as useNavigator,n as useRoute,i as useRouteNode,l as useRouteUtils,c as useRouter,o as useRouterTransition};
2
2
  //# sourceMappingURL=ink.mjs.map
@@ -1 +1 @@
1
- import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,f as n,i as r,n as i,p as a,r as o}from"./RouterProviderCore-BIxREXzN.mjs";import{n as s,t as c}from"./RouterProvider-CU-5Tr1j.mjs";export{s as Link,t as RouterErrorBoundary,c as RouterProvider,r as useNavigator,e as useRoute,n as useRouteNode,o as useRouteUtils,a as useRouter,i as useRouterTransition};
1
+ import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,f as n,i as r,n as i,p as a,r as o}from"./RouterProviderCore-CwOqpEA2.mjs";import{n as s,t as c}from"./RouterProvider-CAYdWGdy.mjs";export{s as Link,t as RouterErrorBoundary,c as RouterProvider,r as useNavigator,e as useRoute,n as useRouteNode,o as useRouteUtils,a as useRouter,i as useRouterTransition};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@real-router/react",
3
- "version": "0.28.21",
3
+ "version": "0.28.23",
4
4
  "type": "commonjs",
5
5
  "description": "React integration for Real-Router",
6
6
  "main": "./dist/cjs/index.js",
@@ -117,9 +117,9 @@
117
117
  "license": "MIT",
118
118
  "sideEffects": false,
119
119
  "dependencies": {
120
- "@real-router/core": "^0.74.8",
121
- "@real-router/route-utils": "^0.2.7",
122
- "@real-router/sources": "^0.11.0"
120
+ "@real-router/core": "^0.75.0",
121
+ "@real-router/route-utils": "^0.2.8",
122
+ "@real-router/sources": "^0.11.1"
123
123
  },
124
124
  "devDependencies": {
125
125
  "@testing-library/dom": "~10.4.1",
@@ -129,7 +129,7 @@
129
129
  "ink": "7.1.0",
130
130
  "ink-testing-library": "4.0.0",
131
131
  "vitest-react-profiler": "1.12.0",
132
- "@real-router/browser-plugin": "^0.18.17"
132
+ "@real-router/browser-plugin": "^0.18.18"
133
133
  },
134
134
  "peerDependencies": {
135
135
  "@types/react": ">=18.0.0",
@@ -1,2 +0,0 @@
1
- const e=require("./useRoute-D2vAzKWM.js");let t=require("react"),n=require("@real-router/core"),r=require("@real-router/route-utils"),i=require("react/jsx-runtime"),a=require("@real-router/sources"),o=require("@real-router/core/api");const s=()=>{let n=(0,t.useContext)(e.s);if(!n)throw Error(`useRouter must be used within a RouterProvider`);return n};function c(e){let r=s(),i=(0,t.useMemo)(()=>(0,a.createRouteNodeSource)(r,e),[r,e]),o=(0,t.useSyncExternalStore)(i.subscribe,i.getSnapshot,i.getSnapshot),c=(0,n.getNavigator)(r);return(0,t.useMemo)(()=>({navigator:c,route:o.route,previousRoute:o.previousRoute}),[c,o])}function l(e){return e.button===0&&!e.metaKey&&!e.altKey&&!e.ctrlKey&&!e.shiftKey}function u(e){return encodeURI(e).replaceAll(`#`,`%23`)}function d(e,t,n,r){try{let i=r?.hash,a;i!==void 0&&(a=i.startsWith(`#`)?i.slice(1):i);let o=e.buildUrl;if(o){let e=o(t,n,a===void 0?void 0:{hash:a});if(typeof e==`string`&&e.length>0)return e}let s=e.buildPath(t,n);if(typeof s!=`string`||s.length===0){console.error(`[real-router] Route "${t}" yielded an empty path. The element will render without an href attribute.`);return}return a?`${s}#${u(a)}`:s}catch{console.error(`[real-router] Route "${t}" is not defined. The element will render without an href attribute.`);return}}function f(e,t,n,r,i){let a={...i};r!==void 0&&(a.hash=r);let o=e.getState();if(o?.name===t&&_(o.params,n)){let e=o.context?.url?.hash??``;e!==(r??e)&&(a.force=!0,a.hashChange=!0)}return e.navigate(t,n,a)}const p=/\s/,m=/\S+/g;function h(e){return p.test(e)?e.match(m)??[]:[e]}function g(e,t,n){if(e&&t){let e=h(t);if(e.length===0)return n??void 0;if(!n)return e.join(` `);let r=h(n),i=new Set(r);for(let t of e)i.has(t)||(i.add(t),r.push(t));return r.join(` `)}return n??void 0}function _(e,t){if(Object.is(e,t))return!0;if(!e||!t)return!1;let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;let r=e,i=t;for(let e of n)if(!Object.prototype.hasOwnProperty.call(t,e)||!Object.is(r[e],i[e]))return!1;return!0}function v(e,n,r=!1,i=!0,o){let c=s(),l=(0,t.useMemo)(()=>{if(n===void 0&&!r&&i&&o===void 0){let t=(0,a.createActiveNameSelector)(c);return{subscribe:n=>t.subscribe(e,n),getSnapshot:()=>t.isActive(e)}}return(0,a.createActiveRouteSource)(c,e,n,{strict:r,ignoreQueryParams:i,...o!==void 0&&{hash:o}})},[c,e,n,r,i,o]);return(0,t.useSyncExternalStore)(l.subscribe,l.getSnapshot,l.getSnapshot)}function y({children:e,fallback:n,onError:r}){let o=s(),c=(0,t.useMemo)(()=>(0,a.createDismissableError)(o),[o]),l=(0,t.useSyncExternalStore)(c.subscribe,c.getSnapshot,c.getSnapshot),u=(0,t.useRef)(r);return(0,t.useLayoutEffect)(()=>{u.current=r}),(0,t.useEffect)(()=>{l.error&&u.current?.(l.error,l.toRoute,l.fromRoute)},[l.version]),(0,i.jsxs)(i.Fragment,{children:[e,l.error?n(l.error,l.resetError):null]})}const b=()=>{let n=(0,t.useContext)(e.a);if(!n)throw Error(`useNavigator must be used within a RouterProvider`);return n},x=()=>(0,r.getRouteUtils)((0,o.getPluginApi)(s()).getTree());function S(){let e=(0,a.getTransitionSource)(s());return(0,t.useSyncExternalStore)(e.subscribe,e.getSnapshot,e.getSnapshot)}const C=({router:r,children:o})=>{let s=(0,t.useMemo)(()=>(0,n.getNavigator)(r),[r]),c=(0,t.useMemo)(()=>(0,a.createRouteSource)(r),[r]);(0,t.useEffect)(()=>{(0,a.primeErrorSource)(r)},[r]);let l=(0,t.useSyncExternalStore)(c.subscribe,c.getSnapshot,c.getSnapshot),u=(0,t.useMemo)(()=>({navigator:s,route:l.route,previousRoute:l.previousRoute}),[s,l]);return(0,i.jsx)(e.s.Provider,{value:r,children:(0,i.jsx)(e.a.Provider,{value:s,children:(0,i.jsx)(e.o.Provider,{value:u,children:o})})})};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return y}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return x}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return _}});
2
- //# sourceMappingURL=RouterProviderCore-BDaTT1iW.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"RouterProviderCore-BDaTT1iW.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 Params,\n Router,\n State,\n} from \"@real-router/core\";\n\nexport function shouldNavigate(evt: MouseEvent): boolean {\n return (\n evt.button === 0 &&\n !evt.metaKey &&\n !evt.altKey &&\n !evt.ctrlKey &&\n !evt.shiftKey\n );\n}\n\n/**\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 options?: { hash?: string },\n) => string | undefined;\n\n/**\n * Builds an href for a `<Link>` element.\n *\n * - Prefers the URL plugin's `buildUrl` (browser-plugin, navigation-plugin,\n * hash-plugin) when present.\n * - Falls back to `router.buildPath` for runtimes without a URL plugin\n * (memory-plugin, console UIs, NativeScript). In that fallback the hash\n * is appended manually so the rendered href is still correct.\n * - The optional 4th argument is an options object so the contract stays\n * extensible. The `hash` option is a decoded fragment without leading \"#\";\n * `<Link hash=\"#section\">` is accepted defensively (leading \"#\" stripped).\n * Frozen API: previous 3-arg call sites continue to work unchanged.\n */\nexport function buildHref(\n router: Router,\n routeName: string,\n routeParams: Params,\n options?: { hash?: string },\n): string | undefined {\n try {\n const rawHash = options?.hash;\n let normHash: string | undefined;\n\n if (rawHash !== undefined) {\n normHash = rawHash.startsWith(\"#\") ? rawHash.slice(1) : rawHash;\n }\n\n const buildUrl = router.buildUrl as BuildUrlFn | undefined;\n\n if (buildUrl) {\n const url = buildUrl(\n routeName,\n routeParams,\n normHash === undefined ? undefined : { hash: normHash },\n );\n\n // Accept only non-empty strings. The BuildUrlFn type contract is\n // `string | undefined`, but defensive against:\n // - `\"\"` (empty string) → would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - `null` (type-contract violation) → would render `<a href={null}>`,\n // stringified to `\"null\"` in some renderers.\n // Either case falls through to the `router.buildPath` fallback below.\n if (typeof url === \"string\" && url.length > 0) {\n return url;\n }\n }\n\n const path = router.buildPath(routeName, routeParams);\n\n // Symmetric to the buildUrl guard above (#S1 audit, Invariant 12).\n // `router.buildPath` is typed `string`, but defends against:\n // - `\"\"` (empty string) — would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - non-string type-contract violations from custom path-matchers.\n // Both yield `undefined` (renderer drops the attribute) with a warning.\n if (typeof path !== \"string\" || path.length === 0) {\n console.error(\n `[real-router] Route \"${routeName}\" yielded an empty path. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n\n return normHash ? `${path}#${encodeFragmentInline(normHash)}` : path;\n } catch {\n console.error(\n `[real-router] Route \"${routeName}\" is not defined. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n}\n\n/**\n * `<Link>` click-handler navigation helper (#532).\n *\n * Wraps `router.navigate(name, params, opts)` with same-route different-hash\n * detection: when the consumer clicks a hash-bearing Link that targets the\n * current route with the same params but a different fragment, core's\n * SAME_STATES check would otherwise reject the navigation. The helper adds\n * `force: true` and `hashChange: true` automatically — subscribers can then\n * disambiguate via `state.context.url.hashChanged`.\n *\n * For pure programmatic same-route hash-only navigation, callers are\n * documented to pass `{ force: true }` themselves; the auto-bypass here is\n * a UX convenience for `<Link hash>` that all 6 framework adapters share.\n */\n/**\n * Local extended-options type. Adapters that depend only on `@real-router/core`\n * (without a URL plugin) do not see the `NavigationOptions` augmentation that\n * declares `hash` / `hashChange`. Casting to this widened type inside the\n * helper keeps shared/dom-utils self-contained — adapters do not need to\n * augment NavigationOptions themselves to consume `<Link hash>`.\n */\ntype HashAwareNavigationOptions = NavigationOptions & {\n hash?: string;\n hashChange?: boolean;\n};\n\nexport function navigateWithHash(\n router: Router,\n routeName: string,\n routeParams: Params,\n hash: string | undefined,\n extraOptions?: NavigationOptions,\n): Promise<State> {\n const opts: HashAwareNavigationOptions = { ...extraOptions };\n\n if (hash !== undefined) {\n opts.hash = hash;\n }\n\n const current = router.getState();\n\n if (\n current?.name === routeName &&\n shallowEqual(current.params, routeParams)\n ) {\n const currentHash =\n (current.context as { url?: { hash?: string } } | undefined)?.url?.hash ??\n \"\";\n const newHash = hash ?? currentHash;\n\n if (currentHash !== newHash) {\n opts.force = true;\n opts.hashChange = true;\n }\n }\n\n return router.navigate(routeName, routeParams, opts);\n}\n\n// Match-any-whitespace regex shared across calls. RegExp literals at\n// call-site recompile in some engines; lifting it avoids that microcost\n// for the slow-path branch.\nconst WHITESPACE_PROBE = /\\s/;\nconst WHITESPACE_SPLIT = /\\S+/g;\n\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 = Object.keys(prev);\n\n if (prevKeys.length !== Object.keys(next).length) {\n return false;\n }\n\n const prevRecord = prev as Record<string, unknown>;\n const nextRecord = next as Record<string, unknown>;\n\n for (const key of prevKeys) {\n // hasOwnProperty guard: without it, a key missing in `next` reads as\n // `undefined` and falsely matches `prev[key] === undefined`. Same shape\n // as React's shallowEqual (packages/shared/shallowEqual.js).\n if (\n !Object.prototype.hasOwnProperty.call(next, key) ||\n !Object.is(prevRecord[key], nextRecord[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function applyLinkA11y(element: HTMLElement | null | undefined): void {\n if (!element) {\n return;\n }\n\n // Cross-realm safety (audit-2026-05-17 §5 HIGH #4):\n // `instanceof HTMLAnchorElement` compares against the constructor from\n // the CURRENT realm. An element created in a different window (iframe\n // contentDocument, micro-frontend, embedded widget) fails the check\n // even when it IS a real anchor — the helper would then inject\n // role=\"link\" + tabindex=\"0\" on top of native anchor semantics,\n // breaking screen reader output (\"link link\") and focus order.\n //\n // tagName is realm-agnostic and is uppercase for HTML-namespaced\n // elements in any document. SVG `<a>` has lowercase tagName plus a\n // different prototype (SVGAElement) — skipping it here is wrong by\n // accident: SVG anchors don't have keyboard activation semantics the\n // helper would add. But they also don't reach this helper in\n // practice (router Link components emit HTML anchors). Lock the\n // uppercase compare to keep the contract narrow.\n const tag = element.tagName;\n\n if (tag === \"A\" || tag === \"BUTTON\") {\n return;\n }\n if (!element.hasAttribute(\"role\")) {\n element.setAttribute(\"role\", \"link\");\n }\n if (!element.hasAttribute(\"tabindex\")) {\n element.setAttribute(\"tabindex\", \"0\");\n }\n}\n","import {\n createActiveNameSelector,\n createActiveRouteSource,\n} from \"@real-router/sources\";\nimport { useMemo, useSyncExternalStore } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { Params } from \"@real-router/core\";\n\nexport function useIsActiveRoute(\n routeName: string,\n params?: Params,\n strict = false,\n ignoreQueryParams = true,\n hash?: string,\n): boolean {\n const router = useRouter();\n\n // Fast path (#1248) — the default-options active check: no custom `params`,\n // non-strict, query params ignored, no `hash`. Resolve through the per-router\n // shared `createActiveNameSelector` — ONE `router.subscribe` handle serves any\n // number of distinct-`routeName` links — instead of a per-instance\n // `createActiveRouteSource` (a `BaseSource` AND its own router subscription for\n // every distinct name). Direct port of the svelte (#1101) / angular (#1104)\n // fast paths; the selector's `isActive` is exactly non-strict, query-ignoring,\n // name-only matching, identical to the default-options `createActiveRouteSource`.\n // Any deviation falls to the slow path below, whose canonical-args cache handles\n // the full surface (custom params, strict, `ignoreQueryParams: false`,\n // hash-aware #532).\n //\n // The `useMemo` wrap skips the branch + `canonicalJson(params)` + cache lookup\n // on every render when all primitive deps and the `params` reference are stable.\n // exactOptionalPropertyTypes forbids `{ hash: undefined }` literally, so we\n // conditionally spread the key only when the caller passed a value.\n const store = useMemo(() => {\n if (\n params === undefined &&\n !strict &&\n ignoreQueryParams &&\n hash === undefined\n ) {\n const selector = createActiveNameSelector(router);\n\n return {\n subscribe: (onChange: () => void) =>\n selector.subscribe(routeName, onChange),\n getSnapshot: () => selector.isActive(routeName),\n };\n }\n\n return createActiveRouteSource(router, routeName, params, {\n strict,\n ignoreQueryParams,\n ...(hash !== undefined && { hash }),\n });\n }, [router, routeName, params, strict, ignoreQueryParams, hash]);\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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outEffect as a,useMemo as o,useRef as s,useSyncExternalStore as c}from"react";import{getNavigator as l}from"@real-router/core";import{getRouteUtils as u}from"@real-router/route-utils";import{Fragment as d,jsx as f,jsxs as p}from"react/jsx-runtime";import{createActiveNameSelector as m,createActiveRouteSource as h,createDismissableError as g,createRouteNodeSource as _,createRouteSource as v,getTransitionSource as y,primeErrorSource as b}from"@real-router/sources";import{getPluginApi as x}from"@real-router/core/api";const S=()=>{let e=r(n);if(!e)throw Error(`useRouter must be used within a RouterProvider`);return e};function C(e){let t=S(),n=o(()=>_(t,e),[t,e]),r=c(n.subscribe,n.getSnapshot,n.getSnapshot),i=l(t);return o(()=>({navigator:i,route:r.route,previousRoute:r.previousRoute}),[i,r])}function w(e){return e.button===0&&!e.metaKey&&!e.altKey&&!e.ctrlKey&&!e.shiftKey}function T(e){return encodeURI(e).replaceAll(`#`,`%23`)}function E(e,t,n,r){try{let i=r?.hash,a;i!==void 0&&(a=i.startsWith(`#`)?i.slice(1):i);let o=e.buildUrl;if(o){let e=o(t,n,a===void 0?void 0:{hash:a});if(typeof e==`string`&&e.length>0)return e}let s=e.buildPath(t,n);if(typeof s!=`string`||s.length===0){console.error(`[real-router] Route "${t}" yielded an empty path. The element will render without an href attribute.`);return}return a?`${s}#${T(a)}`:s}catch{console.error(`[real-router] Route "${t}" is not defined. The element will render without an href attribute.`);return}}function D(e,t,n,r,i){let a={...i};r!==void 0&&(a.hash=r);let o=e.getState();if(o?.name===t&&M(o.params,n)){let e=o.context?.url?.hash??``;e!==(r??e)&&(a.force=!0,a.hashChange=!0)}return e.navigate(t,n,a)}const O=/\s/,k=/\S+/g;function A(e){return O.test(e)?e.match(k)??[]:[e]}function j(e,t,n){if(e&&t){let e=A(t);if(e.length===0)return n??void 0;if(!n)return e.join(` `);let r=A(n),i=new Set(r);for(let t of e)i.has(t)||(i.add(t),r.push(t));return r.join(` `)}return n??void 0}function M(e,t){if(Object.is(e,t))return!0;if(!e||!t)return!1;let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;let r=e,i=t;for(let e of n)if(!Object.prototype.hasOwnProperty.call(t,e)||!Object.is(r[e],i[e]))return!1;return!0}function N(e,t,n=!1,r=!0,i){let a=S(),s=o(()=>{if(t===void 0&&!n&&r&&i===void 0){let t=m(a);return{subscribe:n=>t.subscribe(e,n),getSnapshot:()=>t.isActive(e)}}return h(a,e,t,{strict:n,ignoreQueryParams:r,...i!==void 0&&{hash:i}})},[a,e,t,n,r,i]);return c(s.subscribe,s.getSnapshot,s.getSnapshot)}function P({children:e,fallback:t,onError:n}){let r=S(),l=o(()=>g(r),[r]),u=c(l.subscribe,l.getSnapshot,l.getSnapshot),f=s(n);return a(()=>{f.current=n}),i(()=>{u.error&&f.current?.(u.error,u.toRoute,u.fromRoute)},[u.version]),p(d,{children:[e,u.error?t(u.error,u.resetError):null]})}const F=()=>{let t=r(e);if(!t)throw Error(`useNavigator must be used within a RouterProvider`);return t},I=()=>u(x(S()).getTree());function L(){let e=y(S());return c(e.subscribe,e.getSnapshot,e.getSnapshot)}const R=({router:r,children:a})=>{let s=o(()=>l(r),[r]),u=o(()=>v(r),[r]);i(()=>{b(r)},[r]);let d=c(u.subscribe,u.getSnapshot,u.getSnapshot),p=o(()=>({navigator:s,route:d.route,previousRoute:d.previousRoute}),[s,d]);return f(n.Provider,{value:r,children:f(e.Provider,{value:s,children:f(t.Provider,{value:p,children:a})})})};export{P as a,E as c,w as d,C as f,F as i,D as l,L as n,N as o,S as p,I as r,j as s,R as t,M as u};
2
- //# sourceMappingURL=RouterProviderCore-BIxREXzN.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"RouterProviderCore-BIxREXzN.mjs","names":[],"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 Params,\n Router,\n State,\n} from \"@real-router/core\";\n\nexport function shouldNavigate(evt: MouseEvent): boolean {\n return (\n evt.button === 0 &&\n !evt.metaKey &&\n !evt.altKey &&\n !evt.ctrlKey &&\n !evt.shiftKey\n );\n}\n\n/**\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 options?: { hash?: string },\n) => string | undefined;\n\n/**\n * Builds an href for a `<Link>` element.\n *\n * - Prefers the URL plugin's `buildUrl` (browser-plugin, navigation-plugin,\n * hash-plugin) when present.\n * - Falls back to `router.buildPath` for runtimes without a URL plugin\n * (memory-plugin, console UIs, NativeScript). In that fallback the hash\n * is appended manually so the rendered href is still correct.\n * - The optional 4th argument is an options object so the contract stays\n * extensible. The `hash` option is a decoded fragment without leading \"#\";\n * `<Link hash=\"#section\">` is accepted defensively (leading \"#\" stripped).\n * Frozen API: previous 3-arg call sites continue to work unchanged.\n */\nexport function buildHref(\n router: Router,\n routeName: string,\n routeParams: Params,\n options?: { hash?: string },\n): string | undefined {\n try {\n const rawHash = options?.hash;\n let normHash: string | undefined;\n\n if (rawHash !== undefined) {\n normHash = rawHash.startsWith(\"#\") ? rawHash.slice(1) : rawHash;\n }\n\n const buildUrl = router.buildUrl as BuildUrlFn | undefined;\n\n if (buildUrl) {\n const url = buildUrl(\n routeName,\n routeParams,\n normHash === undefined ? undefined : { hash: normHash },\n );\n\n // Accept only non-empty strings. The BuildUrlFn type contract is\n // `string | undefined`, but defensive against:\n // - `\"\"` (empty string) → would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - `null` (type-contract violation) → would render `<a href={null}>`,\n // stringified to `\"null\"` in some renderers.\n // Either case falls through to the `router.buildPath` fallback below.\n if (typeof url === \"string\" && url.length > 0) {\n return url;\n }\n }\n\n const path = router.buildPath(routeName, routeParams);\n\n // Symmetric to the buildUrl guard above (#S1 audit, Invariant 12).\n // `router.buildPath` is typed `string`, but defends against:\n // - `\"\"` (empty string) — would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - non-string type-contract violations from custom path-matchers.\n // Both yield `undefined` (renderer drops the attribute) with a warning.\n if (typeof path !== \"string\" || path.length === 0) {\n console.error(\n `[real-router] Route \"${routeName}\" yielded an empty path. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n\n return normHash ? `${path}#${encodeFragmentInline(normHash)}` : path;\n } catch {\n console.error(\n `[real-router] Route \"${routeName}\" is not defined. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n}\n\n/**\n * `<Link>` click-handler navigation helper (#532).\n *\n * Wraps `router.navigate(name, params, opts)` with same-route different-hash\n * detection: when the consumer clicks a hash-bearing Link that targets the\n * current route with the same params but a different fragment, core's\n * SAME_STATES check would otherwise reject the navigation. The helper adds\n * `force: true` and `hashChange: true` automatically — subscribers can then\n * disambiguate via `state.context.url.hashChanged`.\n *\n * For pure programmatic same-route hash-only navigation, callers are\n * documented to pass `{ force: true }` themselves; the auto-bypass here is\n * a UX convenience for `<Link hash>` that all 6 framework adapters share.\n */\n/**\n * Local extended-options type. Adapters that depend only on `@real-router/core`\n * (without a URL plugin) do not see the `NavigationOptions` augmentation that\n * declares `hash` / `hashChange`. Casting to this widened type inside the\n * helper keeps shared/dom-utils self-contained — adapters do not need to\n * augment NavigationOptions themselves to consume `<Link hash>`.\n */\ntype HashAwareNavigationOptions = NavigationOptions & {\n hash?: string;\n hashChange?: boolean;\n};\n\nexport function navigateWithHash(\n router: Router,\n routeName: string,\n routeParams: Params,\n hash: string | undefined,\n extraOptions?: NavigationOptions,\n): Promise<State> {\n const opts: HashAwareNavigationOptions = { ...extraOptions };\n\n if (hash !== undefined) {\n opts.hash = hash;\n }\n\n const current = router.getState();\n\n if (\n current?.name === routeName &&\n shallowEqual(current.params, routeParams)\n ) {\n const currentHash =\n (current.context as { url?: { hash?: string } } | undefined)?.url?.hash ??\n \"\";\n const newHash = hash ?? currentHash;\n\n if (currentHash !== newHash) {\n opts.force = true;\n opts.hashChange = true;\n }\n }\n\n return router.navigate(routeName, routeParams, opts);\n}\n\n// Match-any-whitespace regex shared across calls. RegExp literals at\n// call-site recompile in some engines; lifting it avoids that microcost\n// for the slow-path branch.\nconst WHITESPACE_PROBE = /\\s/;\nconst WHITESPACE_SPLIT = /\\S+/g;\n\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 = Object.keys(prev);\n\n if (prevKeys.length !== Object.keys(next).length) {\n return false;\n }\n\n const prevRecord = prev as Record<string, unknown>;\n const nextRecord = next as Record<string, unknown>;\n\n for (const key of prevKeys) {\n // hasOwnProperty guard: without it, a key missing in `next` reads as\n // `undefined` and falsely matches `prev[key] === undefined`. Same shape\n // as React's shallowEqual (packages/shared/shallowEqual.js).\n if (\n !Object.prototype.hasOwnProperty.call(next, key) ||\n !Object.is(prevRecord[key], nextRecord[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function applyLinkA11y(element: HTMLElement | null | undefined): void {\n if (!element) {\n return;\n }\n\n // Cross-realm safety (audit-2026-05-17 §5 HIGH #4):\n // `instanceof HTMLAnchorElement` compares against the constructor from\n // the CURRENT realm. An element created in a different window (iframe\n // contentDocument, micro-frontend, embedded widget) fails the check\n // even when it IS a real anchor — the helper would then inject\n // role=\"link\" + tabindex=\"0\" on top of native anchor semantics,\n // breaking screen reader output (\"link link\") and focus order.\n //\n // tagName is realm-agnostic and is uppercase for HTML-namespaced\n // elements in any document. SVG `<a>` has lowercase tagName plus a\n // different prototype (SVGAElement) — skipping it here is wrong by\n // accident: SVG anchors don't have keyboard activation semantics the\n // helper would add. But they also don't reach this helper in\n // practice (router Link components emit HTML anchors). Lock the\n // uppercase compare to keep the contract narrow.\n const tag = element.tagName;\n\n if (tag === \"A\" || tag === \"BUTTON\") {\n return;\n }\n if (!element.hasAttribute(\"role\")) {\n element.setAttribute(\"role\", \"link\");\n }\n if (!element.hasAttribute(\"tabindex\")) {\n element.setAttribute(\"tabindex\", \"0\");\n }\n}\n","import {\n createActiveNameSelector,\n createActiveRouteSource,\n} from \"@real-router/sources\";\nimport { useMemo, useSyncExternalStore } from \"react\";\n\nimport { useRouter } from \"./useRouter\";\n\nimport type { Params } from \"@real-router/core\";\n\nexport function useIsActiveRoute(\n routeName: string,\n params?: Params,\n strict = false,\n ignoreQueryParams = true,\n hash?: string,\n): boolean {\n const router = useRouter();\n\n // Fast path (#1248) — the default-options active check: no custom `params`,\n // non-strict, query params ignored, no `hash`. Resolve through the per-router\n // shared `createActiveNameSelector` — ONE `router.subscribe` handle serves any\n // number of distinct-`routeName` links — instead of a per-instance\n // `createActiveRouteSource` (a `BaseSource` AND its own router subscription for\n // every distinct name). Direct port of the svelte (#1101) / angular (#1104)\n // fast paths; the selector's `isActive` is exactly non-strict, query-ignoring,\n // name-only matching, identical to the default-options `createActiveRouteSource`.\n // Any deviation falls to the slow path below, whose canonical-args cache handles\n // the full surface (custom params, strict, `ignoreQueryParams: false`,\n // hash-aware #532).\n //\n // The `useMemo` wrap skips the branch + `canonicalJson(params)` + cache lookup\n // on every render when all primitive deps and the `params` reference are stable.\n // exactOptionalPropertyTypes forbids `{ hash: undefined }` literally, so we\n // conditionally spread the key only when the caller passed a value.\n const store = useMemo(() => {\n if (\n params === undefined &&\n !strict &&\n ignoreQueryParams &&\n hash === undefined\n ) {\n const selector = createActiveNameSelector(router);\n\n return {\n subscribe: (onChange: () => void) =>\n selector.subscribe(routeName, onChange),\n getSnapshot: () => selector.isActive(routeName),\n };\n }\n\n return createActiveRouteSource(router, routeName, params, {\n strict,\n ignoreQueryParams,\n ...(hash !== undefined && { hash }),\n });\n }, [router, routeName, params, strict, ignoreQueryParams, hash]);\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":"6mBAMA,MAAa,MAA0B,CACrC,IAAM,EAAS,EAAW,CAAa,EAEvC,GAAI,CAAC,EACH,MAAU,MAAM,gDAAgD,EAGlE,OAAO,CACT,ECNA,SAAgB,EAAa,EAAgC,CAC3D,IAAM,EAAS,EAAU,EAEnB,EAAQ,MACN,EAAsB,EAAQ,CAAQ,EAC5C,CAAC,EAAQ,CAAQ,CACnB,EAKM,EAAW,EACf,EAAM,UACN,EAAM,YACN,EAAM,WACR,EAGM,EAAY,EAAa,CAAM,EAErC,OAAO,OACgB,CACnB,YACA,MAAO,EAAS,MAChB,cAAe,EAAS,aAC1B,GACA,CAAC,EAAW,CAAQ,CACtB,CACF,CC7BA,SAAgB,EAAe,EAA0B,CACvD,OACE,EAAI,SAAW,GACf,CAAC,EAAI,SACL,CAAC,EAAI,QACL,CAAC,EAAI,SACL,CAAC,EAAI,QAET,CAmBA,SAAS,EAAqB,EAAyB,CACrD,OAAO,UAAU,CAAO,CAAC,CAAC,WAAW,IAAK,KAAK,CACjD,CAqBA,SAAgB,EACd,EACA,EACA,EACA,EACoB,CACpB,GAAI,CACF,IAAM,EAAU,GAAS,KACrB,EAEA,IAAY,IAAA,KACd,EAAW,EAAQ,WAAW,GAAG,EAAI,EAAQ,MAAM,CAAC,EAAI,GAG1D,IAAM,EAAW,EAAO,SAExB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