@real-router/react 0.37.0 → 0.37.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"RouterProviderCore-BQA-I4NQ.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 { getPluginApi } from \"@real-router/core/api\";\nimport { putField } from \"@real-router/core/utils\";\n\nimport 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 — a shim evaluated ahead of core still wins\n * (#1798), which is the doctrine's own caveat and travels with it.\n */\nconst objectKeys = Object.keys;\n\n/**\n * The brand `packages/core/src/internals.ts` puts on every router it registers,\n * RE-DECLARED rather than imported (#2294).\n *\n * ⚑ `Symbol.for` makes the two the same symbol, so **the STRING is the\n * contract** — change it in one place and this warning silently stops firing.\n * The same shape core already uses for `CONFIG_FAULT`, declared twice across a\n * boundary it cannot import over, and pinned the same way: the guard is\n * `foreign-router-href-2294.test.ts`, whose cells fail on exactly that drift.\n */\nconst ROUTER_BRAND = Symbol.for(\"real-router.router\");\n\n/**\n * Is this a real router that core cannot read — as opposed to the `Router`-SHAPED\n * double this helper accepts by contract?\n *\n * ⚠ Read defensively: the argument is the caller's object and may be a `Proxy`\n * whose `get` trap throws. A diagnostic that throws would change where the error\n * comes FROM, which is the #1572 class, so a throwing read means \"cannot tell\".\n */\nfunction isUnreadableRouter(candidate: unknown): boolean {\n try {\n return (\n (candidate as Record<symbol, unknown> | null | undefined)?.[\n ROUTER_BRAND\n ] === true\n );\n } catch {\n return false;\n }\n}\n\n/**\n * The registry lookup, ALONE — and standing alone is what makes the warning\n * correct (#2294).\n *\n * ⚑ Inside the resolve-and-print `try` this could not be told apart from a\n * `forwardState` that threw for a reason the arm handles deliberately. The\n * channel guard (#1572) is exactly that, and it fires on a router that IS\n * registered and IS branded — so a check made there would report duplicated core\n * on a perfectly healthy one.\n */\nfunction readPluginApi(\n router: Router,\n routeName: string,\n): ReturnType<typeof getPluginApi> | undefined {\n try {\n return getPluginApi(router);\n } catch {\n if (isUnreadableRouter(router)) {\n console.error(\n `[real-router] Route \"${routeName}\" rendered its LITERAL path: this IS a router, ` +\n \"but not one this copy of @real-router/core built, so `forwardTo` was not resolved. \" +\n \"It is either wrapped in a Proxy (Vue `reactive()` / Pinia — store it with `markRaw`), \" +\n \"or your dependency tree holds two copies of @real-router/core — dedupe it to one.\",\n );\n }\n\n return undefined;\n }\n}\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 * Does an anchor's `target` send this navigation somewhere the router cannot\n * follow? (#1834)\n *\n * `target` names the browsing context the author wants the URL loaded into.\n * Three values are the router's — absent, empty, `_self` — and every other one\n * goes to the browser, the only thing that can resolve a context name.\n * Intercepting instead is how a `<Link target=\"_blank\">` ends up reloading the\n * same tab rather than opening a new one. React Router's\n * `shouldProcessLinkClick` and TanStack Router's `handleClick` split the same\n * way; neither reproduces browsing contexts inside the router, and neither does\n * this.\n *\n * ⚠ The split is by SPELLING, not by where the value resolves to, and three\n * spellings resolve back to this context anyway: `_parent` and `_top` fall back\n * to `_self` in a document with no ancestor, and `_SELF` matches `_self`\n * ASCII-case-insensitively (MDN, `<a>` § target). All three are handed to the\n * browser, which reaches the right destination by a full page load instead of a\n * transition. Resolving them properly means reproducing frame ancestry and\n * keyword folding here; both reference routers decline, and the cost is a page\n * load rather than a wrong destination.\n *\n * ⚠ Ask this only about an `<a>`. On a `<button v-link>` or a `<div use:link>`\n * the attribute is inert markup the browser will not act on, so deferring there\n * would leave the activation unhandled by anyone. Callers that cannot assume an\n * anchor ask {@link anchorTargetsAnotherContext} instead, which narrows first;\n * `target-predicate-authority-1834` owns which call site is in which set.\n */\nexport function targetsAnotherContext(\n target: string | null | undefined,\n): boolean {\n return Boolean(target) && target !== \"_self\";\n}\n\n/**\n * The same question, asked about an ELEMENT — for the `use:link` / `v-link`\n * forms, which attach to whatever element the consumer wrote and so cannot\n * assume an anchor (#1834). The `<Link>` components pass a value instead\n * (they render the anchor), and so does Angular's directive (its selector is\n * `a[realLink]`).\n *\n * ⚠ `tagName`, never `instanceof HTMLAnchorElement`, for the reason\n * `applyLinkA11y` sets out below: the constructor belongs to the realm this\n * module loaded in, so a real anchor from an iframe `contentDocument` or a\n * micro-frontend fails the check. Failing it HERE re-intercepts the very\n * `target=\"_blank\"` click this predicate exists to leave alone.\n *\n * Anything that is not an HTML anchor answers `false`: `target` is\n * anchor-specific markup the browser will not act on, so a `<button use:link>`\n * or a `<div v-link>` carrying one must still navigate in-app.\n */\nexport function anchorTargetsAnotherContext(\n element: Element | null | undefined,\n): boolean {\n if (element?.tagName !== \"A\") {\n return false;\n }\n\n return targetsAnotherContext(element.getAttribute(\"target\"));\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 the core's resolving door 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 // ⚑ RESOLVE, then print (#2250). An href is a promise about where the click\n // lands, and the click resolves `forwardTo`. `router.buildPath` alone is\n // class LITERAL by record and answers about the route it was NAMED —\n // INVARIANTS #8 keeps that so a plugin can build a state for an alias\n // without being teleported off it — so the chain is resolved FIRST and the\n // printer prints the target. The door choice belongs here rather than one\n // layer down.\n //\n // ⚠ **The `??` is not reached by a name the table does not hold, and the\n // claim that it was described a door this arm stopped calling.** That read\n // `buildNavigationState`, which answers `undefined` for an unknown route;\n // since #2265 the resolving door is `forwardState`, which ANSWERS for one\n // (measured — it does not validate the name), leaving the printer to throw.\n // `packages/react/INVARIANTS.md` row 3 still holds — `Both throw →\n // undefined + console.error` — but it is reached by both printers throwing,\n // not by a `undefined` the `??` absorbs. What the `??` IS load-bearing for\n // is the two cases below.\n //\n // ⚠ **The fallback is also where the channel guard lands (#1572).** A route's\n // declared query name handed in the PATH bag makes the class-① door throw\n // where `buildPath` answers, so the `??` prints the literal path — the same\n // href this arm has always rendered. Under a URL plugin the guard is not\n // swallowed: `router.buildUrl` throws and the outer `catch` drops the href.\n //\n // ⚠ **The inner `try` keeps this helper's STRUCTURAL contract.** `buildHref`\n // is handed a `Router`-shaped object, not necessarily a registered one, and\n // `getPluginApi` resolves it through `getInternals` — a WeakMap keyed on\n // identity, which REFUSES a test double or a `Proxy` wrapper. Such a router\n // keeps the literal path; the stub-router CONTROL in\n // `packages/react/tests/functional/dom-utils/forwarding-link-href-2250.test.ts`\n // owns that.\n let resolved: string | undefined;\n const api = readPluginApi(router, routeName);\n\n try {\n // ⚠ **`forwardState`, not `buildNavigationState`.** Both resolve the whole\n // chain, and the href is identical — but the committing door opts into\n // `reportUndeclaredParamKey`, and an href COMMITS NOTHING. That diagnostic\n // is for a state you are about to persist, which is why `canNavigateTo`\n // is silent despite sharing `navigate`'s form (#2248 / #1581).\n // ⚑ **`buildPathResolved`, not `router.buildPath` — ONE href is ONE pass\n // of the chain (#2260).** The facade's printer runs the `forwardState`\n // seam a door lower (#2087), which is right for a caller holding a raw\n // intent and a SECOND pass for this one, which just resolved. Counted,\n // because nothing in either door's source says \"twice\": the second pass\n // is what two individually-correct doors compose to.\n //\n // ⚠ A plugin author registers one interceptor and has no reason to expect\n // two invocations per href — a stateful one double-counts. Cost is the\n // lesser half: +1333 ns per href with `search-schema` +\n // `persistent-params` installed, per `<Link>` per render.\n //\n // ⚠ `api?.` is a TYPE gate, not a runtime guard, and naming it so keeps it\n // from being read as one: calling `forwardState` on `undefined` throws\n // into the same `catch` for the same outcome, so a mutant dropping the\n // check is EQUIVALENT. What it buys is that TypeScript can see the call is\n // safe below a lookup that may have failed (#2294).\n const forwarded = api?.forwardState(routeName, routeParams, routeSearch);\n\n resolved =\n forwarded &&\n api?.buildPathResolved(\n forwarded.name,\n forwarded.params,\n forwarded.search,\n );\n } catch {\n resolved = undefined;\n }\n\n const path =\n resolved ?? 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 * 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\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 */\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 // ⚑ `putField`, not `opts.hash = …` (#2141 / #1852). The spread above produces\n // no own key for this slot unless the caller's extra options carried one, so\n // a plain assignment walks the prototype: an ambient accessor an application\n // or a polyfill put on `Object.prototype` takes the value and the navigation\n // runs without the fragment it was asked for, or — getter-only — throws.\n //\n // ⚠ This dir is shared, so one unguarded write here multiplies by its whole\n // consumer set — `packages/react` is the coverage and authority owner\n // (#1838) and owns that count. Its scan classifies COMPUTED-key writes only,\n // which is why a literal slot like this one sat outside it.\n putField(opts as unknown as Record<string, unknown>, \"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 an\n// `if (!value) return []` guard here would be unreachable (#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 the adapters built on it resolve active state identically —\n // Solid is the exception, its `Link` carrying its own copy of the decision\n // (#1248 landed the fast path inline here; #1427 folded it into the shared\n // builder). The `useMemo` wrap skips the branch + `canonicalJson(params)` +\n // cache lookup on every render when all deps (including the `params`\n // 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":"6nBAMA,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,CCXA,MAAM,EAAa,OAAO,KAYpB,EAAe,OAAO,IAAI,oBAAoB,EAUpD,SAAS,EAAmB,EAA6B,CACvD,GAAI,CACF,OACG,IACC,KACI,EAEV,MAAQ,CACN,MAAO,EACT,CACF,CAYA,SAAS,EACP,EACA,EAC6C,CAC7C,GAAI,CACF,OAAO,EAAa,CAAM,CAC5B,M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,CAAC,EACH,MAAU,MAAM,mDAAmD,EAGrE,OAAO,CACT,ECgBa,MAAkC,CAC7C,IAAM,EAAS,EAAU,EAEzB,OAAO,EAAc,EAAa,CAAM,CAAC,CAAC,QAAQ,CAAC,CACrD,EC3BA,SAAgB,GAAgD,CAC9D,IAAM,EAAS,EAAU,EACnB,EAAQ,EAAoB,CAAM,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,EAC7B,SAAA,EAAC,EAAiB,SAAlB,CAA2B,MAAO,EAChC,SAAA,EAAC,EAAa,SAAd,CAAuB,MAAO,EAC3B,UACoB,CAAA,CACE,CAAA,CACL,CAAA,CAE5B"}
1
+ {"version":3,"file":"RouterProviderCore-BQA-I4NQ.mjs","names":["NavigatorContext","RouteContext","RouterContext","Fragment$1","useRouter","router","useContext","useRouteNode","store","useMemo","createRouteNodeSource","nodeName","snapshot","useSyncExternalStore","navigator","getNavigator","objectKeys","ROUTER_BRAND","isUnreadableRouter","candidate","readPluginApi","getPluginApi","routeName","resolveLinkTarget","to","routeParams","routeSearch","shouldNavigate","evt","targetsAnotherContext","target","encodeFragmentInline","decoded","buildHref","normHash","hash","buildUrl","url","resolved","api","forwarded","path","navigateWithHash","opts","extraOptions","putField","current","navigatedSearch","sameLocationSearch","currentHash","WHITESPACE_PROBE","WHITESPACE_SPLIT","parseTokens","value","buildActiveClassName","isActive","activeClassName","activeTokens","baseClassName","baseTokens","seen","token","shallowEqual","prev","next","prevKeys","nextKeys","prevRecord","nextRecord","key","useIsActiveRoute","createActiveSource","params","search","strict","ignoreQueryParams","RouterErrorBoundary","createDismissableError","onErrorRef","useRef","onError","useLayoutEffect","useEffect","jsxs","children","fallback","useNavigator","useRouteUtils","getRouteUtils","useRouterTransition","getTransitionSource","RouterProviderCore","createRouteSource","primeErrorSource","routeContextValue","jsx"],"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 { getPluginApi } from \"@real-router/core/api\";\nimport { putField } from \"@real-router/core/utils\";\n\nimport 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 — a shim evaluated ahead of core still wins\n * (#1798), which is the doctrine's own caveat and travels with it.\n */\nconst objectKeys = Object.keys;\n\n/**\n * The brand `packages/core/src/internals.ts` puts on every router it registers,\n * RE-DECLARED rather than imported (#2294).\n *\n * ⚑ `Symbol.for` makes the two the same symbol, so **the STRING is the\n * contract** — change it in one place and this warning silently stops firing.\n * The same shape core already uses for `CONFIG_FAULT`, declared twice across a\n * boundary it cannot import over, and pinned the same way: the guard is\n * `foreign-router-href-2294.test.ts`, whose cells fail on exactly that drift.\n */\nconst ROUTER_BRAND = Symbol.for(\"real-router.router\");\n\n/**\n * Is this a real router that core cannot read — as opposed to the `Router`-SHAPED\n * double this helper accepts by contract?\n *\n * ⚠ Read defensively: the argument is the caller's object and may be a `Proxy`\n * whose `get` trap throws. A diagnostic that throws would change where the error\n * comes FROM, which is the #1572 class, so a throwing read means \"cannot tell\".\n */\nfunction isUnreadableRouter(candidate: unknown): boolean {\n try {\n return (\n (candidate as Record<symbol, unknown> | null | undefined)?.[\n ROUTER_BRAND\n ] === true\n );\n } catch {\n return false;\n }\n}\n\n/**\n * The registry lookup, ALONE — and standing alone is what makes the warning\n * correct (#2294).\n *\n * ⚑ Inside the resolve-and-print `try` this could not be told apart from a\n * `forwardState` that threw for a reason the arm handles deliberately. The\n * channel guard (#1572) is exactly that, and it fires on a router that IS\n * registered and IS branded — so a check made there would report duplicated core\n * on a perfectly healthy one.\n */\nfunction readPluginApi(\n router: Router,\n routeName: string,\n): ReturnType<typeof getPluginApi> | undefined {\n try {\n return getPluginApi(router);\n } catch {\n if (isUnreadableRouter(router)) {\n console.error(\n `[real-router] Route \"${routeName}\" rendered its LITERAL path: this IS a router, ` +\n \"but not one this copy of @real-router/core built, so `forwardTo` was not resolved. \" +\n \"It is either wrapped in a Proxy (Vue `reactive()` / Pinia — store it with `markRaw`), \" +\n \"or your dependency tree holds two copies of @real-router/core — dedupe it to one.\",\n );\n }\n\n return undefined;\n }\n}\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 * Does an anchor's `target` send this navigation somewhere the router cannot\n * follow? (#1834)\n *\n * `target` names the browsing context the author wants the URL loaded into.\n * Three values are the router's — absent, empty, `_self` — and every other one\n * goes to the browser, the only thing that can resolve a context name.\n * Intercepting instead is how a `<Link target=\"_blank\">` ends up reloading the\n * same tab rather than opening a new one. React Router's\n * `shouldProcessLinkClick` and TanStack Router's `handleClick` split the same\n * way; neither reproduces browsing contexts inside the router, and neither does\n * this.\n *\n * ⚠ The split is by SPELLING, not by where the value resolves to, and three\n * spellings resolve back to this context anyway: `_parent` and `_top` fall back\n * to `_self` in a document with no ancestor, and `_SELF` matches `_self`\n * ASCII-case-insensitively (MDN, `<a>` § target). All three are handed to the\n * browser, which reaches the right destination by a full page load instead of a\n * transition. Resolving them properly means reproducing frame ancestry and\n * keyword folding here; both reference routers decline, and the cost is a page\n * load rather than a wrong destination.\n *\n * ⚠ Ask this only about an `<a>`. On a `<button v-link>` or a `<div use:link>`\n * the attribute is inert markup the browser will not act on, so deferring there\n * would leave the activation unhandled by anyone. Callers that cannot assume an\n * anchor ask {@link anchorTargetsAnotherContext} instead, which narrows first;\n * `target-predicate-authority-1834` owns which call site is in which set.\n */\nexport function targetsAnotherContext(\n target: string | null | undefined,\n): boolean {\n return Boolean(target) && target !== \"_self\";\n}\n\n/**\n * The same question, asked about an ELEMENT — for the `use:link` / `v-link`\n * forms, which attach to whatever element the consumer wrote and so cannot\n * assume an anchor (#1834). The `<Link>` components pass a value instead\n * (they render the anchor), and so does Angular's directive (its selector is\n * `a[realLink]`).\n *\n * ⚠ `tagName`, never `instanceof HTMLAnchorElement`, for the reason\n * `applyLinkA11y` sets out below: the constructor belongs to the realm this\n * module loaded in, so a real anchor from an iframe `contentDocument` or a\n * micro-frontend fails the check. Failing it HERE re-intercepts the very\n * `target=\"_blank\"` click this predicate exists to leave alone.\n *\n * Anything that is not an HTML anchor answers `false`: `target` is\n * anchor-specific markup the browser will not act on, so a `<button use:link>`\n * or a `<div v-link>` carrying one must still navigate in-app.\n */\nexport function anchorTargetsAnotherContext(\n element: Element | null | undefined,\n): boolean {\n if (element?.tagName !== \"A\") {\n return false;\n }\n\n return targetsAnotherContext(element.getAttribute(\"target\"));\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 the core's resolving door 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 // ⚑ RESOLVE, then print (#2250). An href is a promise about where the click\n // lands, and the click resolves `forwardTo`. `router.buildPath` alone is\n // class LITERAL by record and answers about the route it was NAMED —\n // INVARIANTS #8 keeps that so a plugin can build a state for an alias\n // without being teleported off it — so the chain is resolved FIRST and the\n // printer prints the target. The door choice belongs here rather than one\n // layer down.\n //\n // ⚠ **The `??` is not reached by a name the table does not hold, and the\n // claim that it was described a door this arm stopped calling.** That read\n // `buildNavigationState`, which answers `undefined` for an unknown route;\n // since #2265 the resolving door is `forwardState`, which ANSWERS for one\n // (measured — it does not validate the name), leaving the printer to throw.\n // `packages/react/INVARIANTS.md` row 3 still holds — `Both throw →\n // undefined + console.error` — but it is reached by both printers throwing,\n // not by a `undefined` the `??` absorbs. What the `??` IS load-bearing for\n // is the two cases below.\n //\n // ⚠ **The fallback is also where the channel guard lands (#1572).** A route's\n // declared query name handed in the PATH bag makes the class-① door throw\n // where `buildPath` answers, so the `??` prints the literal path — the same\n // href this arm has always rendered. Under a URL plugin the guard is not\n // swallowed: `router.buildUrl` throws and the outer `catch` drops the href.\n //\n // ⚠ **The inner `try` keeps this helper's STRUCTURAL contract.** `buildHref`\n // is handed a `Router`-shaped object, not necessarily a registered one, and\n // `getPluginApi` resolves it through `getInternals` — a WeakMap keyed on\n // identity, which REFUSES a test double or a `Proxy` wrapper. Such a router\n // keeps the literal path; the stub-router CONTROL in\n // `packages/react/tests/functional/dom-utils/forwarding-link-href-2250.test.ts`\n // owns that.\n let resolved: string | undefined;\n const api = readPluginApi(router, routeName);\n\n try {\n // ⚠ **`forwardState`, not `buildNavigationState`.** Both resolve the whole\n // chain, and the href is identical — but the committing door opts into\n // `reportUndeclaredParamKey`, and an href COMMITS NOTHING. That diagnostic\n // is for a state you are about to persist, which is why `canNavigateTo`\n // is silent despite sharing `navigate`'s form (#2248 / #1581).\n // ⚑ **`buildPathResolved`, not `router.buildPath` — ONE href is ONE pass\n // of the chain (#2260).** The facade's printer runs the `forwardState`\n // seam a door lower (#2087), which is right for a caller holding a raw\n // intent and a SECOND pass for this one, which just resolved. Counted,\n // because nothing in either door's source says \"twice\": the second pass\n // is what two individually-correct doors compose to.\n //\n // ⚠ A plugin author registers one interceptor and has no reason to expect\n // two invocations per href — a stateful one double-counts. Cost is the\n // lesser half: +1333 ns per href with `search-schema` +\n // `persistent-params` installed, per `<Link>` per render.\n //\n // ⚠ `api?.` is a TYPE gate, not a runtime guard, and naming it so keeps it\n // from being read as one: calling `forwardState` on `undefined` throws\n // into the same `catch` for the same outcome, so a mutant dropping the\n // check is EQUIVALENT. What it buys is that TypeScript can see the call is\n // safe below a lookup that may have failed (#2294).\n const forwarded = api?.forwardState(routeName, routeParams, routeSearch);\n\n resolved =\n forwarded &&\n api?.buildPathResolved(\n forwarded.name,\n forwarded.params,\n forwarded.search,\n );\n } catch {\n resolved = undefined;\n }\n\n const path =\n resolved ?? 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 * 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\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 */\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 // ⚑ `putField`, not `opts.hash = …` (#2141 / #1852). The spread above produces\n // no own key for this slot unless the caller's extra options carried one, so\n // a plain assignment walks the prototype: an ambient accessor an application\n // or a polyfill put on `Object.prototype` takes the value and the navigation\n // runs without the fragment it was asked for, or — getter-only — throws.\n //\n // ⚠ This dir is shared, so one unguarded write here multiplies by its whole\n // consumer set — `packages/react` is the coverage and authority owner\n // (#1838) and owns that count. Its scan classifies COMPUTED-key writes only,\n // which is why a literal slot like this one sat outside it.\n putField(opts as unknown as Record<string, unknown>, \"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 an\n// `if (!value) return []` guard here would be unreachable (#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 the adapters built on it resolve active state identically —\n // Solid is the exception, its `Link` carrying its own copy of the decision\n // (#1248 landed the fast path inline here; #1427 folded it into the shared\n // builder). The `useMemo` wrap skips the branch + `canonicalJson(params)` +\n // cache lookup on every render when all deps (including the `params`\n // 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":"6nBAMA,MAAaI,MAA0B,CACrC,IAAMC,EAASC,EAAWJ,CAAa,EAEvC,GAAI,CAACG,EACH,MAAU,MAAM,gDAAgD,EAGlE,OAAOA,CACT,ECNA,SAAgBE,EAAa,EAAgC,CAC3D,IAAMF,EAASD,EAAU,EAEnBI,EAAQC,MACNC,EAAsBL,EAAQM,CAAQ,EAC5C,CAACN,EAAQM,CAAQ,CACnB,EAKMC,EAAWC,EACfL,EAAM,UACNA,EAAM,YACNA,EAAM,WACR,EAGMM,EAAYC,EAAaV,CAAM,EAErC,OAAOI,OACgB,CACnB,YACA,MAAOG,EAAS,MAChB,cAAeA,EAAS,aAC1B,GACA,CAACE,EAAWF,CAAQ,CACtB,CACF,CCXA,MAAMI,EAAa,OAAO,KAYpBC,EAAe,OAAO,IA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EAC7B,SAAA0F,EAAC/F,EAAiB,SAAlB,CAA2B,MAAOc,EAChC,SAAAiF,EAAC9F,EAAa,SAAd,CAAuB,MAAO6F,EAC3B,UACoB,CAAA,CACE,CAAA,CACL,CAAA,CAE5B"}
@@ -1 +1 @@
1
- {"version":3,"file":"createHttpStatusSink-D3tbAjzC.mjs","names":[],"sources":["../../src/components/ClientOnly.tsx","../../src/components/ServerOnly.tsx","../../src/hooks/useDeferred.tsx","../../src/components/Streamed.tsx","../../src/components/HttpStatusProvider.tsx","../../src/components/HttpStatusCode.tsx","../../src/utils/createHttpStatusSink.ts"],"sourcesContent":["import { useEffect, useState } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface ClientOnlyProps {\n readonly children: ReactNode;\n readonly fallback?: ReactNode;\n}\n\nexport function ClientOnly({\n children,\n fallback = null,\n}: ClientOnlyProps): ReactNode {\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n // SSR/hydration boundary: server emits the fallback branch, client matches\n // it on first paint, then this effect flips state to swap in the children.\n // The intentional re-render is what makes the markup match across renders.\n // eslint-disable-next-line @eslint-react/set-state-in-effect -- intentional post-hydration swap\n setMounted(true);\n }, []);\n\n return mounted ? children : fallback;\n}\n","import { useEffect, useState } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface ServerOnlyProps {\n readonly children: ReactNode;\n readonly fallback?: ReactNode;\n}\n\nexport function ServerOnly({\n children,\n fallback = null,\n}: ServerOnlyProps): ReactNode {\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n // SSR/hydration boundary: server emits the children branch, client matches\n // it on first paint, then this effect flips state to swap in the fallback\n // (or hide entirely). The intentional re-render keeps markup consistent\n // across renders.\n // eslint-disable-next-line @eslint-react/set-state-in-effect -- intentional post-hydration swap\n setMounted(true);\n }, []);\n\n return mounted ? fallback : children;\n}\n","import { NEVER_PROMISE } from \"../constants\";\nimport { useRoute } from \"./useRoute\";\n\ninterface DeferredContext {\n ssrDataDeferred?: Record<string, Promise<unknown>>;\n}\n\n/**\n * Read a deferred promise published by `defer({ deferred: { <key>: Promise } })`\n * inside an SSR data loader.\n *\n * - **Server render**: returns the actual loader-returned promise. Combine\n * with `<Suspense>` + `use(promise)` for native streaming via React 19's\n * `renderToReadableStream`.\n * - **Post-hydration**: returns a registry-backed promise; the inline\n * `<script>__rrDefer__(\"key\", json)</script>` tags emitted by the server\n * stream resolve it. `use()` returns synchronously once the registry\n * settles.\n * - **Unknown key**: returns a never-resolving promise — Suspense boundary\n * stays in fallback. This surfaces consumer/loader key drift as a visible\n * loading state instead of a silent runtime error.\n *\n * The hook subscribes to `RouteContext`, so it re-runs on every navigation.\n * Promise reference identity is stable across renders within the same\n * navigation — `use()` will not re-suspend on rerenders.\n */\nexport function useDeferred<T = unknown>(key: string): Promise<T> {\n const { route } = useRoute();\n const context = route.context as DeferredContext;\n const deferred = context.ssrDataDeferred;\n const promise = deferred?.[key];\n\n return (promise ?? NEVER_PROMISE) as Promise<T>;\n}\n","import { Suspense } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface StreamedProps {\n /** Shown while any descendant `use(promise)` / `<Await>` is pending. */\n readonly fallback: ReactNode;\n readonly children: ReactNode;\n}\n\n/**\n * Cross-adapter alias for `<Suspense fallback={…}>`. Pairs with `<Await>`\n * for symmetry with `<Streamed>` boundaries in the SvelteKit / Solid\n * deferred-data conventions.\n *\n * ```tsx\n * <Streamed fallback={<Spinner />}>\n * <Await<Review[]> name=\"reviews\">\n * {(reviews) => <ReviewList items={reviews} />}\n * </Await>\n * </Streamed>\n * ```\n *\n * The component is a thin wrapper around React's native `<Suspense>` — no\n * additional behaviour. Use plain `<Suspense>` directly if you don't need\n * the cross-framework naming alignment.\n */\nexport function Streamed({ fallback, children }: StreamedProps): ReactNode {\n return <Suspense fallback={fallback}>{children}</Suspense>;\n}\n","import { createContext } from \"react\";\n\nimport type { HttpStatusSink } from \"../utils/createHttpStatusSink\";\nimport type { ReactNode } from \"react\";\n\nexport const HttpStatusContext = createContext<HttpStatusSink | null>(null);\n\nexport interface HttpStatusProviderProps {\n readonly sink: HttpStatusSink;\n readonly children: ReactNode;\n}\n\nexport function HttpStatusProvider({\n sink,\n children,\n}: HttpStatusProviderProps): ReactNode {\n // `<HttpStatusContext.Provider value>` (not the React 19 `<HttpStatusContext value>`\n // shorthand) — same component file is exported via `/legacy/ssr` for React 18\n // consumers, where the shorthand throws \"Element type is invalid: expected\n // a string but got: object\".\n return (\n <HttpStatusContext.Provider value={sink}>\n {children}\n </HttpStatusContext.Provider>\n );\n}\n","import { useContext } from \"react\";\n\nimport { HttpStatusContext } from \"./HttpStatusProvider\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface HttpStatusCodeProps {\n /** HTTP status to apply to the response. Common values: 404, 410, 451, 503. */\n readonly code: number;\n}\n\n/**\n * Render-time HTTP status declaration. Mount inside a route component (typical\n * use case: a glob `*` route's NotFound page) when the status is decided by\n * the rendered tree rather than a loader.\n *\n * Writes `code` to the nearest `<HttpStatusProvider>`'s sink during render and\n * returns `null`. With no provider mounted (the standard client-side case)\n * the component is a silent no-op — same component tree hydrates without\n * touching the DOM or warning about mismatches.\n *\n * Loader-driven errors (`LoaderNotFound` → 404, `LoaderRedirect` → 30x) keep\n * working as before; this component covers render-time decisions only.\n *\n * Last write wins when several `<HttpStatusCode />` instances mount in the\n * same render pass — sink reflects the last component that ran.\n *\n * ```tsx\n * // entry-server.tsx\n * import { renderToString } from \"react-dom/server\";\n * import { createHttpStatusSink, HttpStatusProvider } from \"@real-router/react/ssr\";\n *\n * const sink = createHttpStatusSink();\n * const html = renderToString(\n * <HttpStatusProvider sink={sink}>\n * <RouterProvider router={router}>\n * <App />\n * </RouterProvider>\n * </HttpStatusProvider>,\n * );\n * response.status(sink.code ?? 200).send(html);\n * ```\n *\n * **Streaming SSR (`renderToReadableStream`):** the response status MUST be\n * sent before the first body byte flushes. If `<HttpStatusCode />` is mounted\n * inside a late-resolving `<Suspense>` boundary, the sink write may happen\n * AFTER the headers are already on the wire — the override is then lost.\n * Either mount the component in the shell (above every `<Suspense>` that\n * could delay it) or `await stream.allReady` before reading `sink.code`\n * (which forfeits streaming benefits). For non-streaming SSR\n * (`renderToString`) there is no such ordering concern.\n *\n * **Valid `code` range:** Node's `res.end()` throws `Invalid status code` on\n * `NaN`, `0`, negative values, or values `> 999` — this surfaces as a 5xx /\n * dropped connection, not silent corruption. Pass a real HTTP status integer\n * (commonly 4xx/5xx; 100-999 is what Node accepts).\n */\nexport function HttpStatusCode({ code }: HttpStatusCodeProps): ReactNode {\n const sink = useContext(HttpStatusContext);\n\n if (sink) {\n // Dev-only validation: Node's `res.end()` throws `Invalid status code` on\n // NaN / 0 / negative / non-integer / >999. Surface the bad value at the\n // source so the consumer can fix the routing logic, instead of waiting\n // for the server to crash mid-response. Production builds (Vite, esbuild,\n // tsdown all replace `process.env.NODE_ENV !== \"production\"` with `false`)\n // strip the check.\n if (\n process.env.NODE_ENV !== \"production\" &&\n (!Number.isInteger(code) || code < 100 || code > 999)\n ) {\n console.error(\n `[real-router] <HttpStatusCode code={${String(code)}} /> received an invalid HTTP status code. Node's res.end() rejects values that are not an integer in [100, 999] — pass a real HTTP status (commonly 4xx/5xx).`,\n );\n }\n\n sink.code = code;\n }\n\n return null;\n}\n","/**\n * Render-scoped HTTP status sink. Created per request on the server, passed to\n * `<HttpStatusProvider sink={...}>`, and read after `renderToString` /\n * `renderToReadableStream` to apply the value to the HTTP response.\n *\n * Last write wins: if the rendered tree mounts more than one\n * `<HttpStatusCode />`, the value reflects the last component that ran during\n * the render pass.\n *\n * No-op on the client — `<HttpStatusCode />` reads the optional context and\n * skips the write when no provider is mounted, so the same component tree can\n * be hydrated without changing behaviour.\n *\n * Constraints:\n * - **Per-request only.** Don't share a sink across requests; the rendered\n * tree mutates `code` in place. Module-level singletons leak status\n * between concurrent requests.\n * - **Don't `Object.freeze` the sink.** The component writes to `.code`;\n * freezing makes the assignment throw under ESM strict mode.\n */\nexport interface HttpStatusSink {\n code: number | undefined;\n}\n\nexport function createHttpStatusSink(): HttpStatusSink {\n return { code: undefined };\n}\n"],"mappings":"uLASA,SAAgB,EAAW,CACzB,WACA,WAAW,MACkB,CAC7B,GAAM,CAAC,EAAS,GAAc,EAAS,EAAK,EAU5C,OARA,MAAgB,CAKd,EAAW,EAAI,CACjB,EAAG,CAAC,CAAC,EAEE,EAAU,EAAW,CAC9B,CCfA,SAAgB,EAAW,CACzB,WACA,WAAW,MACkB,CAC7B,GAAM,CAAC,EAAS,GAAc,EAAS,EAAK,EAW5C,OATA,MAAgB,CAMd,EAAW,EAAI,CACjB,EAAG,CAAC,CAAC,EAEE,EAAU,EAAW,CAC9B,CCCA,SAAgB,EAAyB,EAAyB,CAChE,GAAM,CAAE,SAAU,EAAS,EAK3B,OAJgB,EAAM,QACG,kBACE,IAER,CACrB,CCNA,SAAgB,EAAS,CAAE,WAAU,YAAsC,CACzE,OAAO,EAAC,EAAD,CAAoB,WAAW,UAAmB,CAAA,CAC3D,CCxBA,MAAa,EAAoB,EAAqC,IAAI,EAO1E,SAAgB,EAAmB,CACjC,OACA,YACqC,CAKrC,OACE,EAAC,EAAkB,SAAnB,CAA4B,MAAO,EAChC,UACyB,CAAA,CAEhC,CCgCA,SAAgB,EAAe,CAAE,QAAwC,CACvE,IAAM,EAAO,EAAW,CAAiB,EAqBzC,OAnBI,IAQA,QAAQ,IAAI,WAAa,eACxB,CAAC,OAAO,UAAU,CAAI,GAAK,EAAO,KAAO,EAAO,MAEjD,QAAQ,MACN,uCAAuC,OAAO,CAAI,EAAE,+JACtD,EAGF,EAAK,KAAO,GAGP,IACT,CCxDA,SAAgB,GAAuC,CACrD,MAAO,CAAE,KAAM,IAAA,EAAU,CAC3B"}
1
+ {"version":3,"file":"createHttpStatusSink-D3tbAjzC.mjs","names":["NEVER_PROMISE","ClientOnly","mounted","setMounted","useState","useEffect","children","fallback","ServerOnly","useDeferred","useRoute","route","key","Streamed","jsx","Suspense","HttpStatusContext","createContext","HttpStatusProvider","sink","HttpStatusCode","useContext","code","createHttpStatusSink"],"sources":["../../src/components/ClientOnly.tsx","../../src/components/ServerOnly.tsx","../../src/hooks/useDeferred.tsx","../../src/components/Streamed.tsx","../../src/components/HttpStatusProvider.tsx","../../src/components/HttpStatusCode.tsx","../../src/utils/createHttpStatusSink.ts"],"sourcesContent":["import { useEffect, useState } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface ClientOnlyProps {\n readonly children: ReactNode;\n readonly fallback?: ReactNode;\n}\n\nexport function ClientOnly({\n children,\n fallback = null,\n}: ClientOnlyProps): ReactNode {\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n // SSR/hydration boundary: server emits the fallback branch, client matches\n // it on first paint, then this effect flips state to swap in the children.\n // The intentional re-render is what makes the markup match across renders.\n // eslint-disable-next-line @eslint-react/set-state-in-effect -- intentional post-hydration swap\n setMounted(true);\n }, []);\n\n return mounted ? children : fallback;\n}\n","import { useEffect, useState } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface ServerOnlyProps {\n readonly children: ReactNode;\n readonly fallback?: ReactNode;\n}\n\nexport function ServerOnly({\n children,\n fallback = null,\n}: ServerOnlyProps): ReactNode {\n const [mounted, setMounted] = useState(false);\n\n useEffect(() => {\n // SSR/hydration boundary: server emits the children branch, client matches\n // it on first paint, then this effect flips state to swap in the fallback\n // (or hide entirely). The intentional re-render keeps markup consistent\n // across renders.\n // eslint-disable-next-line @eslint-react/set-state-in-effect -- intentional post-hydration swap\n setMounted(true);\n }, []);\n\n return mounted ? fallback : children;\n}\n","import { NEVER_PROMISE } from \"../constants\";\nimport { useRoute } from \"./useRoute\";\n\ninterface DeferredContext {\n ssrDataDeferred?: Record<string, Promise<unknown>>;\n}\n\n/**\n * Read a deferred promise published by `defer({ deferred: { <key>: Promise } })`\n * inside an SSR data loader.\n *\n * - **Server render**: returns the actual loader-returned promise. Combine\n * with `<Suspense>` + `use(promise)` for native streaming via React 19's\n * `renderToReadableStream`.\n * - **Post-hydration**: returns a registry-backed promise; the inline\n * `<script>__rrDefer__(\"key\", json)</script>` tags emitted by the server\n * stream resolve it. `use()` returns synchronously once the registry\n * settles.\n * - **Unknown key**: returns a never-resolving promise — Suspense boundary\n * stays in fallback. This surfaces consumer/loader key drift as a visible\n * loading state instead of a silent runtime error.\n *\n * The hook subscribes to `RouteContext`, so it re-runs on every navigation.\n * Promise reference identity is stable across renders within the same\n * navigation — `use()` will not re-suspend on rerenders.\n */\nexport function useDeferred<T = unknown>(key: string): Promise<T> {\n const { route } = useRoute();\n const context = route.context as DeferredContext;\n const deferred = context.ssrDataDeferred;\n const promise = deferred?.[key];\n\n return (promise ?? NEVER_PROMISE) as Promise<T>;\n}\n","import { Suspense } from \"react\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface StreamedProps {\n /** Shown while any descendant `use(promise)` / `<Await>` is pending. */\n readonly fallback: ReactNode;\n readonly children: ReactNode;\n}\n\n/**\n * Cross-adapter alias for `<Suspense fallback={…}>`. Pairs with `<Await>`\n * for symmetry with `<Streamed>` boundaries in the SvelteKit / Solid\n * deferred-data conventions.\n *\n * ```tsx\n * <Streamed fallback={<Spinner />}>\n * <Await<Review[]> name=\"reviews\">\n * {(reviews) => <ReviewList items={reviews} />}\n * </Await>\n * </Streamed>\n * ```\n *\n * The component is a thin wrapper around React's native `<Suspense>` — no\n * additional behaviour. Use plain `<Suspense>` directly if you don't need\n * the cross-framework naming alignment.\n */\nexport function Streamed({ fallback, children }: StreamedProps): ReactNode {\n return <Suspense fallback={fallback}>{children}</Suspense>;\n}\n","import { createContext } from \"react\";\n\nimport type { HttpStatusSink } from \"../utils/createHttpStatusSink\";\nimport type { ReactNode } from \"react\";\n\nexport const HttpStatusContext = createContext<HttpStatusSink | null>(null);\n\nexport interface HttpStatusProviderProps {\n readonly sink: HttpStatusSink;\n readonly children: ReactNode;\n}\n\nexport function HttpStatusProvider({\n sink,\n children,\n}: HttpStatusProviderProps): ReactNode {\n // `<HttpStatusContext.Provider value>` (not the React 19 `<HttpStatusContext value>`\n // shorthand) — same component file is exported via `/legacy/ssr` for React 18\n // consumers, where the shorthand throws \"Element type is invalid: expected\n // a string but got: object\".\n return (\n <HttpStatusContext.Provider value={sink}>\n {children}\n </HttpStatusContext.Provider>\n );\n}\n","import { useContext } from \"react\";\n\nimport { HttpStatusContext } from \"./HttpStatusProvider\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface HttpStatusCodeProps {\n /** HTTP status to apply to the response. Common values: 404, 410, 451, 503. */\n readonly code: number;\n}\n\n/**\n * Render-time HTTP status declaration. Mount inside a route component (typical\n * use case: a glob `*` route's NotFound page) when the status is decided by\n * the rendered tree rather than a loader.\n *\n * Writes `code` to the nearest `<HttpStatusProvider>`'s sink during render and\n * returns `null`. With no provider mounted (the standard client-side case)\n * the component is a silent no-op — same component tree hydrates without\n * touching the DOM or warning about mismatches.\n *\n * Loader-driven errors (`LoaderNotFound` → 404, `LoaderRedirect` → 30x) keep\n * working as before; this component covers render-time decisions only.\n *\n * Last write wins when several `<HttpStatusCode />` instances mount in the\n * same render pass — sink reflects the last component that ran.\n *\n * ```tsx\n * // entry-server.tsx\n * import { renderToString } from \"react-dom/server\";\n * import { createHttpStatusSink, HttpStatusProvider } from \"@real-router/react/ssr\";\n *\n * const sink = createHttpStatusSink();\n * const html = renderToString(\n * <HttpStatusProvider sink={sink}>\n * <RouterProvider router={router}>\n * <App />\n * </RouterProvider>\n * </HttpStatusProvider>,\n * );\n * response.status(sink.code ?? 200).send(html);\n * ```\n *\n * **Streaming SSR (`renderToReadableStream`):** the response status MUST be\n * sent before the first body byte flushes. If `<HttpStatusCode />` is mounted\n * inside a late-resolving `<Suspense>` boundary, the sink write may happen\n * AFTER the headers are already on the wire — the override is then lost.\n * Either mount the component in the shell (above every `<Suspense>` that\n * could delay it) or `await stream.allReady` before reading `sink.code`\n * (which forfeits streaming benefits). For non-streaming SSR\n * (`renderToString`) there is no such ordering concern.\n *\n * **Valid `code` range:** Node's `res.end()` throws `Invalid status code` on\n * `NaN`, `0`, negative values, or values `> 999` — this surfaces as a 5xx /\n * dropped connection, not silent corruption. Pass a real HTTP status integer\n * (commonly 4xx/5xx; 100-999 is what Node accepts).\n */\nexport function HttpStatusCode({ code }: HttpStatusCodeProps): ReactNode {\n const sink = useContext(HttpStatusContext);\n\n if (sink) {\n // Dev-only validation: Node's `res.end()` throws `Invalid status code` on\n // NaN / 0 / negative / non-integer / >999. Surface the bad value at the\n // source so the consumer can fix the routing logic, instead of waiting\n // for the server to crash mid-response. Production builds (Vite, esbuild,\n // tsdown all replace `process.env.NODE_ENV !== \"production\"` with `false`)\n // strip the check.\n if (\n process.env.NODE_ENV !== \"production\" &&\n (!Number.isInteger(code) || code < 100 || code > 999)\n ) {\n console.error(\n `[real-router] <HttpStatusCode code={${String(code)}} /> received an invalid HTTP status code. Node's res.end() rejects values that are not an integer in [100, 999] — pass a real HTTP status (commonly 4xx/5xx).`,\n );\n }\n\n sink.code = code;\n }\n\n return null;\n}\n","/**\n * Render-scoped HTTP status sink. Created per request on the server, passed to\n * `<HttpStatusProvider sink={...}>`, and read after `renderToString` /\n * `renderToReadableStream` to apply the value to the HTTP response.\n *\n * Last write wins: if the rendered tree mounts more than one\n * `<HttpStatusCode />`, the value reflects the last component that ran during\n * the render pass.\n *\n * No-op on the client — `<HttpStatusCode />` reads the optional context and\n * skips the write when no provider is mounted, so the same component tree can\n * be hydrated without changing behaviour.\n *\n * Constraints:\n * - **Per-request only.** Don't share a sink across requests; the rendered\n * tree mutates `code` in place. Module-level singletons leak status\n * between concurrent requests.\n * - **Don't `Object.freeze` the sink.** The component writes to `.code`;\n * freezing makes the assignment throw under ESM strict mode.\n */\nexport interface HttpStatusSink {\n code: number | undefined;\n}\n\nexport function createHttpStatusSink(): HttpStatusSink {\n return { code: undefined };\n}\n"],"mappings":"uLASA,SAAgBC,EAAW,CACzB,WACA,WAAW,MACkB,CAC7B,GAAM,CAACC,EAASC,GAAcC,EAAS,EAAK,EAU5C,OARAC,MAAgB,CAKdF,EAAW,EAAI,CACjB,EAAG,CAAC,CAAC,EAEED,EAAUI,EAAWC,CAC9B,CCfA,SAAgBC,EAAW,CACzB,WACA,WAAW,MACkB,CAC7B,GAAM,CAACN,EAASC,GAAcC,EAAS,EAAK,EAW5C,OATAC,MAAgB,CAMdF,EAAW,EAAI,CACjB,EAAG,CAAC,CAAC,EAEED,EAAUK,EAAWD,CAC9B,CCCA,SAAgBG,EAAyB,EAAyB,CAChE,GAAM,CAAE,SAAUC,EAAS,EAK3B,OAJgBC,EAAM,QACG,kBACEC,IAERZ,CACrB,CCNA,SAAgBa,EAAS,CAAE,WAAU,YAAsC,CACzE,OAAOC,EAACC,EAAD,CAAoB,WAAW,UAAmB,CAAA,CAC3D,CCxBA,MAAaC,EAAoBC,EAAqC,IAAI,EAO1E,SAAgBC,EAAmB,CACjC,OACA,YACqC,CAKrC,OACEJ,EAACE,EAAkB,SAAnB,CAA4B,MAAOG,EAChC,UACyB,CAAA,CAEhC,CCgCA,SAAgBC,EAAe,CAAE,QAAwC,CACvE,IAAMD,EAAOE,EAAWL,CAAiB,EAqBzC,OAnBIG,IAQA,QAAQ,IAAI,WAAa,eACxB,CAAC,OAAO,UAAUG,CAAI,GAAKA,EAAO,KAAOA,EAAO,MAEjD,QAAQ,MACN,uCAAuC,OAAOA,CAAI,EAAE,+JACtD,EAGF,EAAK,KAAOA,GAGP,IACT,CCxDA,SAAgBC,GAAuC,CACrD,MAAO,CAAE,KAAM,IAAA,EAAU,CAC3B"}
@@ -1,6 +1,6 @@
1
1
  import { a as RouteExitContext, c as useRouteExit, d as NotFoundProps, f as RouteViewProps, i as useRouteEnter, l as RouteView, n as RouteEnterHandler, o as RouteExitHandler, p as SelfProps, r as UseRouteEnterOptions, s as UseRouteExitOptions, t as RouteEnterContext, u as MatchProps } from "./useRouteEnter-BDNrSg2k.mjs";
2
2
  import { n as RouterErrorBoundaryProps, r as LinkProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-DZI_DkW5.mjs";
3
- import { i as Link, n as DirectionTracker, r as createDirectionTracker, t as RouterProvider } from "./RouterProvider-BixslYdB.mjs";
3
+ import { i as Link, n as DirectionTracker, r as createDirectionTracker, t as RouterProvider } from "./RouterProvider-BhOgl2jd.mjs";
4
4
  import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-YvPtN5pW.mjs";
5
5
  import { Navigator } from "@real-router/core";
6
6
  import { RouterTransitionSnapshot } from "@real-router/sources";
@@ -1,2 +1,2 @@
1
- import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,h as n,i as r,m as i,n as a,r as o}from"./RouterProviderCore-BQA-I4NQ.mjs";import{n as s,t as c}from"./RouterProvider-BDUET4Ke.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,events as b}from"@real-router/core";import{startsWithSegment as x}from"@real-router/route-utils";import{Fragment as S,jsx as C}from"react/jsx-runtime";import{createRouteEnterGate as w,guardLeaveListener as T}from"@real-router/sources";import{getPluginApi as E}from"@real-router/core/api";function D(e){return null}D.displayName=`RouteView.Match`;function O(e){return null}O.displayName=`RouteView.Self`;function k(e){return null}k.displayName=`RouteView.NotFound`;const A=new Set([D,O,k]);function j(e,t,n){return t===``?!1:n?e===t:x(e,t)}function M(e,t){u.forEach(e,e=>{p(e)&&(A.has(e.type)?t.push(e):M(e.props.children,t))})}function N(e,t,n,r,i){let a=i===void 0?e:C(f,{fallback:i,children:e});return n?C(l,{mode:r,children:a},t):C(d,{children:a},t)}function P(e,t){return e.type===k?(t.notFoundFound||=(t.notFoundChildren=e.props.children,!0),!0):e.type===O&&(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0)}function F(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&&j(t,u,s)?{rendered:N(a.children,u,c,`visible`,l),activatedName:u}:c&&r.has(u)?{rendered:N(a.children,u,c,`hidden`,l),activatedName:null}:{rendered:null,activatedName:null}}function I(e,t,n,r){if(r.selfFound&&t===n){e.push(N(r.selfChildren,`__route-view-self__`,!1,`visible`,r.selfFallback));return}t===y&&r.notFoundChildren!==null&&e.push(C(d,{children:r.notFoundChildren},`__route-view-not-found__`))}function L(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(P(s,i))continue;let e=F(s,t,n,r,a!==null);e.activatedName!==null&&(a=e.activatedName),e.rendered!==null&&o.push(e.rendered)}return a===null&&I(o,t,n,i),{rendered:o,activeMatchFound:a!==null,activatedName:a}}function R({nodeName:e,children:t}){let{route:n}=i(e),r=_(null);r.current??=new Set;let a=r.current,o=g(()=>{let e=[];return M(t,e),e},[t]),s=n?.name??null,{rendered:c,activatedName:l}=g(()=>{if(s===null)return{rendered:[],activatedName:null};let t=L(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?C(S,{children:c}):null}R.displayName=`RouteView`;const z=Object.assign(R,{Match:D,Self:O,NotFound:k}),B=Object.freeze({destroy:()=>{}});function V(e){if(typeof document>`u`)return B;let t=!1;document.documentElement.dataset.navDirection=`forward`;let n=!1,r=!1,i=()=>{t=!0,r=n};globalThis.addEventListener(`popstate`,i);let a=E(e),o=()=>{if(n=!1,r){r=!1;return}t=!1},s=[a.addEventListener(b.TRANSITION_START,()=>{n=!0}),a.addEventListener(b.TRANSITION_SUCCESS,o),a.addEventListener(b.TRANSITION_ERROR,o),a.addEventListener(b.TRANSITION_CANCEL,o),e.subscribeLeave(()=>{document.documentElement.dataset.navDirection=t?`back`:`forward`,t=!1,r=!1})];return{destroy:()=>{for(let e of s)e();globalThis.removeEventListener(`popstate`,i),delete document.documentElement.dataset.navDirection}}}function H(e,t){let r=n(),i=_(e),a=t?.skipSameRoute??!0;h(()=>{i.current=e}),m(()=>r.subscribeLeave(T(e=>i.current(e),{skipSameRoute:a})),[r,a])}function U(t,n){let{route:r,previousRoute:i}=e(),a=_(t),[o]=v(()=>w()),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,z as RouteView,t as RouterErrorBoundary,c as RouterProvider,V as createDirectionTracker,r as useNavigator,e as useRoute,U as useRouteEnter,H as useRouteExit,i as useRouteNode,o as useRouteUtils,n as useRouter,a as useRouterTransition};
1
+ import{t as e}from"./useRoute-5MF3j-9P.mjs";import{a as t,h as n,i as r,m as i,n as a,r as o}from"./RouterProviderCore-BQA-I4NQ.mjs";import{n as s,t as c}from"./RouterProvider-BDUET4Ke.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,events as b}from"@real-router/core";import{startsWithSegment as x}from"@real-router/route-utils";import{Fragment as S,jsx as C}from"react/jsx-runtime";import{createRouteEnterGate as w,guardLeaveListener as T}from"@real-router/sources";import{getPluginApi as E}from"@real-router/core/api";function D(e){return null}D.displayName=`RouteView.Match`;function O(e){return null}O.displayName=`RouteView.Self`;function k(e){return null}k.displayName=`RouteView.NotFound`;const A=new Set([D,O,k]);function j(e,t,n){return t===``?!1:n?e===t:x(e,t)}function M(e,t){u.forEach(e,e=>{p(e)&&(A.has(e.type)?t.push(e):M(e.props.children,t))})}function N(e,t,n,r,i){let a=i===void 0?e:C(f,{fallback:i,children:e});return n?C(l,{mode:r,children:a},t):C(d,{children:a},t)}function P(e,t){return e.type===k?(t.notFoundFound||=(t.notFoundChildren=e.props.children,!0),!0):e.type===O&&(t.selfFound||=(t.selfChildren=e.props.children,t.selfFallback=e.props.fallback,!0),!0)}function F(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&&j(t,u,s)?{rendered:N(a.children,u,c,`visible`,l),activatedName:u}:c&&r.has(u)?{rendered:N(a.children,u,c,`hidden`,l),activatedName:null}:{rendered:null,activatedName:null}}function I(e,t,n,r){if(r.selfFound&&t===n){e.push(N(r.selfChildren,`__route-view-self__`,!1,`visible`,r.selfFallback));return}t===y&&r.notFoundChildren!==null&&e.push(C(d,{children:r.notFoundChildren},`__route-view-not-found__`))}function L(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(P(s,i))continue;let e=F(s,t,n,r,a!==null);e.activatedName!==null&&(a=e.activatedName),e.rendered!==null&&o.push(e.rendered)}return a===null&&I(o,t,n,i),{rendered:o,activeMatchFound:a!==null,activatedName:a}}function R({nodeName:e,children:t}){let{route:n}=i(e),r=_(null);r.current??=new Set;let a=r.current,o=g(()=>{let e=[];return M(t,e),e},[t]),s=n?.name??null,{rendered:c,activatedName:l}=g(()=>{if(s===null)return{rendered:[],activatedName:null};let t=L(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?C(S,{children:c}):null}R.displayName=`RouteView`;const z=Object.assign(R,{Match:D,Self:O,NotFound:k}),B=Object.freeze({destroy:()=>{}});function V(e){if(typeof document>`u`)return B;let t=!1;document.documentElement.dataset.navDirection=`forward`;let n=!1,r=!1,i=()=>{let t=e.getState(),n=e.buildUrl;if(t===void 0||n===void 0)return!1;try{let e=t.context?.url?.hash,r=n(t.name,t.params,t.search,e?{hash:e}:void 0);return r!==void 0&&new URL(r,globalThis.location.href).href===globalThis.location.href}catch{return!1}},a=()=>{i()||(t=!0,r=n)};globalThis.addEventListener(`popstate`,a);let o=E(e),s=()=>{if(n=!1,r){r=!1;return}t=!1},c=[o.addEventListener(b.TRANSITION_START,()=>{n=!0}),o.addEventListener(b.TRANSITION_SUCCESS,s),o.addEventListener(b.TRANSITION_ERROR,s),o.addEventListener(b.TRANSITION_CANCEL,s),e.subscribeLeave(()=>{document.documentElement.dataset.navDirection=t?`back`:`forward`,t=!1,r=!1})];return{destroy:()=>{for(let e of c)e();globalThis.removeEventListener(`popstate`,a),delete document.documentElement.dataset.navDirection}}}function H(e,t){let r=n(),i=_(e),a=t?.skipSameRoute??!0;h(()=>{i.current=e}),m(()=>r.subscribeLeave(T(e=>i.current(e),{skipSameRoute:a})),[r,a])}function U(t,n){let{route:r,previousRoute:i}=e(),a=_(t),[o]=v(()=>w()),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,z as RouteView,t as RouterErrorBoundary,c as RouterProvider,V as createDirectionTracker,r as useNavigator,e as useRoute,U as useRouteEnter,H as useRouteExit,i as useRouteNode,o as useRouteUtils,n as useRouter,a 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","../../../../shared/dom-utils/direction-tracker.ts","../../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 { events } from \"@real-router/core\";\nimport { getPluginApi } from \"@real-router/core/api\";\n\nimport type { Router } from \"@real-router/core\";\n\nexport interface DirectionTracker {\n destroy: () => void;\n}\n\nconst NOOP_INSTANCE: DirectionTracker = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\n/**\n * Track navigation direction (forward / back) and write it to\n * `<html data-nav-direction>` on every leave. CSS / JS readers consume\n * the attribute via `html[data-nav-direction=\"back\"]` selectors or\n * `document.documentElement.dataset.navDirection`.\n *\n * Mechanism-agnostic — works identically whether downstream UI uses CSS\n * `@keyframes`, View Transitions pseudo-elements, or library state\n * (motion's `motion.div initial={{ x: ... }}`).\n *\n * Implementation:\n * - On install, set `data-nav-direction=\"forward\"` baseline.\n * - Attach a `popstate` listener that flips an internal flag to\n * `true`. Browser back/forward navigation triggers popstate; user\n * clicks on `<Link>` / programmatic `router.navigate(...)` do not.\n * - On every `subscribeLeave`, write\n * `popstateFlag ? \"back\" : \"forward\"` and reset the flag.\n *\n * Returns `{ destroy }` to clean up the listener and clear the dataset\n * attribute.\n */\nexport function createDirectionTracker(router: Router): DirectionTracker {\n if (typeof document === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n let popstateFlag = false;\n\n document.documentElement.dataset.navDirection = \"forward\";\n\n let transitionInFlight = false;\n let armedMidTransition = false;\n\n // ⚑ The flag is SPENT by the transition it belongs to, whether or not that\n // transition reaches a leave phase (#1924). It is armed by any `popstate` on\n // `globalThis`, not only one the router consumes, so `history.back()` onto an\n // entry that resolves to the current state — core answers `SAME_STATES`, and\n // measured, that arc emits `TRANSITION_ERROR` with no `TRANSITION_START` and\n // no leave — would otherwise leave it armed indefinitely and publish the next\n // FORWARD navigation as \"back\".\n //\n // ⚠ A clock has no correct value to be set to. The leave phase is separated\n // from its popstate by every deactivation guard, and a guard may await\n // anything; the plugin also DEFERS a popstate that arrives during an\n // in-flight transition and replays it from that transition's `finally`. The\n // gap has no upper bound. Measured on the obvious choice: a task-boundary\n // expiry disarms a live navigation on ONE async `canDeactivate`.\n const onPopstate = (): void => {\n popstateFlag = true;\n // A deferred event belongs to the replay, not to the transition running\n // now, so that transition's terminal event must not spend it.\n armedMidTransition = transitionInFlight;\n };\n\n // IMPORTANT — listener-ordering: `popstate` fires on `window`, which\n // has no DOM descendants, so capture phase is moot. Listeners are\n // dispatched in registration order. To beat the browser-plugin's own\n // popstate handler, this tracker must be installed **before**\n // `router.usePlugin(browserPluginFactory())` in user code. Otherwise\n // the plugin's handler runs first and synchronously fires\n // `subscribeLeave` while `popstateFlag` is still `false`.\n globalThis.addEventListener(\"popstate\", onPopstate);\n\n const api = getPluginApi(router);\n\n const onSettled = (): void => {\n transitionInFlight = false;\n\n if (armedMidTransition) {\n armedMidTransition = false;\n\n return;\n }\n\n popstateFlag = false;\n };\n\n const unsubs = [\n api.addEventListener(events.TRANSITION_START, () => {\n transitionInFlight = true;\n }),\n api.addEventListener(events.TRANSITION_SUCCESS, onSettled),\n api.addEventListener(events.TRANSITION_ERROR, onSettled),\n api.addEventListener(events.TRANSITION_CANCEL, onSettled),\n router.subscribeLeave(() => {\n document.documentElement.dataset.navDirection = popstateFlag\n ? \"back\"\n : \"forward\";\n popstateFlag = false;\n armedMidTransition = false;\n }),\n ];\n\n return {\n destroy: () => {\n for (const unsub of unsubs) {\n unsub();\n }\n\n globalThis.removeEventListener(\"popstate\", onPopstate);\n delete document.documentElement.dataset.navDirection;\n },\n };\n}\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":"kqBAEA,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,UA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ACvD,EAAI,iBAAiB,EAAO,kBAAmB,CAAS,EACxD,EAAO,mBAAqB,CAC1B,SAAS,gBAAgB,QAAQ,aAAe,EAC5C,OACA,UACJ,EAAe,GACf,EAAqB,EACvB,CAAC,CACH,EAEA,MAAO,CACL,YAAe,CACb,IAAK,IAAM,KAAS,EAClB,EAAM,EAGR,WAAW,oBAAoB,WAAY,CAAU,EACrD,OAAO,SAAS,gBAAgB,QAAQ,YAC1C,CACF,CACF,CCwBA,SAAgB,EACd,EACA,EACM,CACN,IAAM,EAAS,EAAU,EACnB,EAAa,EAAO,CAAO,EAC3B,EAAgB,GAAS,eAAiB,GAQhD,MAAsB,CACpB,EAAW,QAAU,CACvB,CAAC,EAED,MAKS,EAAO,eACZ,EAAoB,GAAY,EAAW,QAAQ,CAAO,EAAG,CAC3D,eACF,CAAC,CACH,EACC,CAAC,EAAQ,CAAa,CAAC,CAC5B,CChEA,SAAgB,EACd,EACA,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":["useRoute","RouterErrorBoundary","useRouter","useNavigator","useRouteNode","useRouterTransition","useRouteUtils","Link","RouterProvider","Fragment$1","Match","Self","NotFound","MARKER_TYPES","isSegmentMatch","fullSegmentName","exact","routeName","startsWithSegment","collectElements","Children","children","isValidElement","child","result","renderSlotElement","content","fallback","slotChildren","jsx","Suspense","keepAlive","Activity","key","Fragment","recordFallback","slots","processMatch","matchProps","nodeName","segment","alreadyActive","hasBeenActivated","appendFallback","rendered","UNKNOWN_ROUTE","buildRenderList","activatedName","elements","RouteViewRoot","hasBeenActivatedRef","useRef","useMemo","collected","route","useEffect","RouteView","NOOP_INSTANCE","createDirectionTracker","popstateFlag","transitionInFlight","armedMidTransition","landsOnRouterState","state","router","buildUrl","hash","url","onPopstate","api","getPluginApi","onSettled","unsubs","events","unsub","useRouteExit","handlerRef","handler","skipSameRoute","options","useLayoutEffect","guardLeaveListener","context","useRouteEnter","gate","useState","createRouteEnterGate","previousRoute"],"sources":["../../src/components/modern/RouteView/components.tsx","../../src/components/modern/RouteView/helpers.tsx","../../src/components/modern/RouteView/RouteView.tsx","../../../../shared/dom-utils/direction-tracker.ts","../../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 { events } from \"@real-router/core\";\nimport { getPluginApi } from \"@real-router/core/api\";\n\nimport type { Params, Router, SearchParams } from \"@real-router/core\";\n\ntype BuildUrl = (\n name: string,\n params: Params,\n search?: SearchParams,\n options?: { hash?: string },\n) => string | undefined;\n\nexport interface DirectionTracker {\n destroy: () => void;\n}\n\nconst NOOP_INSTANCE: DirectionTracker = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\n/**\n * Track navigation direction (forward / back) and write it to\n * `<html data-nav-direction>` on every leave. CSS / JS readers consume\n * the attribute via `html[data-nav-direction=\"back\"]` selectors or\n * `document.documentElement.dataset.navDirection`.\n *\n * Mechanism-agnostic — works identically whether downstream UI uses CSS\n * `@keyframes`, View Transitions pseudo-elements, or library state\n * (motion's `motion.div initial={{ x: ... }}`).\n *\n * Implementation:\n * - On install, set `data-nav-direction=\"forward\"` baseline.\n * - Attach a `popstate` listener that flips an internal flag to\n * `true`. Browser back/forward navigation triggers popstate; user\n * clicks on `<Link>` / programmatic `router.navigate(...)` do not.\n * - On every `subscribeLeave`, write\n * `popstateFlag ? \"back\" : \"forward\"` and reset the flag.\n *\n * Returns `{ destroy }` to clean up the listener and clear the dataset\n * attribute.\n */\nexport function createDirectionTracker(router: Router): DirectionTracker {\n if (typeof document === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n let popstateFlag = false;\n\n document.documentElement.dataset.navDirection = \"forward\";\n\n let transitionInFlight = false;\n let armedMidTransition = false;\n\n // ⚑ The flag is SPENT by the transition it belongs to, whether or not that\n // transition reaches a leave phase (#1924). It is armed by any `popstate` on\n // `globalThis`, not only one the router consumes, so `history.back()` onto an\n // entry that resolves to the current state — core answers `SAME_STATES`, and\n // measured, that arc emits `TRANSITION_ERROR` with no `TRANSITION_START` and\n // no leave — would otherwise leave it armed indefinitely and publish the next\n // FORWARD navigation as \"back\".\n //\n // ⚠ A clock has no correct value to be set to. The leave phase is separated\n // from its popstate by every deactivation guard, and a guard may await\n // anything; the plugin also DEFERS a popstate that arrives during an\n // in-flight transition and replays it from that transition's `finally`. The\n // gap has no upper bound. Measured on the obvious choice: a task-boundary\n // expiry disarms a live navigation on ONE async `canDeactivate`.\n // ⚑ A traversal onto the URL of the router's own state starts no\n // transition: a URL plugin's return after a refused Back or Forward\n // (#2740), or a Back onto an entry holding that state. The URL comes from\n // the URL plugin's `buildUrl`; without one, every popstate arms the flag.\n const landsOnRouterState = (): boolean => {\n const state = router.getState();\n const buildUrl = router.buildUrl as BuildUrl | undefined;\n\n if (state === undefined || buildUrl === undefined) {\n return false;\n }\n\n try {\n const hash = (state.context as { url?: { hash?: string } } | undefined)\n ?.url?.hash;\n const url = buildUrl(\n state.name,\n state.params,\n state.search,\n hash ? { hash } : undefined,\n );\n\n return (\n url !== undefined &&\n new URL(url, globalThis.location.href).href === globalThis.location.href\n );\n } catch {\n return false;\n }\n };\n\n const onPopstate = (): void => {\n if (landsOnRouterState()) {\n return;\n }\n\n popstateFlag = true;\n // A deferred event belongs to the replay, not to the transition running\n // now, so that transition's terminal event must not spend it.\n armedMidTransition = transitionInFlight;\n };\n\n // IMPORTANT — listener-ordering: `popstate` fires on `window`, which\n // has no DOM descendants, so capture phase is moot. Listeners are\n // dispatched in registration order. To beat the browser-plugin's own\n // popstate handler, this tracker must be installed **before**\n // `router.usePlugin(browserPluginFactory())` in user code. Otherwise\n // the plugin's handler runs first and synchronously fires\n // `subscribeLeave` while `popstateFlag` is still `false`.\n globalThis.addEventListener(\"popstate\", onPopstate);\n\n const api = getPluginApi(router);\n\n const onSettled = (): void => {\n transitionInFlight = false;\n\n if (armedMidTransition) {\n armedMidTransition = false;\n\n return;\n }\n\n popstateFlag = false;\n };\n\n const unsubs = [\n api.addEventListener(events.TRANSITION_START, () => {\n transitionInFlight = true;\n }),\n api.addEventListener(events.TRANSITION_SUCCESS, onSettled),\n api.addEventListener(events.TRANSITION_ERROR, onSettled),\n api.addEventListener(events.TRANSITION_CANCEL, onSettled),\n router.subscribeLeave(() => {\n document.documentElement.dataset.navDirection = popstateFlag\n ? \"back\"\n : \"forward\";\n popstateFlag = false;\n armedMidTransition = false;\n }),\n ];\n\n return {\n destroy: () => {\n for (const unsub of unsubs) {\n unsub();\n }\n\n globalThis.removeEventListener(\"popstate\", onPopstate);\n delete document.documentElement.dataset.navDirection;\n },\n };\n}\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":"kqBAEA,SAAgBU,EAAM,EAA0B,CAC9C,OAAO,IACT,CAEA,EAAM,YAAc,kBAEpB,SAAgBC,EAAK,EAAyB,CAC5C,OAAO,IACT,CAEA,EAAK,YAAc,iBAEnB,SAAgBC,EAAS,EAA6B,CACpD,OAAO,IACT,CAEA,EAAS,YAAc,qBCTvB,MAAMC,EAAqC,IAAI,IAAI,CAACH,EAAOC,EAAMC,CAAQ,CAAC,EAgB1E,SAASE,EACP,EACA,EACA,EACS,CAST,OARIC,IAAoB,GACf,GAGLC,EACKC,IAAcF,EAGhBG,EAAkBD,EAAWF,CAAe,CACrD,CAEA,SAAgBI,EACd,EACA,EACM,CAYNC,EAAS,QAAQC,EAAW,GAAU,CAC/BC,EAAeC,CAAK,IAIrBV,EAAa,IAAIU,EAAM,IAAI,EAC7BC,EAAO,KAAKD,CAAK,EAEjBJ,EACGI,EAAM,MAA2C,SAClDC,CACF,EAEJ,CAAC,CACH,CAEA,SAASC,EACP,EACA,EACA,EACA,EACA,EACc,CACd,IAAMC,EACJC,IAAa,IAAA,GACXC,EAEAC,EAACC,EAAD,CAAoB,WAAW,SAAAF,CAAuB,CAAA,EAW1D,OARIG,EAEAF,EAACG,EAAD,CAAgB,OACb,SAAAN,CACO,EAFiBO,CAEjB,EAIPJ,EAACK,EAAD,CAAA,SAAqBR,CAAkB,EAAxBO,CAAwB,CAChD,CAEA,SAASE,EAAe,EAAqB,EAA+B,CAwB1E,OAvBIZ,EAAM,OAASX,GAIjB,AAEEwB,EAAM,iBADN,EAAM,iBAAoBb,EAAM,MAAwB,SAClC,IAGjB,IAGLA,EAAM,OAAS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AAsB,CACpB,EAAW,QAAUH,CACvB,CAAC,EAEDtB,MAKSS,EAAO,eACZiB,EAAoB,GAAYL,EAAW,QAAQM,CAAO,EAAG,CAC3D,eACF,CAAC,CACH,EACC,CAAClB,EAAQc,CAAa,CAAC,CAC5B,CChEA,SAAgBK,EACd,EACA,EACM,CACN,GAAM,CAAE,QAAO,iBAAkBnF,EAAS,EACpC4E,EAAazB,EAAO0B,CAAO,EAW3B,CAACO,GAAQC,MAAeC,EAAqB,CAAC,EAC9CR,EAAgBC,GAAS,eAAiB,GAKhDC,MAAsB,CACpB,EAAW,QAAUH,CACvB,CAAC,EAEDtB,MAAgB,CACd,IAAM2B,EAAUE,EAAK9B,EAAOiC,EAAeT,CAAa,EAEpDI,GACFN,EAAW,QAAQM,CAAO,CAE9B,EAAG,CAACE,EAAM9B,EAAOiC,EAAeT,CAAa,CAAC,CAChD"}
@@ -1 +1 @@
1
- {"version":3,"file":"ink.mjs","names":[],"sources":["../../src/components/InkLink.tsx","../../src/components/InkRouterProvider.tsx"],"sourcesContent":["import { Text, useFocus, useInput } from \"ink\";\nimport { memo } from \"react\";\n\nimport { EMPTY_OPTIONS, EMPTY_PARAMS } from \"../constants\";\nimport { shallowEqual } from \"../dom-utils\";\nimport { useIsActiveRoute } from \"../hooks/useIsActiveRoute\";\nimport { useRouter } from \"../hooks/useRouter\";\n\nimport type { InkLinkProps } from \"../ink-types\";\nimport type { FC } from \"react\";\n\n/**\n * Pick the most specific value across focus / active / base priority.\n * Focus wins over active; active wins over base. Each layer falls through\n * to the next when its value is undefined, matching the original explicit\n * if/else cascade for both `color` and `inverse`.\n */\nfunction pickPriority<T>(\n isFocused: boolean,\n isRouteActive: boolean,\n focusValue: T | undefined,\n activeValue: T | undefined,\n baseValue: T | undefined,\n): T | undefined {\n if (isFocused) {\n return focusValue ?? activeValue ?? baseValue;\n }\n\n if (isRouteActive) {\n return activeValue ?? baseValue;\n }\n\n return baseValue;\n}\n\nfunction areInkLinkPropsEqual(\n prev: Readonly<InkLinkProps>,\n next: Readonly<InkLinkProps>,\n): boolean {\n return (\n prev.routeName === next.routeName &&\n prev.activeStrict === next.activeStrict &&\n prev.ignoreQueryParams === next.ignoreQueryParams &&\n prev.color === next.color &&\n prev.activeColor === next.activeColor &&\n prev.focusColor === next.focusColor &&\n prev.inverse === next.inverse &&\n prev.activeInverse === next.activeInverse &&\n prev.focusInverse === next.focusInverse &&\n prev.id === next.id &&\n prev.autoFocus === next.autoFocus &&\n prev.onSelect === next.onSelect &&\n prev.children === next.children &&\n shallowEqual(prev.routeParams, next.routeParams) &&\n shallowEqual(prev.routeSearch, next.routeSearch) &&\n shallowEqual(prev.routeOptions, next.routeOptions)\n );\n}\n\nconst InkLinkImpl: FC<InkLinkProps> = ({\n routeName,\n routeParams,\n routeSearch,\n routeOptions = EMPTY_OPTIONS,\n activeStrict = false,\n ignoreQueryParams = true,\n color,\n activeColor,\n focusColor,\n inverse,\n activeInverse,\n focusInverse,\n id,\n autoFocus,\n onSelect,\n children,\n}) => {\n const router = useRouter();\n const { isFocused } = useFocus({\n ...(id !== undefined && { id }),\n ...(autoFocus !== undefined && { autoFocus }),\n });\n\n // Pass `routeParams` straight through (possibly `undefined`) so a no-params\n // `<InkLink>` and a manual `useIsActiveRoute(routeName)` share ONE cached\n // active-route source — `createActiveRouteSource` keys `undefined` as \"\" but\n // EMPTY_PARAMS ({}) as \"{}\", so defaulting before the call would split the\n // same question into a second eager subscription (#776).\n const isRouteActive = useIsActiveRoute(\n routeName,\n routeParams,\n routeSearch,\n activeStrict,\n ignoreQueryParams,\n );\n\n // Navigation needs a concrete params object — default here only.\n const paramsForNav = routeParams ?? EMPTY_PARAMS;\n\n // No useCallback: `useInput` consumes the handler via its own internal\n // ref; a stable identity provides no cache-bail-out benefit here. Same\n // reasoning as Link's handleClick.\n useInput(\n (_input, key) => {\n if (key.return) {\n // Isolate a throwing `onSelect`: unlike the DOM `<Link>` (where the\n // browser contains event-listener exceptions), an uncaught throw here\n // escapes into ink's stdin handler → `uncaughtException` crashes a real\n // CLI, and it also swallows the navigation below. Log and still\n // navigate — mirrors `route-announcer`'s consumer-callback isolation.\n try {\n onSelect?.();\n } catch (error) {\n console.error(\n \"[real-router] InkLink onSelect threw; proceeding with navigation.\",\n error,\n );\n }\n // Query channel at position 3 (RFC-4 M2 / #1548) — from `routeSearch`;\n // options at position 4.\n router\n .navigate(routeName, paramsForNav, routeSearch, routeOptions)\n .catch(() => {});\n }\n },\n { isActive: isFocused },\n );\n\n const finalColor = pickPriority(\n isFocused,\n isRouteActive,\n focusColor,\n activeColor,\n color,\n );\n const finalInverse = pickPriority(\n isFocused,\n isRouteActive,\n focusInverse,\n activeInverse,\n inverse,\n );\n\n const textProps: { color?: string; inverse?: boolean } = {};\n\n if (finalColor !== undefined) {\n textProps.color = finalColor;\n }\n\n if (finalInverse !== undefined) {\n textProps.inverse = finalInverse;\n }\n\n return <Text {...textProps}>{children}</Text>;\n};\n\nexport const InkLink: FC<InkLinkProps> = memo(\n InkLinkImpl,\n areInkLinkPropsEqual,\n);\n\nInkLink.displayName = \"InkLink\";\n","import { RouterProviderCore } from \"../RouterProviderCore\";\n\nimport type { InkRouterProviderProps } from \"../ink-types\";\nimport type { FC } from \"react\";\n\n// Composes the DOM-free RouterProviderCore (not the full RouterProvider) so the\n// terminal /ink chunk never pulls in the scroll-spy / view-transitions /\n// announcer / scroll-restore factories — none can run without a DOM (#800).\nexport const InkRouterProvider: FC<InkRouterProviderProps> = ({\n router,\n children,\n}) => <RouterProviderCore router={router}>{children}</RouterProviderCore>;\n"],"mappings":"oSAiBA,SAAS,EACP,EACA,EACA,EACA,EACA,EACe,CASf,OARI,EACK,GAAc,GAAe,EAGlC,EACK,GAAe,EAGjB,CACT,CAEA,SAAS,EACP,EACA,EACS,CACT,OACE,EAAK,YAAc,EAAK,WACxB,EAAK,eAAiB,EAAK,cAC3B,EAAK,oBAAsB,EAAK,mBAChC,EAAK,QAAU,EAAK,OACpB,EAAK,cAAgB,EAAK,aA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AA6B,CAAA"}
1
+ {"version":3,"file":"ink.mjs","names":["EMPTY_OPTIONS","EMPTY_PARAMS","useRoute","RouterErrorBoundary","shallowEqual","useRouter","useNavigator","useRouteNode","useRouterTransition","useIsActiveRoute","useRouteUtils","RouterProviderCore","pickPriority","isFocused","focusValue","activeValue","baseValue","isRouteActive","areInkLinkPropsEqual","prev","next","InkLink","memo","router","useFocus","id","autoFocus","routeName","routeParams","routeSearch","activeStrict","ignoreQueryParams","paramsForNav","useInput","key","onSelect","error","routeOptions","finalColor","focusColor","activeColor","color","finalInverse","focusInverse","activeInverse","inverse","textProps","jsx","Text","InkRouterProvider"],"sources":["../../src/components/InkLink.tsx","../../src/components/InkRouterProvider.tsx"],"sourcesContent":["import { Text, useFocus, useInput } from \"ink\";\nimport { memo } from \"react\";\n\nimport { EMPTY_OPTIONS, EMPTY_PARAMS } from \"../constants\";\nimport { shallowEqual } from \"../dom-utils\";\nimport { useIsActiveRoute } from \"../hooks/useIsActiveRoute\";\nimport { useRouter } from \"../hooks/useRouter\";\n\nimport type { InkLinkProps } from \"../ink-types\";\nimport type { FC } from \"react\";\n\n/**\n * Pick the most specific value across focus / active / base priority.\n * Focus wins over active; active wins over base. Each layer falls through\n * to the next when its value is undefined, matching the original explicit\n * if/else cascade for both `color` and `inverse`.\n */\nfunction pickPriority<T>(\n isFocused: boolean,\n isRouteActive: boolean,\n focusValue: T | undefined,\n activeValue: T | undefined,\n baseValue: T | undefined,\n): T | undefined {\n if (isFocused) {\n return focusValue ?? activeValue ?? baseValue;\n }\n\n if (isRouteActive) {\n return activeValue ?? baseValue;\n }\n\n return baseValue;\n}\n\nfunction areInkLinkPropsEqual(\n prev: Readonly<InkLinkProps>,\n next: Readonly<InkLinkProps>,\n): boolean {\n return (\n prev.routeName === next.routeName &&\n prev.activeStrict === next.activeStrict &&\n prev.ignoreQueryParams === next.ignoreQueryParams &&\n prev.color === next.color &&\n prev.activeColor === next.activeColor &&\n prev.focusColor === next.focusColor &&\n prev.inverse === next.inverse &&\n prev.activeInverse === next.activeInverse &&\n prev.focusInverse === next.focusInverse &&\n prev.id === next.id &&\n prev.autoFocus === next.autoFocus &&\n prev.onSelect === next.onSelect &&\n prev.children === next.children &&\n shallowEqual(prev.routeParams, next.routeParams) &&\n shallowEqual(prev.routeSearch, next.routeSearch) &&\n shallowEqual(prev.routeOptions, next.routeOptions)\n );\n}\n\nconst InkLinkImpl: FC<InkLinkProps> = ({\n routeName,\n routeParams,\n routeSearch,\n routeOptions = EMPTY_OPTIONS,\n activeStrict = false,\n ignoreQueryParams = true,\n color,\n activeColor,\n focusColor,\n inverse,\n activeInverse,\n focusInverse,\n id,\n autoFocus,\n onSelect,\n children,\n}) => {\n const router = useRouter();\n const { isFocused } = useFocus({\n ...(id !== undefined && { id }),\n ...(autoFocus !== undefined && { autoFocus }),\n });\n\n // Pass `routeParams` straight through (possibly `undefined`) so a no-params\n // `<InkLink>` and a manual `useIsActiveRoute(routeName)` share ONE cached\n // active-route source — `createActiveRouteSource` keys `undefined` as \"\" but\n // EMPTY_PARAMS ({}) as \"{}\", so defaulting before the call would split the\n // same question into a second eager subscription (#776).\n const isRouteActive = useIsActiveRoute(\n routeName,\n routeParams,\n routeSearch,\n activeStrict,\n ignoreQueryParams,\n );\n\n // Navigation needs a concrete params object — default here only.\n const paramsForNav = routeParams ?? EMPTY_PARAMS;\n\n // No useCallback: `useInput` consumes the handler via its own internal\n // ref; a stable identity provides no cache-bail-out benefit here. Same\n // reasoning as Link's handleClick.\n useInput(\n (_input, key) => {\n if (key.return) {\n // Isolate a throwing `onSelect`: unlike the DOM `<Link>` (where the\n // browser contains event-listener exceptions), an uncaught throw here\n // escapes into ink's stdin handler → `uncaughtException` crashes a real\n // CLI, and it also swallows the navigation below. Log and still\n // navigate — mirrors `route-announcer`'s consumer-callback isolation.\n try {\n onSelect?.();\n } catch (error) {\n console.error(\n \"[real-router] InkLink onSelect threw; proceeding with navigation.\",\n error,\n );\n }\n // Query channel at position 3 (RFC-4 M2 / #1548) — from `routeSearch`;\n // options at position 4.\n router\n .navigate(routeName, paramsForNav, routeSearch, routeOptions)\n .catch(() => {});\n }\n },\n { isActive: isFocused },\n );\n\n const finalColor = pickPriority(\n isFocused,\n isRouteActive,\n focusColor,\n activeColor,\n color,\n );\n const finalInverse = pickPriority(\n isFocused,\n isRouteActive,\n focusInverse,\n activeInverse,\n inverse,\n );\n\n const textProps: { color?: string; inverse?: boolean } = {};\n\n if (finalColor !== undefined) {\n textProps.color = finalColor;\n }\n\n if (finalInverse !== undefined) {\n textProps.inverse = finalInverse;\n }\n\n return <Text {...textProps}>{children}</Text>;\n};\n\nexport const InkLink: FC<InkLinkProps> = memo(\n InkLinkImpl,\n areInkLinkPropsEqual,\n);\n\nInkLink.displayName = \"InkLink\";\n","import { RouterProviderCore } from \"../RouterProviderCore\";\n\nimport type { InkRouterProviderProps } from \"../ink-types\";\nimport type { FC } from \"react\";\n\n// Composes the DOM-free RouterProviderCore (not the full RouterProvider) so the\n// terminal /ink chunk never pulls in the scroll-spy / view-transitions /\n// announcer / scroll-restore factories — none can run without a DOM (#800).\nexport const InkRouterProvider: FC<InkRouterProviderProps> = ({\n router,\n children,\n}) => <RouterProviderCore router={router}>{children}</RouterProviderCore>;\n"],"mappings":"oSAiBA,SAASY,EACP,EACA,EACA,EACA,EACA,EACe,CASf,OARIC,EACKC,GAAcC,GAAeC,EAGlCC,EACKF,GAAeC,EAGjBA,CACT,CAEA,SAASE,EACP,EACA,EACS,CACT,OACEC,EAAK,YAAcC,EAAK,WACxBD,EAAK,eAAiBC,EAAK,cAC3BD,EAAK,oBAAsBC,EAAK,mBAChCD,EAAK,QAAUC,EAAK,OACpBD,EAAK,cAAgBC,EAAK,aAC1BD,EAAK,aAAeC,EAAK,YACzBD,EAAK,UAAYC,EAAK,SACtBD,EAAK,gBAAkBC,EAAK,eAC5BD,EAAK,eAAiBC,EAAK,cAC3BD,EAAK,KAAOC,EAAK,IACjBD,EAAK,YAAcC,EAAK,WACxBD,EAA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inkProps, t as RouterErrorBoundary } from "./RouterErrorBoundary-DZI_DkW5.mjs";
2
- import { i as Link, t as RouterProvider } from "./RouterProvider-BixslYdB.mjs";
2
+ import { i as Link, t as RouterProvider } from "./RouterProvider-BhOgl2jd.mjs";
3
3
  import { a as useNavigator, i as useRouteUtils, n as useRouteNode, o as useRouter, r as useRoute, t as useRouterTransition } from "./useRouterTransition-YvPtN5pW.mjs";
4
4
  import { Navigator } from "@real-router/core";
5
5
  import { RouterTransitionSnapshot } from "@real-router/sources";
@@ -1 +1 @@
1
- {"version":3,"file":"ssr.mjs","names":[],"sources":["../../src/components/Await.tsx"],"sourcesContent":["import { use } from \"react\";\n\nimport { useDeferred } from \"../hooks/useDeferred\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface AwaitProps<T> {\n /** Deferred key declared in the loader's `defer({ deferred: { <name>: ... } })`. */\n readonly name: string;\n /** Render the resolved value. Suspends while pending; throws inside the\n * nearest Error Boundary on rejection. */\n readonly children: (value: T) => ReactNode;\n}\n\n/**\n * Ergonomic wrapper around `useDeferred(name)` + React 19's `use(promise)`.\n *\n * ```tsx\n * <Suspense fallback={<Spinner />}>\n * <Await<Review[]> name=\"reviews\">\n * {(reviews) => <ReviewList items={reviews} />}\n * </Await>\n * </Suspense>\n * ```\n *\n * Equivalent to:\n *\n * ```tsx\n * function Inner() {\n * const reviews = use(useDeferred<Review[]>(\"reviews\"));\n * return <ReviewList items={reviews} />;\n * }\n * ```\n *\n * Pick `<Await>` for cross-adapter consistency with the SvelteKit\n * `{#await}` / Solid `<Await/>` shape; pick the inline `use(useDeferred(...))`\n * form if you prefer one fewer abstraction.\n */\nexport function Await<T = unknown>({\n name,\n children,\n}: AwaitProps<T>): ReactNode {\n const value = use(useDeferred<T>(name));\n\n return children(value);\n}\n"],"mappings":"yHAsCA,SAAgB,EAAmB,CACjC,OACA,YAC2B,CAG3B,OAAO,EAFO,EAAI,EAAe,CAAI,CAEjB,CAAC,CACvB"}
1
+ {"version":3,"file":"ssr.mjs","names":["useDeferred","Streamed","ServerOnly","HttpStatusProvider","ClientOnly","createHttpStatusSink","Await","children","use","name","HttpStatusCode"],"sources":["../../src/components/Await.tsx"],"sourcesContent":["import { use } from \"react\";\n\nimport { useDeferred } from \"../hooks/useDeferred\";\n\nimport type { ReactNode } from \"react\";\n\nexport interface AwaitProps<T> {\n /** Deferred key declared in the loader's `defer({ deferred: { <name>: ... } })`. */\n readonly name: string;\n /** Render the resolved value. Suspends while pending; throws inside the\n * nearest Error Boundary on rejection. */\n readonly children: (value: T) => ReactNode;\n}\n\n/**\n * Ergonomic wrapper around `useDeferred(name)` + React 19's `use(promise)`.\n *\n * ```tsx\n * <Suspense fallback={<Spinner />}>\n * <Await<Review[]> name=\"reviews\">\n * {(reviews) => <ReviewList items={reviews} />}\n * </Await>\n * </Suspense>\n * ```\n *\n * Equivalent to:\n *\n * ```tsx\n * function Inner() {\n * const reviews = use(useDeferred<Review[]>(\"reviews\"));\n * return <ReviewList items={reviews} />;\n * }\n * ```\n *\n * Pick `<Await>` for cross-adapter consistency with the SvelteKit\n * `{#await}` / Solid `<Await/>` shape; pick the inline `use(useDeferred(...))`\n * form if you prefer one fewer abstraction.\n */\nexport function Await<T = unknown>({\n name,\n children,\n}: AwaitProps<T>): ReactNode {\n const value = use(useDeferred<T>(name));\n\n return children(value);\n}\n"],"mappings":"yHAsCA,SAAgBM,EAAmB,CACjC,OACA,YAC2B,CAG3B,OAAOC,EAFOC,EAAIR,EAAeS,CAAI,CAEjB,CAAC,CACvB"}