@real-router/vue 0.19.30 → 0.19.32

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":"index.js","names":["Fragment","UNKNOWN_ROUTE","RouterKey","suspenseComponent","KeepAlive","Fragment","NOOP_INSTANCE","objectKeys","NOOP_INSTANCE","NOOP_INSTANCE","Fragment","NavigatorKey","useRoute","RouterKey","NavigatorKey","RouteKey","RouterKey","NavigatorKey","RouteKey"],"sources":["../../src/components/RouteView/components.ts","../../src/components/RouteView/helpers.ts","../../src/useRefFromSource.ts","../../src/composables/useRouter.ts","../../src/composables/useRouteNode.ts","../../src/components/RouteView/RouteView.ts","../../src/constants.ts","../../../../shared/dom-utils/route-announcer.ts","../../../../shared/dom-utils/scroll-restore.ts","../../../../shared/dom-utils/scroll-spy.ts","../../../../shared/dom-utils/view-transitions.ts","../../../../shared/dom-utils/link-utils.ts","../../src/components/Link.ts","../../src/components/RouterErrorBoundary.ts","../../src/directives/vLink.ts","../../src/composables/useNavigator.ts","../../src/composables/useRouteUtils.ts","../../src/composables/useRouterTransition.ts","../../src/composables/useRouteExit.ts","../../src/composables/useRouteEnter.ts","../../src/setupRouteProvision.ts","../../src/createRouterPlugin.ts","../../src/RouterProvider.ts"],"sourcesContent":["import { defineComponent } from \"vue\";\n\nimport type { SelfProps } from \"./types\";\nimport type { FunctionalComponent, PropType, VNode } from \"vue\";\n\nfunction renderNull() {\n return null;\n}\n\nexport const Match = defineComponent({\n name: \"RouteView.Match\",\n props: {\n segment: {\n type: String as PropType<string>,\n required: true,\n },\n exact: {\n type: Boolean,\n default: false,\n },\n fallback: {\n type: [Object, Function] as PropType<VNode | (() => VNode)>,\n default: undefined,\n },\n keepAlive: {\n type: Boolean,\n default: false,\n },\n },\n render: renderNull,\n});\n\n// Type Self via FunctionalComponent<SelfProps> so the SelfProps interface\n// is anchored to the component contract — knip otherwise flags SelfProps\n// as unused even though it's re-exported as RouteViewSelfProps for\n// consumers wrapping Self in custom HOCs.\nconst SelfImpl = defineComponent({\n name: \"RouteView.Self\",\n props: {\n fallback: {\n type: [Object, Function] as PropType<VNode | (() => VNode)>,\n default: undefined,\n },\n },\n render: renderNull,\n});\n\nexport const Self = SelfImpl as unknown as FunctionalComponent<SelfProps>;\n\nexport const NotFound = defineComponent({\n name: \"RouteView.NotFound\",\n render: renderNull,\n});\n","import { UNKNOWN_ROUTE } from \"@real-router/core\";\nimport { startsWithSegment } from \"@real-router/route-utils\";\nimport { Fragment, isVNode } from \"vue\";\n\nimport { Match, NotFound, Self } from \"./components\";\n\nimport type { VNode } from \"vue\";\n\nconst MARKER_TYPES: ReadonlySet<unknown> = new Set([Match, Self, NotFound]);\nconst KEEP_ALIVE_VALUES: ReadonlySet<unknown> = new Set([\n true,\n \"\",\n \"keep-alive\",\n]);\n\ntype FallbackType = VNode | (() => VNode) | undefined;\n\ninterface FallbackSlots {\n selfVNode: VNode | null;\n selfFallback: FallbackType;\n notFoundVNode: VNode | null;\n}\n\nexport function isSegmentMatch(\n routeName: string,\n fullSegmentName: string,\n exact: boolean,\n): boolean {\n if (exact) {\n return routeName === fullSegmentName;\n }\n\n return startsWithSegment(routeName, fullSegmentName);\n}\n\n// Vue compiles boolean-shorthand template attributes (`<Match keepAlive>`) to\n// an empty string instead of `true`, and converts them to `true` only when the\n// receiving component's prop is declared with `type: Boolean`. `Match` is a\n// marker component (`render: null`) — its props are inspected on the VNode\n// without ever going through Vue's prop-casting pipeline, so the raw `\"\"` (or\n// the hyphenated attribute name) reaches us here. Accept the same trio Vue's\n// runtime does.\nexport function isKeepAliveEnabled(value: unknown): boolean {\n return KEEP_ALIVE_VALUES.has(value);\n}\n\nfunction normalizeChildren(children: unknown): VNode[] {\n if (Array.isArray(children)) {\n const result: VNode[] = [];\n\n for (const child of children) {\n if (Array.isArray(child)) {\n result.push(...normalizeChildren(child));\n } else if (isVNode(child)) {\n result.push(child);\n }\n }\n\n return result;\n }\n\n if (isVNode(children)) {\n return [children];\n }\n\n return [];\n}\n\nexport function collectElements(children: unknown, result: VNode[]): void {\n const vnodes = normalizeChildren(children);\n\n for (const child of vnodes) {\n if (MARKER_TYPES.has(child.type)) {\n result.push(child);\n } else if (child.type === Fragment) {\n collectElements(child.children, result);\n }\n }\n}\n\nfunction recordFallback(child: VNode, slots: FallbackSlots): boolean {\n if (child.type === NotFound) {\n // First-wins: store the FIRST NotFound VNode, ignore later ones — symmetric\n // with <Self> below and the React/Preact/Solid adapters (#1439). Store the\n // VNode (never null for a real marker), not `child.children` (null for a\n // childless <NotFound/>), so the assign-once guard cannot be defeated.\n slots.notFoundVNode ??= child;\n\n return true;\n }\n\n if (child.type === Self) {\n if (slots.selfVNode === null) {\n slots.selfVNode = child;\n const props = child.props as { fallback?: FallbackType } | null;\n\n slots.selfFallback = props?.fallback;\n }\n\n return true;\n }\n\n return false;\n}\n\nfunction evaluateMatch(\n child: VNode,\n routeName: string,\n nodeName: string,\n): { isActive: boolean; fallback: FallbackType } {\n const props = child.props as {\n segment: string;\n exact?: boolean;\n fallback?: FallbackType;\n } | null;\n const segment = props?.segment ?? \"\";\n const exact = props?.exact ?? false;\n const fullSegmentName = nodeName ? `${nodeName}.${segment}` : segment;\n const isActive = isSegmentMatch(routeName, fullSegmentName, exact);\n\n return { isActive, fallback: props?.fallback };\n}\n\nfunction appendFallback(\n rendered: VNode[],\n routeName: string,\n nodeName: string,\n slots: FallbackSlots,\n): FallbackType {\n if (slots.selfVNode !== null && routeName === nodeName) {\n rendered.push(slots.selfVNode);\n\n return slots.selfFallback;\n }\n\n if (routeName === UNKNOWN_ROUTE && slots.notFoundVNode !== null) {\n rendered.push(slots.notFoundVNode);\n }\n\n return undefined;\n}\n\nexport function buildRenderList(\n elements: VNode[],\n routeName: string,\n nodeName: string,\n): {\n rendered: VNode[];\n activeMatchFound: boolean;\n fallback?: FallbackType;\n /**\n * True iff any `<Match>` child in the input has its `keepAlive` prop set\n * to one of Vue's accepted boolean-shorthand forms. Surfaced as a\n * side-channel from the single pipeline pass so the caller doesn't have\n * to re-iterate `elements` after `buildRenderList` returns — closes a MED\n * code-quality finding (audit §8.1).\n */\n hasPerMatchKA: boolean;\n} {\n const slots: FallbackSlots = {\n selfVNode: null,\n selfFallback: undefined,\n notFoundVNode: null,\n };\n let activeMatchFound = false;\n let fallback: FallbackType;\n let hasPerMatchKA = false;\n const rendered: VNode[] = [];\n\n for (const child of elements) {\n // Match-only side-channel: scan for the keepAlive shorthand in the same\n // pass that already inspects every child. Short-circuits once a positive\n // is found to avoid redundant prop reads in big slot trees.\n if (!hasPerMatchKA && child.type === Match) {\n const matchProps = child.props as { keepAlive?: unknown } | null;\n\n if (isKeepAliveEnabled(matchProps?.keepAlive)) {\n hasPerMatchKA = true;\n }\n }\n\n if (recordFallback(child, slots)) {\n continue;\n }\n\n if (activeMatchFound) {\n continue;\n }\n\n const result = evaluateMatch(child, routeName, nodeName);\n\n if (result.isActive) {\n activeMatchFound = true;\n fallback = result.fallback;\n rendered.push(child);\n }\n }\n\n if (!activeMatchFound) {\n fallback = appendFallback(rendered, routeName, nodeName, slots);\n }\n\n return { rendered, activeMatchFound, fallback, hasPerMatchKA };\n}\n","import { shallowRef, onScopeDispose } from \"vue\";\n\nimport type { RouterSource } from \"@real-router/sources\";\nimport type { ShallowRef } from \"vue\";\n\nexport function useRefFromSource<T>(\n // Only `subscribe` + `getSnapshot` are consumed — teardown goes through the\n // `subscribe` unsub via `onScopeDispose`, never `source.destroy`. Narrowing to\n // this shape lets the #1250 name-selector fast path pass a 2-method wrapper\n // (no dead `destroy` needed); full `RouterSource`s still satisfy it.\n source: Pick<RouterSource<T>, \"subscribe\" | \"getSnapshot\">,\n): ShallowRef<T> {\n const ref = shallowRef(source.getSnapshot());\n\n const unsub = source.subscribe(() => {\n ref.value = source.getSnapshot();\n });\n\n onScopeDispose(unsub);\n\n return ref;\n}\n","import { inject } from \"vue\";\n\nimport { RouterKey } from \"../context\";\n\nimport type { Router } from \"@real-router/core\";\n\nexport const useRouter = (): Router => {\n const router = inject(RouterKey);\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 { computed } from \"vue\";\n\nimport { useRefFromSource } from \"../useRefFromSource\";\nimport { useRouter } from \"./useRouter\";\n\nimport type { RouteContext } from \"../types\";\n\nexport function useRouteNode(nodeName: string): RouteContext {\n const router = useRouter();\n\n const source = createRouteNodeSource(router, nodeName);\n const snapshot = useRefFromSource(source);\n\n // getNavigator is WeakMap-cached in core; no useMemo equivalent needed.\n const navigator = getNavigator(router);\n\n // Derive route/previousRoute via computed instead of mirroring with a sync\n // watch into two extra shallowRefs. computed shares snapshot's identity so\n // when the underlying source emits the same reference (idempotent or\n // out-of-node nav), consumers don't see a new ref.\n const route = computed(() => snapshot.value.route);\n const previousRoute = computed(() => snapshot.value.previousRoute);\n\n return {\n navigator,\n route,\n previousRoute,\n };\n}\n","import {\n Fragment,\n defineComponent,\n h,\n KeepAlive,\n markRaw,\n Suspense,\n} from \"vue\";\n\nimport { Match, NotFound, Self } from \"./components\";\nimport {\n buildRenderList,\n collectElements,\n isKeepAliveEnabled,\n} from \"./helpers\";\nimport { useRouteNode } from \"../../composables/useRouteNode\";\n\nimport type { Component, VNode } from \"vue\";\n\ntype SlotChildren = Record<string, (() => VNode[]) | undefined> | null;\n\nfunction getSlotContent(vnode: VNode): VNode[] | null {\n const slots = vnode.children as SlotChildren;\n\n return slots?.default?.() ?? null;\n}\n\nfunction getOrCreateWrapper(\n cache: Map<string, Component>,\n segment: string,\n): Component {\n const existing = cache.get(segment);\n\n if (existing) {\n return existing;\n }\n\n const wrapper = markRaw(\n defineComponent({\n name: `KeepAlive-${segment}`,\n setup(_wrapperProps, wrapperCtx) {\n return () => wrapperCtx.slots.default?.();\n },\n }),\n );\n\n cache.set(segment, wrapper);\n\n return wrapper;\n}\n\nfunction wrapWithSuspense(content: VNode, fallback: unknown): VNode {\n if (fallback === undefined) {\n return content;\n }\n\n const fallbackContent =\n typeof fallback === \"function\" ? (fallback as () => VNode)() : fallback;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment\n const suspenseComponent = Suspense as any;\n\n return h(\n suspenseComponent,\n {},\n {\n default: () => content,\n fallback: () => fallbackContent,\n },\n );\n}\n\n// Lazy-initialised — only allocated when a per-Match keepAlive path needs to\n// keep the cache slot \"occupied\" with a no-render placeholder. Apps without\n// keepAlive never pay the markRaw + defineComponent allocation at import.\nlet emptyKeepAlivePlaceholderInstance: Component | null = null;\n\nfunction getEmptyKeepAlivePlaceholder(): Component {\n emptyKeepAlivePlaceholderInstance ??= markRaw(\n defineComponent({\n name: \"KeepAlive-placeholder\",\n render() {\n return null;\n },\n }),\n );\n\n return emptyKeepAlivePlaceholderInstance;\n}\n\nfunction renderWithRootKA(\n activeChild: VNode,\n wrapperCache: Map<string, Component>,\n fallback: unknown,\n): VNode {\n const activeProps = activeChild.props as { segment?: string } | null;\n const segment = activeProps?.segment ?? \"__not-found__\";\n const WrapperComponent = getOrCreateWrapper(wrapperCache, segment);\n const slotContent = getSlotContent(activeChild) ?? [];\n const keepAliveContent = h(KeepAlive, null, {\n default: () =>\n h(WrapperComponent, { key: segment }, { default: () => slotContent }),\n });\n\n return wrapWithSuspense(keepAliveContent, fallback);\n}\n\nfunction renderWithPerMatchKA(\n activeChild: VNode,\n wrapperCache: Map<string, Component>,\n fallback: unknown,\n): VNode | null {\n const matchProps = activeChild.props as {\n segment?: string;\n keepAlive?: unknown;\n } | null;\n\n if (isKeepAliveEnabled(matchProps?.keepAlive) && activeChild.type === Match) {\n /* v8 ignore start */\n const segment = matchProps?.segment ?? \"__not-found__\";\n /* v8 ignore stop */\n const WrapperComponent = getOrCreateWrapper(wrapperCache, segment);\n const slotContent = getSlotContent(activeChild) ?? [];\n\n return h(Fragment, [\n h(KeepAlive, null, {\n default: () =>\n h(WrapperComponent, { key: segment }, { default: () => slotContent }),\n }),\n ]);\n }\n\n const content = getSlotContent(activeChild);\n\n /* v8 ignore start */\n if (!content) {\n return null;\n }\n /* v8 ignore stop */\n\n return h(Fragment, [\n h(KeepAlive, null, {\n default: () => h(getEmptyKeepAlivePlaceholder()),\n }),\n wrapWithSuspense(h(Fragment, content), fallback),\n ]);\n}\n\nconst RouteViewComponent = defineComponent({\n name: \"RouteView\",\n props: {\n nodeName: {\n type: String,\n required: true,\n },\n keepAlive: {\n type: Boolean,\n default: false,\n },\n },\n setup(props, { slots }) {\n const routeContext = useRouteNode(props.nodeName);\n const wrapperCache = new Map<string, Component>();\n\n return (): VNode | null => {\n const route = routeContext.route.value;\n\n if (!route) {\n return null;\n }\n\n const slotOutput = slots.default?.();\n const elements: VNode[] = [];\n\n collectElements(slotOutput, elements);\n\n // `hasPerMatchKA` is a side-channel produced by the same pipeline pass\n // that builds `rendered` — closes the audit §8.1 \"double iteration\"\n // finding. The previous identity-cache on `slotOutput` is no longer\n // needed: per-render cost is one O(n) walk instead of two.\n const { rendered, fallback, hasPerMatchKA } = buildRenderList(\n elements,\n route.name,\n props.nodeName,\n );\n\n if (rendered.length === 0) {\n return null;\n }\n\n const activeChild = rendered[0];\n\n if (props.keepAlive) {\n return renderWithRootKA(activeChild, wrapperCache, fallback);\n }\n\n /* v8 ignore start */\n if (\n activeChild.type !== Match &&\n activeChild.type !== Self &&\n activeChild.type !== NotFound\n ) {\n return null;\n }\n /* v8 ignore stop */\n\n if (hasPerMatchKA) {\n return renderWithPerMatchKA(activeChild, wrapperCache, fallback);\n }\n\n const content = getSlotContent(activeChild);\n\n if (!content) {\n return null;\n }\n\n return wrapWithSuspense(h(Fragment, content), fallback);\n };\n },\n});\n\nexport const RouteView = Object.assign(RouteViewComponent, {\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","/**\n * Stable empty object for default params\n */\nexport const EMPTY_PARAMS = Object.freeze({});\n\n/**\n * Stable empty options object\n */\nexport const EMPTY_OPTIONS = Object.freeze({});\n","import type { Router, State } from \"@real-router/core\";\n\nconst CLEAR_DELAY = 7000;\nconst SAFARI_READY_DELAY = 100;\nconst ANNOUNCER_ATTR = \"data-real-router-announcer\";\nconst INTERNAL_ROUTE_PREFIX = \"@@\";\nconst VISUALLY_HIDDEN =\n \"position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);clip-path:inset(50%);white-space:nowrap;border:0\";\n\nexport interface RouteAnnouncerOptions {\n prefix?: string;\n getAnnouncementText?: (route: State) => string;\n}\n\nconst NOOP_INSTANCE: { destroy: () => void } = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\n// Live (non-NOOP) instances sharing the single `[data-real-router-announcer]`\n// aria-live element. The element is created once by the first instance\n// (`getOrCreateAnnouncer`) and reused by the rest; it must be removed only when\n// the LAST holder is destroyed. Without this count the first provider's\n// destroy() would detach the shared node while sibling providers (micro-\n// frontends — the same multi-provider scenario `scroll-restore`'s `storageKey`\n// exists for) keep writing to the now-orphaned node → silent screen reader (#783).\nlet announcerRefCount = 0;\n// Generation token (#1217): bumped each time a FRESH shared element is created.\n// Each instance captures the generation live at construction; on destroy it\n// touches the shared refcount / element ONLY if its generation is still current.\n// A stale instance — whose element a host wiped without calling destroy() — must\n// not decrement the new generation's refcount (→ negative) or remove its live\n// element (removeAnnouncer used to query by selector = whoever is in the DOM).\nlet announcerGeneration = 0;\n\nexport function createRouteAnnouncer(\n router: Router,\n options?: RouteAnnouncerOptions,\n): { destroy: () => void } {\n // Defensive SSR / non-browser guard: in SSR (Node.js) or non-DOM\n // environments, `document` is undefined and the announcer cannot\n // attach its aria-live region. Return a frozen NOOP_INSTANCE — same\n // pattern as `createDirectionTracker`, `createScrollRestoration`, and\n // `createViewTransitions`. Without this guard, `NavigationAnnouncer`\n // component construction would throw `ReferenceError: document is not\n // defined` under `@angular/ssr` rendering, tearing down the whole SSR\n // bootstrap. Closes review-2026-05-10 §5.10 ⛔ \"NavigationAnnouncer\n // SSR mode\" MED.\n if (typeof document === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n const prefix = options?.prefix ?? \"Navigated to \";\n const getCustomText = options?.getAnnouncementText;\n\n let isInitialNavigation = true;\n let isReady = false;\n let isDestroyed = false;\n let lastAnnouncedText = \"\";\n let pendingText: string | null = null;\n let clearTimeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const { element: announcer, generation: myGeneration } =\n getOrCreateAnnouncer();\n\n announcerRefCount += 1;\n\n const doAnnounce = (text: string, h1: HTMLElement | null): void => {\n lastAnnouncedText = text;\n clearTimeout(clearTimeoutId);\n announcer.textContent = text;\n clearTimeoutId = setTimeout(() => {\n announcer.textContent = \"\";\n lastAnnouncedText = \"\";\n }, CLEAR_DELAY);\n\n manageFocus(h1);\n };\n\n // Safari-ready delay: announcing before VoiceOver wires up the aria-live region\n // causes the first announcement to be silently dropped. Wait SAFARI_READY_DELAY ms\n // before marking the announcer \"ready\" — any navigation during that window is\n // buffered in pendingText and flushed once the delay expires.\n const safariTimeoutId = setTimeout(() => {\n isReady = true;\n\n if (pendingText !== null && !isDestroyed) {\n const text = pendingText;\n\n pendingText = null;\n doAnnounce(text, document.querySelector<HTMLElement>(\"h1\"));\n }\n }, SAFARI_READY_DELAY);\n\n const unsubscribe = router.subscribe(({ route }) => {\n if (isInitialNavigation) {\n isInitialNavigation = false;\n\n return;\n }\n\n // Double rAF: waits for two paint frames so the incoming route's DOM\n // (including the new <h1>) is fully rendered before resolveText reads it.\n // Single rAF fires before the new route's template has been attached,\n // which would cause resolveText to pick up the OLD h1 or fall back to\n // document.title / route.name prematurely.\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n if (isDestroyed) {\n return;\n }\n\n const h1 = document.querySelector<HTMLElement>(\"h1\");\n const text = resolveText(route, prefix, getCustomText, h1);\n\n if (!text || text === lastAnnouncedText) {\n return;\n }\n\n if (!isReady) {\n // Defer announcement until Safari-ready window elapses (see safariTimeoutId).\n pendingText = text;\n\n return;\n }\n\n doAnnounce(text, h1);\n });\n });\n });\n\n return {\n destroy() {\n // Idempotency guard — required so the ref-count is decremented EXACTLY\n // once per instance. A double destroy() must not drop the count below the\n // number of live holders (which would detach a sibling's element, or\n // leave it attached forever).\n if (isDestroyed) {\n return;\n }\n\n isDestroyed = true;\n unsubscribe();\n clearTimeout(clearTimeoutId);\n clearTimeout(safariTimeoutId);\n\n // Ownership guard (#1217): if a host wiped the shared element out from\n // under us, the next getOrCreateAnnouncer bumped the generation for the\n // fresh element. A stale instance must NOT decrement the new generation's\n // refcount (→ negative) or remove its live element — bail if not current.\n if (myGeneration !== announcerGeneration) {\n return;\n }\n\n announcerRefCount -= 1;\n\n // Only the last holder tears down the shared element — via our captured\n // ref, not a selector query (which would delete whoever's element is\n // currently in the DOM, i.e. a newer generation's).\n if (announcerRefCount === 0) {\n removeAnnouncer(announcer);\n }\n },\n };\n}\n\nfunction getOrCreateAnnouncer(): {\n element: HTMLElement;\n generation: number;\n} {\n const existing = document.querySelector<HTMLElement>(`[${ANNOUNCER_ATTR}]`);\n\n if (existing) {\n return { element: existing, generation: announcerGeneration };\n }\n\n // Creating a FRESH element means no live instance is validly sharing one, so\n // the ref-count restarts from zero (the caller increments immediately after).\n // Without this, an element removed out from under live instances — a host\n // wiping the subtree, or a consumer test whose teardown clears the DOM\n // without calling every instance's destroy() — would leave a stale positive\n // count that prevents the new element from ever being torn down (#783).\n // The generation bump (#1217) lets the wiped element's instances recognize\n // themselves as stale so their destroy() does not touch this fresh element.\n announcerRefCount = 0;\n announcerGeneration += 1;\n\n const element = document.createElement(\"div\");\n\n element.setAttribute(\"style\", VISUALLY_HIDDEN);\n element.setAttribute(\"aria-live\", \"assertive\");\n element.setAttribute(\"aria-atomic\", \"true\");\n element.setAttribute(ANNOUNCER_ATTR, \"\");\n\n // Defensive SSR / pre-`<body>` guard: in some environments (early\n // injection, deferred-body documents, certain SSR rehydration paths)\n // `document.body` can be null when the announcer is constructed.\n // `document.body.prepend(...)` would throw `TypeError: Cannot read\n // properties of null`, tearing down the consumer's RouterProvider /\n // NavigationAnnouncer mount. Fallback to `documentElement` keeps the\n // announcer working for SR users; visual-hidden styling means there is\n // no visible artifact regardless of mount point.\n //\n // TS dom lib types `document.body` as `HTMLElement` (non-null), but\n // runtime can return null per spec. The `as` cast narrows the type to\n // include null so the `??` short-circuit is type-safe.\n ((document.body as HTMLElement | null) ?? document.documentElement).prepend(\n element,\n );\n\n return { element, generation: announcerGeneration };\n}\n\nfunction removeAnnouncer(element: HTMLElement): void {\n element.remove();\n}\n\nfunction resolveText(\n route: State,\n prefix: string,\n getCustomText: ((route: State) => string) | undefined,\n h1: HTMLElement | null,\n): string {\n if (getCustomText) {\n try {\n const customText = getCustomText(route);\n\n // Mini-sprint E.4 (audit-5 §4.2 #4) — empty-string fallback.\n // A consumer pattern like\n // getAnnouncementText: (route) => myMap[route.name] ?? \"\"\n // returns `\"\"` for routes outside the map. The subscribe loop\n // then sees an empty text and silently no-announces — screen\n // readers stay quiet without any signal to the developer. Treat\n // a falsy custom result (`\"\"` / `null` / `undefined`) as\n // \"consumer doesn't have a name for this route\" and fall through\n // to the default resolution chain (h1 → title → route name).\n if (customText) {\n return customText;\n }\n } catch (error) {\n // A throwing consumer callback inside the router's subscribe loop\n // would tear down sibling listeners — log and fall through to the\n // built-in resolution chain so the announcer keeps working.\n console.error(\n \"[real-router] getAnnouncementText threw; falling back to default resolution.\",\n error,\n );\n }\n }\n\n const h1Text = (h1?.textContent ?? \"\").trim();\n const routeName = route.name.startsWith(INTERNAL_ROUTE_PREFIX)\n ? \"\"\n : route.name;\n const rawText =\n h1Text || document.title || routeName || globalThis.location.pathname;\n\n return `${prefix}${rawText}`;\n}\n\nfunction manageFocus(h1: HTMLElement | null): void {\n if (!h1) {\n return;\n }\n\n if (!h1.hasAttribute(\"tabindex\")) {\n h1.setAttribute(\"tabindex\", \"-1\");\n }\n\n h1.focus({ preventScroll: true });\n}\n","import type { Router, State } from \"@real-router/core\";\n\n/**\n * Intrinsics captured at module load (#1971).\n *\n * ⚑ These DECIDE — they answer \"what is on this object\" for a value this module\n * did not build. Read off the live global they can be re-pointed after boot, and\n * `shared/` is the half where that fails OPEN: measured in `browser-env`, a\n * re-pointed `getPrototypeOf` admits a `Date` into `state.params` and a\n * re-pointed `keys` skips option validation entirely.\n *\n * ⚠ Capture narrows the window from \"any time after boot\" to \"before this module\n * loads\". It does not close it (#1798).\n */\nconst objectKeys = Object.keys;\n\nconst DEFAULT_STORAGE_KEY = \"real-router:scroll\";\n\n// Bounded retry budget for resolving a late-mounting scroll container on the\n// restore path. A per-route container (e.g. an `overflow:auto` div rendered\n// only on one route) can be committed to the DOM a few frames after the\n// navigation settles — heavier routes paint later than the subscribe's rAF.\n// ~10 frames (≈160ms at 60fps) comfortably covers a React commit of a large\n// route without being perceptible. See the doc-block on `restorePos`.\nconst RESTORE_RETRY_FRAMES = 10;\n\nconst NOOP_INSTANCE: { destroy: () => void } = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\nexport type ScrollRestorationMode = \"restore\" | \"top\" | \"native\";\n\nexport interface ScrollRestorationOptions {\n mode?: ScrollRestorationMode | undefined;\n anchorScrolling?: boolean | undefined;\n scrollContainer?: (() => HTMLElement | null) | undefined;\n /**\n * Scroll behavior passed to `scrollTo({ behavior })` and\n * `scrollIntoView({ behavior })`.\n *\n * - `\"auto\"` (default) — browser-defined, usually instant.\n * - `\"instant\"` — explicit instant jump (no animation).\n * - `\"smooth\"` — animated transition. Note: smooth restore on back/traverse\n * can feel disorienting if the user expects to land at the saved position\n * immediately. Recommended for `mode: \"top\"` or anchor scroll only.\n *\n * See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/ScrollToOptions/behavior).\n */\n behavior?: ScrollBehavior | undefined;\n /**\n * sessionStorage key used to persist saved scroll positions. Default:\n * `\"real-router:scroll\"`. Override only when multiple independent\n * `RouterProvider` instances share the same document and you need to\n * isolate their scroll stores (e.g. micro-frontends, embedded widgets,\n * or testing). For a single app with one provider the default is fine.\n */\n storageKey?: string | undefined;\n}\n\ninterface NavigationContext {\n direction?: \"forward\" | \"back\" | \"unknown\";\n navigationType?: \"push\" | \"replace\" | \"traverse\" | \"reload\";\n}\n\nexport function createScrollRestoration(\n router: Router,\n options?: ScrollRestorationOptions,\n): { destroy: () => void } {\n if (typeof globalThis.window === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n const mode = options?.mode ?? \"restore\";\n\n // mode \"native\" = utility does nothing. Don't flip history.scrollRestoration,\n // don't subscribe, don't register pagehide — `history.scrollRestoration`\n // stays at the browser default (\"auto\") so the browser handles scroll\n // restore natively. (Note: this is the OPPOSITE of `history.scrollRestoration\n // === \"manual\"` — utility's \"native\" leaves the DOM property at \"auto\" so\n // the browser is in charge.)\n if (mode === \"native\") {\n return NOOP_INSTANCE;\n }\n\n const anchorEnabled = options?.anchorScrolling ?? true;\n const getContainer = options?.scrollContainer;\n const behavior: ScrollBehavior = options?.behavior ?? \"auto\";\n const storageKey = options?.storageKey ?? DEFAULT_STORAGE_KEY;\n\n // Write-through in-memory cache: parse sessionStorage once per provider\n // mount, then mutate in-memory. Avoids a JSON.parse + JSON.stringify pair\n // on every subscribeLeave / pagehide event.\n let store: Record<string, number> | undefined;\n\n const loadStore = (): Record<string, number> => {\n if (store !== undefined) {\n return store;\n }\n\n // ⚑ A PROTOTYPE-LESS record, and here that is the cheap fix rather than the\n // expensive one (#1852). The key is `${route}:${json}`, so both the\n // skip-same-value READ and the write below consult a chain under a name the\n // page never chose; with no chain there is nothing to consult. Core pays for\n // the same guarantee with `putField` because its bags are read on every\n // render and V8 keeps a prototype-less object in dictionary mode — this one\n // is a small per-mount cache read a few times per navigation, so the tax is\n // expected to be negligible and no primitive needs importing.\n //\n // ⚠ \"Expected\", not measured — and the distinction is written here because\n // the sibling claim in `putField`'s docblock was published as \"not\n // measurable\" and then refuted by a better instrument. Nothing benches this\n // cache; if that changes, measure before repeating the word.\n //\n // ⚠ `JSON.parse` DEFINES, so a stored `\"__proto__\"` key arrives as ordinary\n // data either way; what this closes is the ambient half.\n try {\n const raw = sessionStorage.getItem(storageKey);\n const parsed = raw\n ? (JSON.parse(raw) as Record<string, number>)\n : undefined;\n\n store = Object.assign(\n Object.create(null) as Record<string, number>,\n parsed,\n );\n } catch {\n store = Object.create(null) as Record<string, number>;\n }\n\n return store;\n };\n\n const putPos = (key: string, pos: number): void => {\n try {\n const cached = loadStore();\n\n // Skip-same-value: when a route is left at the same scroll position it\n // already holds in the cache (e.g. tab-switching without scrolling),\n // both the in-memory write and the JSON.stringify + setItem pair are\n // no-ops. Eliminates redundant serialization on the navigation hot\n // path for the common \"click tabs without scrolling\" case.\n if (cached[key] === pos) {\n return;\n }\n\n cached[key] = pos;\n sessionStorage.setItem(storageKey, JSON.stringify(cached));\n } catch {\n // Ignore quota / security errors.\n }\n };\n\n const prevScrollRestoration = history.scrollRestoration;\n\n try {\n history.scrollRestoration = \"manual\";\n } catch {\n // Ignore — some embedded contexts may reject the assignment.\n }\n\n // Resolve the container lazily on every event so containers mounted AFTER\n // the provider still get correct scroll handling. Falls back to window when\n // the getter is absent or returns null (pre-mount).\n const readPos = (): number => {\n const element = getContainer?.();\n\n return element ? element.scrollTop : globalThis.scrollY;\n };\n\n const writePos = (top: number): void => {\n const element = getContainer?.();\n\n if (element) {\n element.scrollTo({ top, left: 0, behavior });\n } else {\n globalThis.scrollTo({ top, left: 0, behavior });\n }\n };\n\n // Restore path (back / traverse / reload). Unlike `writePos`, this tolerates a\n // scroll container that both MOUNTS and LAYS OUT a few frames AFTER the\n // navigation settles.\n //\n // The capture-side `readPos` always runs against an already-mounted DOM (the\n // route being left). On restore the target route — and its container — is\n // still being committed by the view layer. The subscribe callback schedules a\n // single rAF; for a heavy route (e.g. a long virtual list) the framework's\n // commit can land AFTER that frame. Two distinct failures follow, each losing\n // the saved position (Scenario 6 e2e, reproduced under CI's slower runner):\n //\n // 1. Container not mounted yet → `getContainer()` is `null`, the scroll\n // silently falls back to `window`, which on a container-only route has\n // nothing to scroll.\n // 2. Container mounted but its content not laid out yet → `scrollHeight`\n // is still small, so a single `scrollTo({ top })` clamps short of the\n // saved position and never re-applies once layout grows.\n //\n // With no `scrollContainer` getter the target is always `window`, present\n // from the first frame — restore in a single shot (unchanged behaviour). When\n // a getter is configured we cannot tell \"this route legitimately uses window\"\n // from \"the container is still mounting\", so re-apply the scroll on every\n // frame for a bounded budget: window as a fallback while the container is\n // absent (harmless clamp on container routes), the container itself once it\n // appears. For instant restores we stop early the moment the position sticks;\n // smooth restores animate asynchronously, so they run the full budget. The\n // frame budget is the hard backstop against an unreachable target (saved\n // position taller than the restored content).\n const restorePos = (top: number): void => {\n if (!getContainer) {\n globalThis.scrollTo({ top, left: 0, behavior });\n\n return;\n }\n\n let frames = 0;\n\n const attempt = (): void => {\n if (destroyed) {\n return;\n }\n\n const element = getContainer();\n\n if (element) {\n element.scrollTo({ top, left: 0, behavior });\n\n // Instant restore landed within rounding tolerance → done; no point\n // re-applying. Smooth restore never matches synchronously, so let it\n // ride the budget.\n if (behavior !== \"smooth\" && Math.abs(element.scrollTop - top) <= 1) {\n return;\n }\n } else {\n globalThis.scrollTo({ top, left: 0, behavior });\n }\n\n if (frames >= RESTORE_RETRY_FRAMES) {\n return;\n }\n\n frames += 1;\n requestAnimationFrame(attempt);\n };\n\n attempt();\n };\n\n const scrollToHashOrTop = (route: State): void => {\n // URL plugin path (#532): `state.context.url.hash` is the source of truth\n // when one of the URL plugins (browser-plugin / navigation-plugin) is\n // installed. The value is already DECODED — feeding it through\n // `decodeURIComponent` again would throw on a bare `%`.\n const ctxHash = (route.context as { url?: { hash?: string } } | undefined)\n ?.url?.hash;\n\n if (ctxHash !== undefined) {\n if (anchorEnabled && ctxHash.length > 0) {\n // eslint-disable-next-line unicorn/prefer-query-selector -- ids may contain CSS-unsafe chars\n const element = document.getElementById(ctxHash);\n\n if (element) {\n element.scrollIntoView({ behavior });\n\n return;\n }\n }\n\n writePos(0);\n\n return;\n }\n\n // Fallback path: no URL plugin, read the DOM. `location.hash` is\n // percent-encoded; ids in the DOM are the raw string, so decode for the\n // match. Fall back to the raw slice if the hash contains a malformed\n // escape sequence (decodeURIComponent throws on those).\n const hash = globalThis.location.hash;\n\n if (anchorEnabled && hash.length > 1) {\n let id: string;\n\n try {\n id = decodeURIComponent(hash.slice(1));\n } catch {\n id = hash.slice(1);\n }\n\n // eslint-disable-next-line unicorn/prefer-query-selector -- ids may contain CSS-unsafe chars\n const element = document.getElementById(id);\n\n if (element) {\n element.scrollIntoView({ behavior });\n\n return;\n }\n }\n\n writePos(0);\n };\n\n let destroyed = false;\n let unserializableWarned = false;\n // Capture/effect seam guard (#782). previousRoute's position is captured\n // synchronously in `subscribe`, but the snap/restore effect runs a frame\n // later in rAF. Across that window the viewport still shows the route BEFORE\n // previousRoute, so a second navigation landing in the same frame would\n // capture that foreign position under previousRoute's key. `scrollSettled` is\n // false across the window — capture is skipped (previousRoute's own stored\n // value survives the transit). A real user scroll in this <16ms window is\n // physically impossible.\n let scrollSettled = true;\n\n // `keyOf` defers to `canonicalJson` which calls `JSON.stringify`. Two\n // realistic inputs blow up the serializer and would otherwise crash the\n // subscribe callback (taking scroll-restore offline for the whole session):\n // - `BigInt` params → `TypeError: Do not know how to serialize a BigInt`\n // - cyclic params (reactive proxies, DOM-ref back-pointers) → stack\n // overflow.\n // The defensive wrapper drops capture/restore for that specific navigation\n // and warns once per provider — the rest of the cache stays usable.\n const safeKeyOf = (state: State): string | null => {\n try {\n return keyOf(state);\n } catch {\n if (!unserializableWarned) {\n unserializableWarned = true;\n console.error(\n `[real-router] scroll-restore: route \"${state.name}\" has params that cannot be canonicalized (e.g. BigInt or cyclic structure). Scroll position will not be captured or restored for this route.`,\n );\n }\n\n return null;\n }\n };\n\n const unsubscribe = router.subscribe(({ route, previousRoute }) => {\n const nav = (route.context as { navigation?: NavigationContext })\n .navigation;\n\n // Browsers dispatch reload as the initial navigation after refresh, so\n // previousRoute is undefined and capture is naturally skipped. The\n // pre-refresh position was already persisted via pagehide. Capture is also\n // skipped while the scroll is unsettled — a second navigation in the same\n // frame, before the prior nav's rAF snap (see `scrollSettled`, #782).\n if (previousRoute && scrollSettled) {\n const prevKey = safeKeyOf(previousRoute);\n\n if (prevKey !== null) {\n putPos(prevKey, readPos());\n }\n }\n\n // This navigation's scroll effect is now pending: the viewport position no\n // longer belongs to `route` until the rAF below runs and settles it.\n scrollSettled = false;\n\n requestAnimationFrame(() => {\n if (destroyed) {\n return;\n }\n\n // Effect running — the position now belongs to `route`, so the next\n // capture is honest again.\n scrollSettled = true;\n\n if (mode === \"top\") {\n scrollToHashOrTop(route);\n\n return;\n }\n\n // Restore branches (reload, back/traverse) MUST be evaluated before the\n // replace-skip below. Since #657 lifted `replace` into TransitionMeta, a\n // history TRAVERSAL (back/forward) under navigation-plugin carries\n // `transition.replace === true` — a traversal reuses an existing history\n // entry, which is replace-shaped at the history level. If the replace-skip\n // ran first it would swallow every back/forward navigation and restore\n // would never fire (the Scenario 6 e2e regression). Genuine in-place\n // replaces (`router.navigate({ replace: true })`, navigateToNotFound) are\n // not traversals and fall through to the skip below.\n //\n // Both arms of each check are required: `transition.reload` only fires for\n // programmatic `router.navigate({reload:true})`. F5 under navigation-plugin\n // primes `nav.navigationType === \"reload\"` via #531 getActivationType but\n // leaves opts.reload undefined, so dropping the plugin arm would regress F5\n // scroll-restore. Browser-plugin's F5 is not covered (no priming, out of\n // scope).\n if (route.transition.reload || nav?.navigationType === \"reload\") {\n const key = safeKeyOf(route);\n\n restorePos(key === null ? 0 : (loadStore()[key] ?? 0));\n\n return;\n }\n\n if (nav?.direction === \"back\" || nav?.navigationType === \"traverse\") {\n const key = safeKeyOf(route);\n\n restorePos(key === null ? 0 : (loadStore()[key] ?? 0));\n\n return;\n }\n\n // Genuine in-place replace (not a traversal) — leave scroll untouched.\n if (route.transition.replace || nav?.navigationType === \"replace\") {\n return;\n }\n\n scrollToHashOrTop(route);\n });\n });\n\n const onPageHide = (): void => {\n const current = router.getState();\n\n if (current) {\n const key = safeKeyOf(current);\n\n if (key !== null) {\n putPos(key, readPos());\n }\n }\n };\n\n globalThis.addEventListener(\"pagehide\", onPageHide);\n\n return {\n destroy: () => {\n // No `if (destroyed) return` guard: every teardown below is idempotent —\n // `unsubscribe()` is a `set.delete` in the core EventEmitter, DOM\n // `removeEventListener` is spec-idempotent, and the history assignment is\n // a plain re-set. There is no ref-count to protect (unlike\n // route-announcer's shared announcer element), so a double `destroy()` is\n // harmless. `destroyed = true` still gates any pending restore rAF / retry.\n destroyed = true;\n unsubscribe();\n globalThis.removeEventListener(\"pagehide\", onPageHide);\n\n try {\n history.scrollRestoration = prevScrollRestoration;\n } catch {\n // Ignore.\n }\n },\n };\n}\n\n/**\n * Internal cache-key builder for scroll-position storage.\n *\n * **Exported for testing only — not part of the public API** (intentionally\n * excluded from `index.ts` barrel). Adapter property tests import it via\n * the direct path to lock the `(name, canonicalJson(params))` key shape\n * as a regression guard (§8b H20 / audit-2026-05-16 #S3). A change to\n * key format would silently lose scroll positions across an upgrade —\n * the test set is the contract.\n *\n * ## Identity-based memoization (audit-2026-05-17 §8b #2)\n *\n * `State` objects emitted by core are frozen per-navigation: their\n * `name` / `params` are immutable for the lifetime of the snapshot, and\n * any change produces a new `State` reference. A `WeakMap<State, string>`\n * therefore safely caches the canonicalised key by identity — repeat\n * `keyOf(state)` calls on the same snapshot (typical on\n * back/forward/traverse where the same prior `State` is re-emitted)\n * skip the recursive `canonicalJson` pass entirely.\n *\n * The cache key is the `State` reference, so entries auto-release when\n * the snapshot is GC'd — no eviction needed.\n */\nconst KEY_CACHE = new WeakMap<State, string>();\n\nexport function keyOf(state: State): string {\n const cached = KEY_CACHE.get(state);\n\n if (cached !== undefined) {\n return cached;\n }\n\n // Key over BOTH channels — path params AND query (RFC-4 M2 / #1548). Merged\n // (not `params:search`) so a query-less route keeps its v1 key shape\n // (`name:{}`), and an unserializable value (BigInt / cyclic) in EITHER channel\n // still throws in `canonicalJson` → `safeKeyOf` drops+warns.\n const key = `${state.name}:${canonicalJson({ ...state.params, ...state.search })}`;\n\n KEY_CACHE.set(state, key);\n\n return key;\n}\n\n/**\n * Stable JSON serializer with sorted object keys.\n *\n * **Exported for testing only — not part of the public API** (intentionally\n * excluded from `index.ts` barrel). Adapter property tests import it via\n * the direct path to lock the key-order-insensitive property\n * (`canonicalJson({a:1,b:2}) === canonicalJson({b:2,a:1})`).\n *\n * ## Divergence from `@real-router/sources/canonicalJson` — by design\n *\n * Two independent implementations live in the monorepo:\n *\n * - **`shared/dom-utils/scroll-restore.canonicalJson`** (this file) — scroll\n * cache key builder. Uses `localeCompare` and a plain-object accumulator;\n * tolerates `__proto__`-keyed inputs only insofar as `JSON.stringify`'s\n * replacer happens to sort them; relies on `JSON.stringify`'s native cycle\n * detector. Designed to be cheap on the navigation hot path. The\n * surrounding [[safeKeyOf]] wrapper catches the two crash inputs (`BigInt`,\n * cyclic) and skips the offending capture/restore.\n *\n * - **`@real-router/sources/canonicalJson`** — sources cache key builder.\n * Uses byte-order compare (`< / >`) for locale-independence, a\n * `Object.create(null)` accumulator to prevent prototype pollution, and a\n * bespoke path-based cycle detector (the native one cannot see the cloned\n * graph). Throws eagerly on `Map`/`Set`/`RegExp`/cycles — the caller falls\n * back to a non-cached source.\n *\n * **They are intentionally NOT interchangeable.** Aligning them would either\n * regress scroll-restore performance (byte-order + recursive clone is heavier\n * per call) or weaken the sources cache (locale dependence breaks\n * deterministic cache keys across machines). No cross-package equivalence\n * test exists or should be added; the relationship is \"different invariants,\n * different costs, different consumers.\" Audit-2 / audit-2026-05-17 §2\n * documents the choice.\n */\nexport function canonicalJson(value: unknown): string {\n return JSON.stringify(value, canonicalReplacer);\n}\n\nfunction canonicalReplacer(_key: string, val: unknown): unknown {\n // audit-2026-05-17 §5 MEDIUM (Sprint A.3) — function/Symbol marker.\n // `JSON.stringify` silently drops function and symbol values from\n // object output. Two routes that differ ONLY in a function/Symbol\n // value would canonicalize to the same string → silent scroll-cache\n // key collision (positions clobber each other). Replacing the value\n // with a sentinel string breaks the collision while keeping the\n // canonical form deterministic. The sentinels are intentionally\n // ASCII-only and lexically distinct from valid JSON-stringified\n // values; consumers will see `\"<fn>\"` / `\"<sym>\"` if they ever\n // round-trip the cache key, signalling the substitution clearly.\n if (typeof val === \"function\") {\n return \"<fn>\";\n }\n if (typeof val === \"symbol\") {\n return \"<sym>\";\n }\n\n if (val !== null && typeof val === \"object\" && !Array.isArray(val)) {\n // Null-prototype accumulator: a plain `{}` would interpret\n // `sorted[\"__proto__\"] = x` as a prototype assignment (silently dropped\n // from JSON.stringify output AND a prototype-pollution vector). Mirrors\n // the same guard in `@real-router/sources/canonicalJson`. The two\n // implementations are still intentionally divergent (see the doc-block\n // on [[canonicalJson]] above), but prototype-safety is non-negotiable\n // on both. Lock-test: scrollRestoreKey.properties.ts Invariant 11.\n const sorted = Object.create(null) as Record<string, unknown>;\n // eslint-disable-next-line unicorn/no-array-sort -- ng-packagr uses pre-ES2023 lib; toSorted unavailable\n const keys = objectKeys(val).sort((left: string, right: string) =>\n left.localeCompare(right),\n );\n\n for (const key of keys) {\n sorted[key] = (val as Record<string, unknown>)[key];\n }\n\n return sorted;\n }\n\n return val;\n}\n","import { getTransitionSource } from \"@real-router/sources\";\n\nimport type { NavigationOptions, Router } from \"@real-router/core\";\n\n/**\n * Router-coordinated scroll spy (#575).\n *\n * On `IntersectionObserver` notifications the utility picks the topmost\n * visible anchor inside the configured scroll container and emits a forced\n * same-route transition with `{ hash, replace: true, force: true, hashChange:\n * true }` through `router.navigate(...)`. The URL plugin\n * (`@real-router/browser-plugin` or `@real-router/navigation-plugin`) updates\n * `state.context.url.hash` so sibling hash-aware `<Link hash>` re-highlights\n * via the standard `createActiveRouteSource` pipeline.\n *\n * **Anti-flicker gates** (RFC §5.2):\n * 1. `getTransitionSource(router).getSnapshot().isTransitioning` — skip emits\n * while a transition is in-flight (re-entrant lock).\n * 2. `coolingDown` — set on a user-driven hash transition (e.g. `<Link hash>`\n * click + smooth `scrollIntoView`). Cleared on `scrollend` or after a\n * 500ms safety timeout. Spy's own emits are excluded via the synchronous\n * `selfEmitting` flag — required so the spy doesn't rate-limit itself.\n *\n * **Self-healing** (RFC §7.3): if the initial URL contains a hash without a\n * matching `id` (e.g. `/page#nonexistent`), the first IO event emitted right\n * after observe()-ing picks the topmost real anchor and corrects the URL.\n *\n * **Hash-only transition pipeline cost** (RFC §5.3): for same-route same-\n * params hash-only navigations, `getTransitionPath` returns empty\n * `toDeactivate` / `toActivate` arrays, so `runGuards` is a no-op. The only\n * work is the URL plugin's `onTransitionSuccess` write and the\n * `getTransitionSource` flip — cheap.\n *\n * **Architecture**: decomposed into 4 private subsystem closure factories\n * (`createUrlPluginDetector`, `createCooldown`, `createDebouncer`,\n * `createObserverPair`). The main `createScrollSpy` wires them together\n * around the shared `silenced` / `destroyed` / `selfEmitting` flags and the\n * `flush()` emit logic. Each subsystem owns its state + cleanup; `destroy()`\n * delegates to each. See section banners below.\n *\n * @returns A `ScrollSpy` handle whose `destroy()` is idempotent.\n */\nexport interface ScrollSpyOptions {\n /**\n * CSS selector for anchor candidates. Empty string `\"\"` or `undefined`\n * disables the spy (returns a NOOP handle). Common values:\n * `\"[id]\"`, `\"[id]:is(h1,h2,h3)\"`, `\"section[id]\"`.\n */\n selector: string;\n\n /**\n * `IntersectionObserver` `rootMargin`. Default\n * `\"-20% 0px -60% 0px\"` — an anchor is considered \"active\" once it crosses\n * into the top 20 % of the viewport (or scroll container).\n */\n rootMargin?: string | undefined;\n\n /**\n * Lazy getter for the scrollable container. Consulted at creation and\n * re-consulted on every reconcile (DOM mutation), so a container that\n * MOUNTS or CHANGES after the spy is created is honoured: the\n * `IntersectionObserver` root and `MutationObserver` target — both immutable\n * once constructed — are rebuilt to match (#780). `null` (or a missing\n * getter) falls back to the window viewport (`root: null` on the\n * `IntersectionObserver`).\n */\n scrollContainer?: (() => HTMLElement | null) | undefined;\n}\n\nexport interface ScrollSpy {\n /** Tear down observer + listeners. Idempotent. */\n destroy: () => void;\n}\n\nconst NOOP_INSTANCE: ScrollSpy = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\n// Hardcoded internals (RFC §5.1 — promote only with evidence).\nconst RAF_DEBOUNCE_MS = 150;\nconst MUTATION_DEBOUNCE_MS = 250;\nconst COOLDOWN_TIMEOUT_MS = 500;\nconst DEFAULT_ROOT_MARGIN = \"-20% 0px -60% 0px\";\n\n// Local extension type — browser-plugin / navigation-plugin augment\n// `NavigationOptions` with `hash` and `hashChange`, but `shared/dom-utils`\n// is plugin-agnostic and cannot rely on the augmentation. Mirrors the\n// `HashAwareNavigationOptions` pattern in `link-utils.ts`.\ntype HashAwareNavigationOptions = NavigationOptions & {\n hash?: string;\n hashChange?: boolean;\n};\n\n// The `url` namespace contract is owned by browser-env: both URL plugins\n// (browser-plugin, navigation-plugin) write `{ hash: string; hashChanged }` on\n// every transition. This is a local mirror (keeps dom-utils independent of\n// browser-env) and must match that canonical shape — `hash` is always present,\n// never a partial slice.\ninterface UrlContextSlice {\n hash: string;\n hashChanged: boolean;\n}\n\nconst getUrlContext = (state: {\n context?: unknown;\n}): UrlContextSlice | undefined =>\n (state.context as { url?: UrlContextSlice } | undefined)?.url;\n\n// =============================================================================\n// Picker — pure, no state. RFC §5.2 selection rule.\n// =============================================================================\n\n// Pick the anchor closest to the active zone top in viewport coordinates.\n// `entry.rootBounds.top` already reflects `rootMargin` (per W3C IO spec\n// §3.3) — for `rootMargin: \"-20% 0px -60% 0px\"` it returns 20% of root\n// height, for `\"-50% 0px -50% 0px\"` it returns the center, etc. Distance\n// = boundingClientRect.top − zoneTop in viewport pixels: positive = anchor\n// below zone top (just entered), negative = anchor above zone top (body\n// crossing zone from above). We prefer smallest non-negative; fall back to\n// least-negative when no entry has crossed yet.\n// Falls back to zoneTop = 0 when rootBounds is null (cross-origin roots,\n// unit tests). Single pass — handles `Iterable` so flushes can pass\n// `Map.values()` directly without realising the array.\nconst pickTopmost = (\n entries: Iterable<IntersectionObserverEntry>,\n): IntersectionObserverEntry | null => {\n let bestPositive: IntersectionObserverEntry | null = null;\n let bestPositiveDist = Number.POSITIVE_INFINITY;\n let bestNegative: IntersectionObserverEntry | null = null;\n let bestNegativeDist = Number.NEGATIVE_INFINITY;\n\n for (const entry of entries) {\n if (!entry.isIntersecting) {\n continue;\n }\n\n const zoneTop = entry.rootBounds?.top ?? 0;\n const distance = entry.boundingClientRect.top - zoneTop;\n\n if (distance >= 0) {\n if (distance < bestPositiveDist) {\n bestPositive = entry;\n bestPositiveDist = distance;\n }\n } else if (distance > bestNegativeDist) {\n bestNegative = entry;\n bestNegativeDist = distance;\n }\n }\n\n return bestPositive ?? bestNegative;\n};\n\n// =============================================================================\n// Subsystem: URL plugin detector (RFC §5.5)\n// Calls `onMissing` if `state.context` is published but `url` key is missing\n// (i.e. no URL plugin installed). Either synchronous on start, or deferred\n// via a one-shot `router.subscribe` if the router has not started yet.\n// `silenced` flag itself lives in main scope — detector signals via callback\n// (per Oracle Q1 — `silenced` has multiple unrelated triggers; main scope\n// owns the kill switch).\n// =============================================================================\n\ninterface UrlPluginDetector {\n destroy: () => void;\n}\n\nconst createUrlPluginDetector = (\n router: Router,\n onMissing: () => void,\n): UrlPluginDetector => {\n let detectionUnsub: (() => void) | null = null;\n\n const verify = (state: { context?: unknown }): void => {\n const context = state.context as\n (Record<string, unknown> & { url?: unknown }) | undefined;\n\n if (context && context.url === undefined) {\n console.warn(\n \"[real-router] scroll-spy: state.context.url is not claimed. \" +\n \"Spy requires browser-plugin or navigation-plugin. Disabling.\",\n );\n onMissing();\n }\n };\n\n const peekState = router.getState();\n\n if (peekState) {\n verify(peekState);\n } else {\n // Re-entry guard: `router.subscribe` MAY invoke the callback synchronously\n // from inside `.subscribe(...)` before the function returns. In that case\n // `detectionUnsub` is still `null` when the callback fires. Without this\n // boolean, a hypothetical multi-fire would double-warn.\n let detectionConsumed = false;\n\n detectionUnsub = router.subscribe(({ route }) => {\n /* v8 ignore next 3 -- @preserve: the multi-fire is hypothetical (see above) — the real router never invokes a subscriber synchronously twice before unsub; defensive guard, not testable without a contract-violating fake */\n if (detectionConsumed) {\n return;\n }\n\n detectionConsumed = true;\n verify(route);\n\n detectionUnsub?.();\n detectionUnsub = null;\n });\n }\n\n return {\n destroy(): void {\n detectionUnsub?.();\n detectionUnsub = null;\n },\n };\n};\n\n// =============================================================================\n// Subsystem: Cooldown gate (RFC §5.2 — anti-flicker for smooth scrollIntoView)\n// Set on user-driven `<Link hash>` click → smooth scroll. Cleared on\n// `scrollend` (Baseline 2026) or 500ms safety timeout (older Safari).\n// =============================================================================\n\ninterface Cooldown {\n readonly active: boolean;\n start: () => void;\n destroy: () => void;\n}\n\nconst createCooldown = (getContainer: () => HTMLElement | null): Cooldown => {\n let active = false;\n let timeout: ReturnType<typeof setTimeout> | null = null;\n let listenerContainer: HTMLElement | null = null;\n let listener: (() => void) | null = null;\n\n const clear = (): void => {\n if (timeout !== null) {\n clearTimeout(timeout);\n timeout = null;\n }\n\n if (listener) {\n const target: EventTarget = listenerContainer ?? globalThis;\n\n target.removeEventListener(\"scrollend\", listener);\n }\n\n listener = null;\n listenerContainer = null;\n active = false;\n };\n\n return {\n get active(): boolean {\n return active;\n },\n start(): void {\n // Reset rather than stack timers if cooldown is already active.\n clear();\n\n active = true;\n\n const lift = (): void => {\n clear();\n };\n\n listener = lift;\n listenerContainer = getContainer();\n\n const target: EventTarget = listenerContainer ?? globalThis;\n\n target.addEventListener(\"scrollend\", lift, { once: true });\n\n timeout = setTimeout(lift, COOLDOWN_TIMEOUT_MS);\n },\n destroy(): void {\n clear();\n },\n };\n};\n\n// =============================================================================\n// Subsystem: rAF + trailing debounce (RFC §5.1)\n// Coalesces a burst of IO events into ≤ 1 callback per debounce window.\n// rAF reduces N setTimeout creations to 1 per animation frame; the trailing\n// 150ms setTimeout waits for the IO stream to quiesce.\n// =============================================================================\n\ninterface Debouncer {\n schedule: () => void;\n destroy: () => void;\n}\n\nconst createDebouncer = (\n callback: () => void,\n trailingMs: number,\n): Debouncer => {\n let raf: number | null = null;\n let timeout: ReturnType<typeof setTimeout> | null = null;\n\n return {\n schedule(): void {\n if (raf !== null) {\n return;\n }\n\n raf = requestAnimationFrame(() => {\n raf = null;\n\n if (timeout !== null) {\n clearTimeout(timeout);\n }\n\n timeout = setTimeout(() => {\n timeout = null;\n callback();\n }, trailingMs);\n });\n },\n destroy(): void {\n if (raf !== null) {\n cancelAnimationFrame(raf);\n raf = null;\n }\n\n if (timeout !== null) {\n clearTimeout(timeout);\n timeout = null;\n }\n },\n };\n};\n\n// =============================================================================\n// Subsystem: Observer pair (IntersectionObserver + MutationObserver)\n// IO + MO genuinely form one subsystem — both write/read `observed` set and\n// `pending` map, and reconcile flow couples them. Per Oracle Q10, splitting\n// would force cross-subsystem references that re-introduce the wiring\n// problem we're trying to solve.\n//\n// Exposes `pending` directly (per Oracle Q4: hiding behind `consume()` adds\n// boilerplate without isolating the shared mutable state — observers write\n// from IO callbacks while main scope reads in `flush()`).\n// =============================================================================\n\ninterface ObserverPair {\n readonly pending: Map<Element, IntersectionObserverEntry>;\n /** True when a resolved container has since detached from the DOM (#1216). */\n isContainerDetached: () => boolean;\n /** Re-resolve the container + re-observe matches (rebuilds the pair on change). */\n reconcile: () => void;\n destroy: () => void;\n}\n\nconst createObserverPair = (\n selector: string,\n rootMargin: string,\n getContainer: () => HTMLElement | null,\n onIntersection: () => void,\n onInvalidSelector: () => void,\n isStopped: () => boolean,\n): ObserverPair => {\n const observed = new Set<Element>();\n // Latest IO entry per target — accumulated across batches. IO delivers\n // entries only for targets whose intersection state CHANGED (W3C IO\n // §3.2.1), so a fast scroll that lands two callbacks inside the same\n // debounce window must merge by target, not overwrite. Entries are\n // dropped from the map when their target leaves the DOM (see `reconcile`)\n // and on `destroy()`.\n const pending = new Map<Element, IntersectionObserverEntry>();\n\n let duplicateIdWarned = false;\n let mutationTimer: ReturnType<typeof setTimeout> | null = null;\n\n const handleIntersection: IntersectionObserverCallback = (entries) => {\n // Defensive: IO callback may fire AFTER `destroy()` if a queued event\n // was already scheduled by the browser before `disconnect()`. Cheap\n // belt-and-suspenders.\n if (isStopped()) {\n return;\n }\n\n for (const entry of entries) {\n pending.set(entry.target, entry);\n }\n\n onIntersection();\n };\n\n // Build (and rebuild) the IntersectionObserver for a given root. A root is\n // immutable once its IO is constructed, so `reconcile` recreates the IO via\n // this same factory when the resolved container changes (#780) — one\n // definition, two call sites.\n const makeIo = (container: HTMLElement | null): IntersectionObserver =>\n new IntersectionObserver(handleIntersection, {\n root: container,\n rootMargin,\n threshold: 0,\n });\n\n // Container the IntersectionObserver root + MutationObserver target are\n // built with. Both are immutable once the observer is constructed (W3C), so\n // a `scrollContainer` that resolves to a different element after creation —\n // most importantly one that MOUNTS after the spy starts (Angular wires the\n // spy at bootstrap, before any component renders; a docs route's container\n // mounts on navigation) — is only honoured by rebuilding the pair in\n // `reconcile`. Tracked here so `reconcile` can compare on every run (#780).\n let observerContainer = getContainer();\n\n let io = makeIo(observerContainer);\n\n const observeMatches = (): void => {\n const scope = getContainer() ?? document;\n let candidates: NodeListOf<Element>;\n\n try {\n candidates = scope.querySelectorAll(selector);\n } catch {\n onInvalidSelector();\n\n return;\n }\n\n const seenIds = new Set<string>();\n\n for (const element of candidates) {\n // Detect duplicate ids once (RFC §7.7). The DOM permits duplicate ids\n // even though it is a markup bug; the spy keeps working but picks the\n // first one deterministically via the topmost-visible rule.\n const id = (element as HTMLElement).id;\n\n if (id && !duplicateIdWarned) {\n if (seenIds.has(id)) {\n duplicateIdWarned = true;\n\n console.warn(\n `[real-router] scroll-spy: duplicate id \"${id}\" observed. ` +\n \"Selection picks the topmost visible match deterministically.\",\n );\n }\n\n seenIds.add(id);\n }\n\n if (observed.has(element)) {\n continue;\n }\n\n io.observe(element);\n observed.add(element);\n }\n };\n\n // MutationObserver init — reused when the observer is re-pointed at a new\n // container in `reconcile`. `childList: true, subtree: true` catches\n // structural changes; `attributes: true, attributeFilter: [\"id\"]` catches\n // anchor id renames (typical for client-rendered docs). The MO targets the\n // scroll container (or document.body for the window viewport).\n const MUTATION_OBSERVE_INIT: MutationObserverInit = {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: [\"id\"],\n };\n\n // Null-then-assigned — the same forward-reference idiom as `flush` in the\n // main scope. `reconcile` re-points it on a container change, so it must be\n // in scope above its assignment; it is non-null by the time any async\n // mutation callback (or `reconcile`) runs.\n let mo: MutationObserver | null = null;\n\n const reconcile = (): void => {\n // Drop observed elements that left the DOM. Avoids observer holding\n // strong refs to detached nodes. Also drop their accumulated entry so\n // stale \"was intersecting\" state for a removed node cannot be picked\n // by `pickTopmost` after the node is gone.\n for (const element of observed) {\n if (element.isConnected) {\n continue;\n }\n\n io.unobserve(element);\n observed.delete(element);\n pending.delete(element);\n }\n\n // Honour a container that mounted (or changed) after construction (#780).\n // The IntersectionObserver root and MutationObserver target cannot be\n // mutated in place, so rebuild the pair under the new container. Clearing\n // `observed` + `pending` makes the rebuild equivalent to constructing the\n // spy with this container from the start: `observeMatches` below\n // re-populates the tracked set from the new container's scope, and the\n // stale merged snapshot (computed against the old root's geometry) is\n // dropped — one empty debounce window, acceptable for a rare event.\n const nextContainer = getContainer();\n\n if (nextContainer !== observerContainer) {\n observerContainer = nextContainer;\n\n io.disconnect();\n io = makeIo(nextContainer);\n observed.clear();\n pending.clear();\n\n mo?.disconnect();\n mo?.observe(nextContainer ?? document.body, MUTATION_OBSERVE_INIT);\n }\n\n observeMatches();\n };\n\n observeMatches();\n\n mo = new MutationObserver(() => {\n if (mutationTimer !== null) {\n clearTimeout(mutationTimer);\n }\n\n mutationTimer = setTimeout(() => {\n mutationTimer = null;\n reconcile();\n }, MUTATION_DEBOUNCE_MS);\n });\n\n mo.observe(observerContainer ?? document.body, MUTATION_OBSERVE_INIT);\n\n return {\n pending,\n // #1216: the MutationObserver is pointed at the container's OWN subtree, so\n // the container's removal (a mutation of its PARENT) is invisible — reconcile\n // never fires on it and a remounted container is never re-observed. Expose a\n // detach check + reconcile so the router.subscribe callback can re-resolve on\n // navigation (exactly when route-tied containers mount/die). When\n // `observerContainer` is null the MO already watches `document.body`, which\n // sees container mounts directly — so only a resolved-then-detached container\n // needs this nav-time nudge.\n isContainerDetached: (): boolean =>\n observerContainer !== null && !observerContainer.isConnected,\n reconcile,\n destroy(): void {\n io.disconnect();\n mo.disconnect();\n\n if (mutationTimer !== null) {\n clearTimeout(mutationTimer);\n mutationTimer = null;\n }\n\n observed.clear();\n pending.clear();\n },\n };\n};\n\n// =============================================================================\n// Main: compositional wiring\n// =============================================================================\n\nexport function createScrollSpy(\n router: Router,\n options: ScrollSpyOptions,\n): ScrollSpy {\n // SSR guard (RFC §7.5) — return early without warnings.\n if (typeof document === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n // Feature-detect IntersectionObserver — no polyfill ships (RFC §4).\n if (typeof IntersectionObserver === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n const { selector } = options;\n\n // Empty selector → disabled. Documented opt-out for conditional enabling\n // (RFC §5.4 `scrollSpy={{ selector: enable ? \"[id]\" : \"\" }}`).\n if (!selector) {\n return NOOP_INSTANCE;\n }\n\n const rootMargin = options.rootMargin ?? DEFAULT_ROOT_MARGIN;\n const getContainer = options.scrollContainer;\n const resolveContainer = (): HTMLElement | null => getContainer?.() ?? null;\n\n // Shared lifecycle flags (Oracle Q1 — `silenced` has multiple unrelated\n // triggers; Oracle Q3 — `selfEmitting` synchronously bracketed around\n // `router.navigate()` cannot cleanly extract). Kept in main scope.\n let destroyed = false;\n let silenced = false;\n let selfEmitting = false;\n\n const isStopped = (): boolean => silenced || destroyed;\n\n // Symmetric late-binding (Oracle Q2): declare `flush` as nullable, wire\n // debouncer + observers, then assign the real implementation. Reads as\n // intentional wiring rather than accidental closure capture ordering.\n // The `flush?.()` call below safely no-ops if a callback somehow fires\n // before assignment (impossible in practice — IO/debounce are async).\n let flush: (() => void) | null = null;\n\n const transitionSource = getTransitionSource(router);\n\n const detector = createUrlPluginDetector(router, () => {\n silenced = true;\n });\n\n const cooldown = createCooldown(resolveContainer);\n\n const debouncer = createDebouncer(() => {\n flush?.();\n }, RAF_DEBOUNCE_MS);\n\n const observers = createObserverPair(\n selector,\n rootMargin,\n resolveContainer,\n () => {\n debouncer.schedule();\n },\n () => {\n if (silenced) {\n return;\n }\n\n silenced = true;\n\n console.warn(\n `[real-router] scroll-spy: invalid selector \"${selector}\". Disabling.`,\n );\n },\n isStopped,\n );\n\n flush = (): void => {\n if (destroyed || silenced) {\n observers.pending.clear();\n\n return;\n }\n\n // Gate-skipped flushes keep `pendingEntries` populated — the merged\n // state is still the best-known snapshot, and the next non-gated flush\n // consumes it. Clearing under a gate would re-introduce the overwrite\n // bug for any anchor whose intersection state did not change during\n // the gate window.\n if (transitionSource.getSnapshot().isTransitioning) {\n return;\n }\n\n if (cooldown.active) {\n return;\n }\n\n // No `if (pending.size === 0) return` fast-path: `pending` is never empty\n // here via any real path (a real IntersectionObserver always delivers ≥1\n // entry, so `handleIntersection` populates `pending` before scheduling; the\n // mutation reconcile that could drop entries runs at MUTATION_DEBOUNCE_MS\n // 250 > RAF_DEBOUNCE_MS 150, i.e. always AFTER the flush). And an empty map\n // is already handled identically below — `pickTopmost(∅)` is `null` → the\n // `if (!picked) return` guard — so the fast-path was both unreachable and\n // redundant.\n\n // Successful flush consumes the merged snapshot. We clear so that the\n // next debounce window starts fresh; an anchor that is still\n // intersecting will only stay observable if IO emits another event for\n // it (which it does whenever the anchor's intersection state actually\n // changes). Skipping the clear here would leak state from one user-\n // perceived \"scroll stop\" into the next.\n const picked = pickTopmost(observers.pending.values());\n\n observers.pending.clear();\n\n if (!picked) {\n // No anchor visible / above zone — preserve last hash (RFC §10 #5).\n return;\n }\n\n const newHash = (picked.target as HTMLElement).id;\n\n if (!newHash) {\n return;\n }\n\n const state = router.getState();\n\n if (!state) {\n return;\n }\n\n // `getUrlContext` is guaranteed present here (the URL-plugin detector\n // silences the spy otherwise), so `?.` only satisfies the `| undefined`\n // slice type. `newHash` is a non-empty id (guarded above), so it can never\n // equal an absent hash — no `?? \"\"` normalization needed for the compare.\n const currentHash = getUrlContext(state)?.hash;\n\n if (newHash === currentHash) {\n return;\n }\n\n // Emit the same-route same-params hash-only transition. URL plugin\n // writes `state.context.url.hash = newHash` + `hashChanged = true` in\n // its `onTransitionSuccess` claim.\n const opts: HashAwareNavigationOptions = {\n hash: newHash,\n replace: true,\n force: true,\n hashChange: true,\n };\n\n // Self-emit guard (RFC §5.2): set synchronously around our own\n // `router.navigate()` so the `router.subscribe` callback skips the\n // cooldown setup for spy-emitted transitions — otherwise spy would\n // rate-limit itself to ≤ 2 emits/s, contradicting the ≤ 10/s benchmark\n // target. Test coupling (Q8): preserve exact `.catch(noop).finally(reset)`\n // chain — migrating to `try/finally` over `await router.navigate(...)`\n // changes microtask schedule and breaks \"spy continues after rejection\".\n selfEmitting = true;\n router\n // Both channels of the CURRENT state, not just the path bag (RFC-4 M2 /\n // #1548): this is a same-route re-navigation to move the hash, so\n // whatever query the user is already looking at has to survive it.\n // Passing `undefined` in slot 3 dropped it — scrolling a page at\n // `/docs?tab=api` silently rewrote the URL to `/docs`. Options stay at\n // slot 4.\n .navigate(state.name, state.params, state.search, opts)\n .catch(() => {\n // Fire-and-forget — suppress expected rejections (concurrent\n // navigate, router stopped, etc.) consistent with `<Link>` adapter\n // patterns.\n })\n .finally(() => {\n selfEmitting = false;\n });\n };\n\n // Cooldown setup on user-driven hash transitions. Spy's own emits are\n // distinguished via the synchronous `selfEmitting` flag (see `flush`).\n const unsubscribeRouter = router.subscribe(({ route }) => {\n if (selfEmitting) {\n return;\n }\n\n // #1216: a route-tied scroll container may have unmounted since the last\n // navigation. The container-scoped MutationObserver can't observe its own\n // removal (a mutation of its parent), so re-resolve + re-observe here —\n // navigation is exactly when such containers mount / die.\n if (observers.isContainerDetached()) {\n observers.reconcile();\n }\n\n if (getUrlContext(route)?.hashChanged) {\n cooldown.start();\n }\n });\n\n return {\n destroy(): void {\n // No `if (destroyed) return` idempotency guard: every subsystem teardown\n // below is itself idempotent (null-guarded timers, `set.delete` on the\n // router unsubscribe, spec-idempotent `IntersectionObserver.disconnect`),\n // and `destroy()` is not a hot path — so a redundant guard would only add\n // an unreachable branch. `destroyed = true` is still set to gate any\n // late-arriving IO/router callback via `isStopped()`.\n destroyed = true;\n\n // Unsubscribe FIRST to prevent late-arriving router transition\n // callback from calling `cooldown.start()` on a half-destroyed\n // instance. Without this ordering, a transition with `hashChanged:\n // true` firing between subsystem teardown and `unsubscribeRouter()`\n // would re-install a 500ms timer that survives `destroy()`. Verified\n // via Oracle review (Q5/Q7).\n unsubscribeRouter();\n\n observers.destroy();\n debouncer.destroy();\n cooldown.destroy();\n detector.destroy();\n },\n };\n}\n","import type { Router } from \"@real-router/core\";\n\nexport interface ViewTransitions {\n destroy: () => void;\n}\n\nconst NOOP_INSTANCE: ViewTransitions = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\nexport function createViewTransitions(router: Router): ViewTransitions {\n if (\n typeof document === \"undefined\" ||\n typeof document.startViewTransition !== \"function\"\n ) {\n return NOOP_INSTANCE;\n }\n\n let closeVT: (() => void) | null = null;\n let currentVT: { skipTransition?: () => void } | null = null;\n // Tracks whether TRANSITION_SUCCESS fired for the current leave. Used to\n // distinguish \"benign cleanup abort\" (router's async path aborts its own\n // controller in a finally block after successful navigation) from \"real\n // cancellation\" (concurrent navigate, guard rejection, dispose).\n let successFired = false;\n\n const resolveAndClear = (): void => {\n closeVT?.();\n closeVT = null;\n };\n\n const offLeave = router.subscribeLeave(({ signal }) => {\n // Reentrant abort: signal already aborted when we're called. Open no VT\n // — router will fall through to TRANSITION_CANCELLED via isCurrentNav()\n // after leave resolves. addEventListener(\"abort\", ...) does not re-fire\n // for past events, so skipping startViewTransition is the safe path.\n if (signal.aborted) {\n return;\n }\n\n successFired = false;\n resolveAndClear();\n\n // Return a Promise so the router awaits until the browser invokes\n // updateCallback. This ensures old DOM snapshot is captured BEFORE the\n // router commits the new state — giving correct exit→state→entry\n // ordering (vs fire-and-forget, where URL changes before VT captures).\n return new Promise<void>((resolveLeave) => {\n // Capture the resolver synchronously BEFORE startViewTransition() is\n // called. The browser invokes updateCallback in a later task, but\n // router.subscribe (TRANSITION_SUCCESS) can fire before that. If we\n // captured `resolve` inside the callback, subscribe would see closeVT\n // still null and skip resolving — the deferred would hang for 4s\n // until the VT API aborts with TimeoutError.\n // eslint-disable-next-line unicorn/prefer-promise-with-resolvers -- frozen shared primitive; resolver captured synchronously before startViewTransition() by design (see comment above)\n const deferred = new Promise<void>((resolve) => {\n closeVT = resolve;\n });\n\n signal.addEventListener(\n \"abort\",\n () => {\n if (successFired) {\n // Router's async path (#finishAsyncNavigation) aborts its own\n // controller in a finally block AFTER completeTransition (and\n // thus AFTER subscribe fired). This is cleanup, not\n // cancellation — VT is progressing normally, do nothing.\n return;\n }\n\n // Real cancellation (concurrent navigate, dispose). Resolve the\n // deferred so updateCallback can complete, skip the VT so no\n // stale animation leaks, and unblock the router if the abort\n // fires before updateCallback was invoked.\n resolveAndClear();\n currentVT?.skipTransition?.();\n resolveLeave();\n },\n { once: true },\n );\n\n try {\n currentVT = document.startViewTransition(() => {\n // Resolving here unblocks the router at the moment the browser\n // enters updateCallback — by spec, old DOM snapshot is captured\n // before this callback runs. Router now proceeds through\n // activation guards and setState; the VT animation waits on\n // `deferred`, which is resolved from router.subscribe after a\n // task-queue tick (see NOTE on setTimeout below).\n resolveLeave();\n\n return deferred;\n });\n } catch {\n // Defensive: spec says startViewTransition doesn't throw under\n // normal conditions, but Chromium has had edge cases (detached\n // document, extension interference). Clean up and unblock router.\n resolveAndClear();\n resolveLeave();\n }\n });\n });\n\n const offSuccess = router.subscribe(() => {\n const resolver = closeVT;\n\n successFired = true;\n closeVT = null;\n\n if (resolver === null) {\n currentVT = null;\n } else {\n // The VT this resolver belongs to. If the next navigation opens a new VT\n // in the task-queue window before this setTimeout runs, the stale\n // resolver must NOT null the new `currentVT` — otherwise a later\n // cancellation reads `null` and skips nothing, leaking a stale animation\n // (#781). Same identity-guard technique the navigation-plugin uses to\n // heal its seams.\n const scheduledVT = currentVT;\n\n // CRITICAL: CANNOT use requestAnimationFrame here. When the router\n // takes the async path (leave returned a Promise), subscribe fires\n // AFTER the browser has already transitioned VT into the\n // \"update-callback-called\" phase. In that phase Chromium sets\n // rendering suppression to true, which ALSO blocks rAF callbacks.\n // rAF would never fire → deferred never resolves → browser aborts\n // vt.ready with TimeoutError after 4s (observed in Chromium).\n //\n // setTimeout runs on the task queue independent of the rendering\n // pipeline, so it fires regardless of suppression. React's scheduler\n // uses MessageChannel tasks, which are queued before our setTimeout,\n // so the new DOM is committed by the time our callback runs.\n setTimeout(() => {\n resolver();\n\n if (currentVT === scheduledVT) {\n currentVT = null;\n }\n }, 0);\n }\n });\n\n return {\n destroy: () => {\n offLeave();\n offSuccess();\n currentVT?.skipTransition?.();\n currentVT = null;\n resolveAndClear();\n },\n };\n}\n","import type {\n NavigationOptions,\n NavigationTarget,\n Params,\n Router,\n SearchParams,\n State,\n} from \"@real-router/core\";\n\n/**\n * Intrinsics captured at module load (#1971).\n *\n * ⚑ These DECIDE — they answer \"what is on this object\" for a value this module\n * did not build. Read off the live global they can be re-pointed after boot, and\n * `shared/` is the half where that fails OPEN: measured in `browser-env`, a\n * re-pointed `getPrototypeOf` admits a `Date` into `state.params` and a\n * re-pointed `keys` skips option validation entirely.\n *\n * ⚠ Capture narrows the window from \"any time after boot\" to \"before this module\n * loads\". It does not close it (#1798).\n */\nconst objectKeys = Object.keys;\n\n/**\n * Resolved navigation channels for a `<Link>` — the single `{ name, params,\n * search }` shape every adapter feeds into `buildHref` / `navigateWithHash` /\n * the active-route source, regardless of which prop form the consumer used.\n */\nexport interface ResolvedLinkTarget {\n name: string;\n params: Params | undefined;\n search: SearchParams | undefined;\n}\n\n/**\n * Collapses a `<Link>`'s two prop forms (RFC-4 M2 B2, #1548) into one channel\n * triple:\n *\n * - **Descriptor** — `to={{ name, params?, search? }}` (a `NavigationTarget`).\n * - **Channel props** — `routeName` + `routeParams?` + `routeSearch?`.\n *\n * The forms are mutually exclusive: the TS union on each adapter's `LinkProps`\n * rejects mixing them at compile time, and this helper is the runtime backstop —\n * when `to` is present it **wins**, and a `dev`-visible `console.warn` fires if\n * channel props were also supplied (a JS consumer, an object spread, or an\n * adapter without a strict union can still slip both through). `routeOptions` /\n * `hash` are separate props under BOTH forms (hash is not part of\n * `NavigationTarget` — #532), so they are resolved by the caller, not here.\n */\nexport function resolveLinkTarget(\n to: NavigationTarget | undefined,\n routeName: string,\n routeParams: Params | undefined,\n routeSearch: SearchParams | undefined,\n): ResolvedLinkTarget {\n if (to !== undefined) {\n if (\n routeName !== \"\" ||\n routeParams !== undefined ||\n routeSearch !== undefined\n ) {\n console.warn(\n \"[real-router] <Link> received both `to` and channel props \" +\n \"(routeName / routeParams / routeSearch). `to` wins; the channel \" +\n \"props are ignored. Use one form or the other.\",\n );\n }\n\n return { name: to.name, params: to.params, search: to.search };\n }\n\n return { name: routeName, params: routeParams, search: routeSearch };\n}\n\nexport function shouldNavigate(evt: MouseEvent): boolean {\n return (\n evt.button === 0 &&\n !evt.metaKey &&\n !evt.altKey &&\n !evt.ctrlKey &&\n !evt.shiftKey\n );\n}\n\n/**\n * RFC 3986 fragment encoding: preserve sub-delims (`&`, `=`, `?`, `:`),\n * encode space, `%`, control chars, non-ASCII via encodeURI; defensively\n * escape `#` (encodeURI does not). Kept BYTE-FOR-BYTE identical to\n * `encodeHashFragment` in `shared/browser-env/url-context.ts` — duplicated\n * because the shared/dom-utils symlink graph does not reach shared/browser-env;\n * a sync test (`link-utils` functional suite) asserts the two stay identical.\n *\n * **STRICTLY-DECODED contract (#1211 / D1=A).** The `<Link hash>` value is a\n * DECODED fragment (no leading `#`) and is encoded verbatim. This OVERTURNS\n * audit-2026-05-17 §5 E.1 — the earlier percent-escape probe (decode + re-encode\n * for copy-from-`location.hash` tolerance) is REMOVED, so both the adapter and\n * the plugin layer obey one contract: `<Link hash=\"a%20b\">` renders `#a%2520b`\n * (the literal fragment `a%20b`) under every runtime. Consumers who want the\n * fragment `a b` pass `hash=\"a b\"`; passing raw `location.hash` (percent-encoded)\n * is no longer supported — it was the source of the plugin↔adapter divergence.\n */\nfunction encodeFragmentInline(decoded: string): string {\n return encodeURI(decoded).replaceAll(\"#\", \"%23\");\n}\n\ntype BuildUrlFn = (\n name: string,\n params: Params,\n search?: SearchParams,\n options?: { hash?: string },\n) => string | undefined;\n\n/**\n * Builds an href for a `<Link>` element.\n *\n * - Prefers the URL plugin's `buildUrl` (browser-plugin, navigation-plugin,\n * hash-plugin) when present.\n * - Falls back to `router.buildPath` for runtimes without a URL plugin\n * (memory-plugin, console UIs, NativeScript). In that fallback the hash\n * is appended manually so the rendered href is still correct.\n * - The optional 4th argument is the decoded hash fragment (no leading \"#\";\n * `<Link hash=\"#section\">` is accepted defensively — leading \"#\" stripped),\n * passed positionally to mirror `navigateWithHash(router, name, params, hash)`\n * (#1442). Previous 3-arg call sites continue to work unchanged.\n */\nexport function buildHref(\n router: Router,\n routeName: string,\n routeParams: Params,\n routeSearch?: SearchParams,\n hash?: string,\n): string | undefined {\n try {\n let normHash: string | undefined;\n\n if (hash !== undefined) {\n normHash = hash.startsWith(\"#\") ? hash.slice(1) : hash;\n }\n\n const buildUrl = router.buildUrl as BuildUrlFn | undefined;\n\n if (buildUrl) {\n const url = buildUrl(\n routeName,\n routeParams,\n // Query channel at position 3 (RFC-4 M2 / #1548) — from the `routeSearch`\n // prop; hash options at position 4. `undefined` when the link has no\n // `routeSearch` (its query, if any, still rides in routeParams).\n routeSearch,\n normHash === undefined ? undefined : { hash: normHash },\n );\n\n // Accept only non-empty strings. The BuildUrlFn type contract is\n // `string | undefined`, but defensive against:\n // - `\"\"` (empty string) → would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - `null` (type-contract violation) → would render `<a href={null}>`,\n // stringified to `\"null\"` in some renderers.\n // Either case falls through to the `router.buildPath` fallback below.\n if (typeof url === \"string\" && url.length > 0) {\n return url;\n }\n }\n\n const path = router.buildPath(routeName, routeParams, routeSearch);\n\n // Symmetric to the buildUrl guard above (#S1 audit, Invariant 12).\n // `router.buildPath` is typed `string`, but defends against:\n // - `\"\"` (empty string) — would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - non-string type-contract violations from custom path-matchers.\n // Both yield `undefined` (renderer drops the attribute) with a warning.\n if (typeof path !== \"string\" || path.length === 0) {\n console.error(\n `[real-router] Route \"${routeName}\" yielded an empty path. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n\n return normHash ? `${path}#${encodeFragmentInline(normHash)}` : path;\n } catch {\n console.error(\n `[real-router] Route \"${routeName}\" is not defined. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n}\n\n/**\n * `<Link>` click-handler navigation helper (#532).\n *\n * Wraps `router.navigate(name, params, opts)` with same-route different-hash\n * detection: when the consumer clicks a hash-bearing Link that targets the\n * current route with the same params but a different fragment, core's\n * SAME_STATES check would otherwise reject the navigation. The helper adds\n * `force: true` and `hashChange: true` automatically — subscribers can then\n * disambiguate via `state.context.url.hashChanged`.\n *\n * For pure programmatic same-route hash-only navigation, callers are\n * documented to pass `{ force: true }` themselves; the auto-bypass here is\n * a UX convenience for `<Link hash>` that all 6 framework adapters share.\n */\n/**\n * Local extended-options type. Adapters that depend only on `@real-router/core`\n * (without a URL plugin) do not see the `NavigationOptions` augmentation that\n * declares `hash` / `hashChange`. Casting to this widened type inside the\n * helper keeps shared/dom-utils self-contained — adapters do not need to\n * augment NavigationOptions themselves to consume `<Link hash>`.\n */\ntype HashAwareNavigationOptions = NavigationOptions & {\n hash?: string;\n hashChange?: boolean;\n};\n\nexport function navigateWithHash(\n router: Router,\n routeName: string,\n routeParams: Params,\n routeSearch: SearchParams | undefined,\n hash: string | undefined,\n extraOptions?: NavigationOptions,\n): Promise<State> {\n const opts: HashAwareNavigationOptions = { ...extraOptions };\n\n if (hash !== undefined) {\n opts.hash = hash;\n }\n\n const current = router.getState();\n\n // \"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 writing\n // `routeSearch={{ page: \"2\" }}` never matched a state parsed from `?page=2`,\n // where the value is the NUMBER 2 — the bypass silently did not fire, core\n // rejected the navigation as SAME_STATES, and `<Link hash>` looked dead. The\n // predicate carries the provenance-tolerant comparison (#1554) that makes the\n // two forms equal because they print the same URL.\n //\n // It also compared the caller's whole `routeParams` bag against `state.params`,\n // which stopped meaning anything once the channels split (#1548) — the\n // predicate applies the channel rule instead of re-deriving it.\n //\n // `strictEquality: true` — a link to a PARENT route is a different location, so\n // the hierarchical arm must not match. `ignoreQueryParams: false` — the query is\n // part of the location here; ignoring it would fire the bypass across a real\n // query change and let `force: true` smuggle it through as a hash change.\n if (\n current !== undefined &&\n router.isActiveRoute(\n routeName,\n routeParams,\n routeSearch ?? current.search,\n true,\n false,\n )\n ) {\n const currentHash =\n (current.context as { url?: { hash?: string } } | undefined)?.url?.hash ??\n \"\";\n const newHash = hash ?? currentHash;\n\n if (currentHash !== newHash) {\n opts.force = true;\n opts.hashChange = true;\n }\n }\n\n // Query channel at position 3 (RFC-4 M2 / #1548) — from the `routeSearch`\n // prop; opts at position 4. `undefined` when the link has no `routeSearch`.\n return router.navigate(routeName, routeParams, routeSearch, opts);\n}\n\n// Match-any-whitespace regex shared across calls. RegExp literals at\n// call-site recompile in some engines; lifting it avoids that microcost\n// for the slow-path branch.\nconst WHITESPACE_PROBE = /\\s/;\nconst WHITESPACE_SPLIT = /\\S+/g;\n\n// `value` is always a truthy class string: both call sites narrow it first\n// (`if (isActive && activeClassName)` / `if (!baseClassName) return …`), so the\n// former `if (!value) return []` guard was unreachable dead code (#809).\nfunction parseTokens(value: string): string[] {\n // Hot-path fast-path (audit-2026-05-17 §8b #1): >99% of active-class\n // inputs at `<Link>` emit are single-token strings like `\"active\"` or\n // `\"is-current\"` — no whitespace, no leading/trailing pad. Skip the\n // regex match and Array result allocation: a literal `[value]` works\n // because the slow-path `match(/\\S+/g)` would return exactly `[value]`\n // for the same input. PBT lock: linkUtils.properties.ts Invariant 13.\n if (!WHITESPACE_PROBE.test(value)) {\n return [value];\n }\n\n return value.match(WHITESPACE_SPLIT) ?? [];\n}\n\nexport function buildActiveClassName(\n isActive: boolean,\n activeClassName: string | undefined,\n baseClassName: string | undefined,\n): string | undefined {\n if (isActive && activeClassName) {\n const activeTokens = parseTokens(activeClassName);\n\n if (activeTokens.length === 0) {\n return baseClassName ?? undefined;\n }\n if (!baseClassName) {\n return activeTokens.join(\" \");\n }\n\n const baseTokens = parseTokens(baseClassName);\n const seen = new Set(baseTokens);\n\n for (const token of activeTokens) {\n if (seen.has(token)) {\n continue;\n }\n\n seen.add(token);\n baseTokens.push(token);\n }\n\n return baseTokens.join(\" \");\n }\n\n return baseClassName ?? undefined;\n}\n\n/**\n * One-level structural equality using `Object.is` per key.\n *\n * **String-keyed properties only (Mini-sprint E.3 — audit-5 §4.2 #3).**\n * Implementation walks `Object.keys()` which by spec returns only\n * enumerable own STRING keys. Symbol-keyed properties — created via\n * `obj[Symbol(\"brand\")] = value` or `{ [Symbol(...)]: value }` — are\n * NOT compared. Two records that differ only in a Symbol-keyed value\n * will compare as equal.\n *\n * This is intentional: route params and Link options are documented as\n * string-keyed primitives (string | number | boolean) — Symbol-keyed\n * metadata (e.g. brand markers, private state) doesn't belong in a\n * cache-key comparison. Switching to `Reflect.ownKeys()` would extend\n * the contract to symbols at the cost of one extra allocation per call\n * (Reflect.ownKeys composes string-keys + symbol-keys arrays). If a\n * consumer relies on symbol-keyed metadata for navigation\n * disambiguation, they should encode it into a string key instead.\n *\n * Mirrors React's `shallowEqual` (packages/shared/shallowEqual.js) in\n * both the string-keys-only semantics and the `hasOwnProperty` guard\n * below.\n */\nexport function shallowEqual(\n prev: object | undefined,\n next: object | undefined,\n): boolean {\n if (Object.is(prev, next)) {\n return true;\n }\n if (!prev || !next) {\n return false;\n }\n\n const prevKeys = objectKeys(prev);\n\n if (prevKeys.length !== objectKeys(next).length) {\n return false;\n }\n\n const prevRecord = prev as Record<string, unknown>;\n const nextRecord = next as Record<string, unknown>;\n\n for (const key of prevKeys) {\n // hasOwnProperty guard: without it, a key missing in `next` reads as\n // `undefined` and falsely matches `prev[key] === undefined`. Same shape\n // as React's shallowEqual (packages/shared/shallowEqual.js).\n if (\n !Object.prototype.hasOwnProperty.call(next, key) ||\n !Object.is(prevRecord[key], nextRecord[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function applyLinkA11y(element: HTMLElement | null | undefined): void {\n if (!element) {\n return;\n }\n\n // Cross-realm safety (audit-2026-05-17 §5 HIGH #4):\n // `instanceof HTMLAnchorElement` compares against the constructor from\n // the CURRENT realm. An element created in a different window (iframe\n // contentDocument, micro-frontend, embedded widget) fails the check\n // even when it IS a real anchor — the helper would then inject\n // role=\"link\" + tabindex=\"0\" on top of native anchor semantics,\n // breaking screen reader output (\"link link\") and focus order.\n //\n // tagName is realm-agnostic and is uppercase for HTML-namespaced\n // elements in any document. SVG `<a>` has lowercase tagName plus a\n // different prototype (SVGAElement) — skipping it here is wrong by\n // accident: SVG anchors don't have keyboard activation semantics the\n // helper would add. But they also don't reach this helper in\n // practice (router Link components emit HTML anchors). Lock the\n // uppercase compare to keep the contract narrow.\n const tag = element.tagName;\n\n if (tag === \"A\" || tag === \"BUTTON\") {\n return;\n }\n if (!element.hasAttribute(\"role\")) {\n element.setAttribute(\"role\", \"link\");\n }\n if (!element.hasAttribute(\"tabindex\")) {\n element.setAttribute(\"tabindex\", \"0\");\n }\n}\n","import { createActiveSource } from \"@real-router/sources\";\nimport { defineComponent, h, computed, shallowRef, watch } from \"vue\";\n\nimport { useRouter } from \"../composables/useRouter\";\nimport { EMPTY_PARAMS, EMPTY_OPTIONS } from \"../constants\";\nimport {\n shouldNavigate,\n buildHref,\n buildActiveClassName,\n navigateWithHash,\n resolveLinkTarget,\n shallowEqual,\n} from \"../dom-utils\";\n\nimport type {\n Params,\n NavigationOptions,\n NavigationTarget,\n SearchParams,\n} from \"@real-router/core\";\nimport type { PropType } from \"vue\";\n\ntype OnClickHandler = (evt: MouseEvent) => void;\n\n/**\n * Invoke ONE user `@click` handler in isolation (#1352). A throwing handler must\n * NOT skip the Link's own navigation (which `handleClick` runs after this\n * returns) or — in the array form — abort the remaining sibling handlers. Native\n * `<a>` logs a throwing click listener and still performs the default action;\n * this matches the codebase's adapter-callback isolation norm\n * (`RouterErrorBoundary.onError`, `EventEmitter.emit`). The user's own\n * `preventDefault()` still takes effect (it runs before any throw), so the\n * `defaultPrevented` contract below is unchanged.\n */\nfunction invokeUserOnClick(fn: OnClickHandler, evt: MouseEvent): void {\n try {\n fn(evt);\n } catch (error) {\n console.error(\n \"[real-router] A <Link> @click handler threw; navigation is unaffected.\",\n error,\n );\n }\n}\n\n/**\n * Vue's compiled template binds multiple `@click` handlers as an array.\n * Single render-function `onClick` is a function. Both must be invoked, each\n * isolated via `invokeUserOnClick` (#1352).\n *\n * The function-branch deliberately omits a `defaultPrevented` check: the\n * single call short-circuits naturally and control returns to the caller\n * (`handleClick`), which then re-reads `evt.defaultPrevented` on the same\n * MouseEvent. The array-branch needs the per-iteration check because the\n * caller cannot observe intermediate handlers — without it, later handlers\n * would still run after an earlier one called `preventDefault()`.\n */\nfunction invokeAttributesOnClick(value: unknown, evt: MouseEvent): void {\n if (typeof value === \"function\") {\n invokeUserOnClick(value as OnClickHandler, evt);\n\n return;\n }\n if (Array.isArray(value)) {\n const handlers = value as OnClickHandler[];\n\n for (const fn of handlers) {\n if (typeof fn !== \"function\") {\n continue;\n }\n\n invokeUserOnClick(fn, evt);\n\n if (evt.defaultPrevented) {\n return;\n }\n }\n }\n}\n\nexport const Link = defineComponent({\n name: \"Link\",\n // Disable Vue's automatic attribute fallthrough. Without this, attrs.onClick\n // (function OR array) is auto-attached as a native click listener AND our\n // explicit onClick fires too — user handlers are double-invoked. We invoke\n // attrs.onClick manually inside handleClick to preserve preventDefault.\n inheritAttrs: false,\n props: {\n // Optional (was required) since the descriptor form (`to`) omits it — the\n // two forms are mutually exclusive, enforced at runtime by resolveLinkTarget.\n routeName: {\n type: String,\n default: undefined,\n },\n // Descriptor form (RFC-4 M2 B2, #1548): `to={{ name, params?, search? }}`,\n // mutually exclusive with the routeName/routeParams/routeSearch channels.\n to: {\n type: Object as PropType<NavigationTarget>,\n default: undefined,\n },\n // Default `undefined` (NOT EMPTY_PARAMS): an omitted `routeParams` must reach\n // `createActiveRouteSource` as `undefined` so it keys the active source as \"\"\n // and shares ONE cached source (one router subscription) with a manual\n // `useIsActiveRoute(routeName)`. Defaulting to EMPTY_PARAMS ({}) here would key\n // \"{}\" and split the same logical question into a second eager subscription\n // (#776). Navigation/href default to EMPTY_PARAMS locally where a concrete\n // object is required.\n routeParams: {\n type: Object as PropType<Params>,\n default: undefined,\n },\n // Query (search) channel (RFC-4 M2, #1548) — parallel to routeParams.\n routeSearch: {\n type: Object as PropType<SearchParams>,\n default: undefined,\n },\n routeOptions: {\n type: Object as PropType<NavigationOptions>,\n default: () => EMPTY_OPTIONS,\n },\n class: {\n type: String,\n default: undefined,\n },\n activeClassName: {\n type: String,\n default: \"active\",\n },\n activeStrict: {\n type: Boolean,\n default: false,\n },\n ignoreQueryParams: {\n type: Boolean,\n default: true,\n },\n target: {\n type: String,\n default: undefined,\n },\n /**\n * URL fragment (decoded form, no leading \"#\") (#532).\n * - omitted/`undefined` → preserve current fragment on same-route navigation\n * - `\"\"` → clear fragment\n * - non-empty → set fragment\n */\n hash: {\n type: String,\n default: undefined,\n },\n },\n setup(props, { slots, attrs }) {\n const router = useRouter();\n\n const isActive = shallowRef(false);\n\n // Content-stable `routeParams` reference. A parent that hands an inline\n // `:routeParams=\"{ id: 1 }\"` literal allocates a fresh object on every\n // render; keying the derivations below off that raw reference would re-run\n // `buildHref` and re-subscribe the ActiveRouteSource on every unrelated\n // parent update. `shallowEqual` collapses structurally-equal params to a\n // stable reference (Object.is per key, order-insensitive — the same\n // contract as the React adapter's Link `memo` comparator), so the `href`\n // computed and the active `watch` bail out until params content actually\n // changes.\n //\n // Hot path on Link-heavy pages: this replaces a per-navigation\n // `canonicalJson` (JSON.stringify + key sort) with a per-navigation\n // `shallowEqual` (no allocation), and lets same-shape navigations skip\n // `buildHref` entirely. Nested-object param VALUES fall back to per-render\n // recompute (shallowEqual compares them by reference) — stabilize with a\n // `ref`/`computed` if it matters, exactly as documented for the React Link.\n // `Params | undefined`: `undefined` (no params) is preserved end-to-end so the\n // active source keys \"\" (see the `routeParams` prop default note, #776).\n let cachedParams: Params | undefined = props.routeParams;\n const stableParams = computed<Params | undefined>(() => {\n const next = props.routeParams;\n\n if (!shallowEqual(cachedParams, next)) {\n cachedParams = next;\n }\n\n return cachedParams;\n });\n\n // Recreate the ActiveRouteSource ONLY when the Link's identity\n // (routeName / params content / strict / ignoreQueryParams / hash) changes.\n // `stableParams` already absorbs same-content param churn, so this dep\n // array is reference-stable across navigations that don't change shape and\n // the subscription persists.\n watch(\n () =>\n [\n props.routeName,\n stableParams.value,\n props.routeSearch,\n props.to,\n props.activeStrict,\n props.ignoreQueryParams,\n props.hash,\n ] as const,\n (\n [\n routeName,\n routeParams,\n routeSearch,\n to,\n activeStrict,\n ignoreQueryParams,\n hash,\n ],\n _prev,\n onCleanup,\n ) => {\n // Resolve the two prop forms (RFC-4 M2 B2, #1548): `to` supersedes the\n // channel props (dev-warn on conflict).\n const resolved = resolveLinkTarget(\n to,\n routeName ?? \"\",\n routeParams,\n routeSearch,\n );\n\n // Hash-aware active (#532): pass hash through so tab links with the\n // same routeName but different `hash` props don't all light up.\n const source = createActiveSource(\n router,\n resolved.name,\n resolved.params,\n resolved.search,\n activeStrict,\n ignoreQueryParams,\n hash,\n );\n\n isActive.value = source.getSnapshot();\n\n const unsub = source.subscribe(() => {\n isActive.value = source.getSnapshot();\n });\n\n onCleanup(unsub);\n },\n { immediate: true, flush: \"sync\" },\n );\n\n const href = computed(() => {\n const resolved = resolveLinkTarget(\n props.to,\n props.routeName ?? \"\",\n stableParams.value,\n props.routeSearch,\n );\n\n return buildHref(\n router,\n resolved.name,\n resolved.params ?? EMPTY_PARAMS,\n resolved.search,\n props.hash,\n );\n });\n\n const finalClassName = computed(() =>\n buildActiveClassName(isActive.value, props.activeClassName, props.class),\n );\n\n const handleClick = (evt: MouseEvent) => {\n // Vue allows attrs.onClick to be a function or an array of functions\n // (compiled templates with multiple @click bindings produce arrays).\n // Both must be invoked; treating arrays as \"no handler\" silently drops\n // user code.\n if (attrs.onClick !== undefined && attrs.onClick !== null) {\n invokeAttributesOnClick(attrs.onClick, evt);\n\n if (evt.defaultPrevented) {\n return;\n }\n }\n\n if (!shouldNavigate(evt) || props.target === \"_blank\") {\n return;\n }\n\n evt.preventDefault();\n\n const resolved = resolveLinkTarget(\n props.to,\n props.routeName ?? \"\",\n props.routeParams,\n props.routeSearch,\n );\n\n navigateWithHash(\n router,\n resolved.name,\n resolved.params ?? EMPTY_PARAMS,\n resolved.search,\n props.hash,\n props.routeOptions,\n ).catch(() => {});\n };\n\n return () => {\n // Build forwarded attrs without `onClick`. Vue's runtime auto-attaches\n // attrs.onClick (function OR array) as a native DOM listener, which would\n // double-invoke user handlers when combined with our explicit `onClick`.\n // We invoke the original attrs.onClick manually inside handleClick so the\n // preventDefault contract is preserved.\n //\n // Spread + delete avoids the per-key copy loop on every render — one\n // allocation + one property deletion instead of N iterations across\n // data-*, aria-*, role, etc. Hot-path optimisation for Link-heavy pages.\n const restAttributes = { ...attrs };\n\n delete restAttributes.onClick;\n\n return h(\n \"a\",\n {\n ...restAttributes,\n href: href.value,\n class: finalClassName.value,\n target: props.target,\n onClick: handleClick,\n },\n slots.default?.(),\n );\n };\n },\n});\n","import { createDismissableError } from \"@real-router/sources\";\nimport { defineComponent, h, watch, Fragment } from \"vue\";\n\nimport { useRouter } from \"../composables/useRouter\";\nimport { useRefFromSource } from \"../useRefFromSource\";\n\nimport type { RouterError, State } from \"@real-router/core\";\nimport type { VNode, PropType } from \"vue\";\n\nexport const RouterErrorBoundary = defineComponent({\n name: \"RouterErrorBoundary\",\n props: {\n fallback: {\n type: Function as PropType<\n (error: RouterError, resetError: () => void) => VNode\n >,\n required: true,\n },\n onError: {\n type: Function as PropType<\n (\n error: RouterError,\n toRoute: State | null,\n fromRoute: State | null,\n ) => void\n >,\n default: undefined,\n },\n },\n setup(props, { slots }) {\n const router = useRouter();\n const snapshot = useRefFromSource(createDismissableError(router));\n\n watch(\n () => snapshot.value.version,\n () => {\n if (snapshot.value.error) {\n props.onError?.(\n snapshot.value.error,\n snapshot.value.toRoute,\n snapshot.value.fromRoute,\n );\n }\n },\n { immediate: true },\n );\n\n return () => {\n const children = slots.default?.() ?? [];\n const errorVNode = snapshot.value.error\n ? props.fallback(snapshot.value.error, snapshot.value.resetError)\n : null;\n\n return h(Fragment, null, [...children, errorVNode]);\n };\n },\n});\n\nexport type RouterErrorBoundaryProps = InstanceType<\n typeof RouterErrorBoundary\n>[\"$props\"];\n","import { shouldNavigate, applyLinkA11y } from \"../dom-utils\";\n\nimport type { Router, NavigationOptions, Params } from \"@real-router/core\";\nimport type { Directive } from \"vue\";\n\nexport interface LinkDirectiveValue {\n name: string;\n params?: Params;\n options?: NavigationOptions;\n}\n\n/**\n * Router stack for nested RouterProviders. The active router is the top of\n * the stack. RouterProvider pushes its router on mount and pops it on unmount,\n * which preserves the parent context when an inner provider tears down.\n *\n * Without the stack, an unmounted child provider would leave the directive\n * pointing at a disposed router, and v-link in the still-mounted parent would\n * navigate via the wrong (or torn-down) instance.\n */\nconst routerStack: Router[] = [];\n\n/**\n * Pushes a router onto the active stack. Returns a release function that\n * removes that exact router from the stack regardless of position — safe\n * across out-of-order provider unmount sequences.\n *\n * @internal Used by RouterProvider during setup/teardown.\n */\nexport function pushDirectiveRouter(router: Router): () => void {\n routerStack.push(router);\n\n return () => {\n const idx = routerStack.lastIndexOf(router);\n\n if (idx !== -1) {\n routerStack.splice(idx, 1);\n }\n };\n}\n\n/**\n * Backwards-compatible alias. Replaces the active router unconditionally and\n * does NOT participate in the stack — use {@link pushDirectiveRouter} from\n * provider code instead. Not exported from the package entry; retained for\n * unit tests and rare standalone-directive setups (where v-link is mounted\n * outside any RouterProvider).\n *\n * @internal\n */\nexport function setDirectiveRouter(router: Router | null): void {\n if (router === null) {\n routerStack.length = 0;\n\n return;\n }\n if (routerStack.length === 0) {\n routerStack.push(router);\n\n return;\n }\n\n routerStack[routerStack.length - 1] = router;\n}\n\nexport function getDirectiveRouter(): Router {\n const top = routerStack.at(-1);\n\n if (!top) {\n throw new Error(\n \"v-link directive requires a RouterProvider ancestor. Make sure RouterProvider is mounted.\",\n );\n }\n\n return top;\n}\n\ninterface Handlers {\n click: (evt: MouseEvent) => void;\n keydown: (evt: KeyboardEvent) => void;\n}\n\n// Single WeakMap halves per-element bookkeeping vs two parallel maps.\nconst handlers = new WeakMap<HTMLElement, Handlers>();\n\n/**\n * Validates a directive binding value before attaching handlers.\n * Returns false (and warns once per call) when the value is missing or\n * has no `name` — silently doing nothing is preferable to a runtime crash\n * inside a click handler.\n */\nfunction isValidBinding(value: unknown): value is LinkDirectiveValue {\n if (value === null || value === undefined) {\n console.error(\n \"[real-router] v-link directive received null/undefined value. The element will not be wired for navigation.\",\n );\n\n return false;\n }\n if (typeof (value as { name?: unknown }).name !== \"string\") {\n console.error(\n \"[real-router] v-link directive value is missing a string `name` field. The element will not be wired for navigation.\",\n );\n\n return false;\n }\n\n return true;\n}\n\nfunction createClickHandler(\n router: Router,\n value: LinkDirectiveValue,\n): (evt: MouseEvent) => void {\n return (evt: MouseEvent) => {\n if (!shouldNavigate(evt)) {\n return;\n }\n\n evt.preventDefault();\n router\n .navigate(value.name, value.params ?? {}, undefined, value.options ?? {})\n .catch(() => {});\n };\n}\n\nfunction createKeydownHandler(\n router: Router,\n value: LinkDirectiveValue,\n element: HTMLElement,\n): (evt: KeyboardEvent) => void {\n return (evt: KeyboardEvent) => {\n if (evt.key === \"Enter\" && !(element instanceof HTMLButtonElement)) {\n router\n .navigate(\n value.name,\n value.params ?? {},\n undefined,\n value.options ?? {},\n )\n .catch(() => {});\n }\n };\n}\n\nfunction attachHandlers(\n element: HTMLElement,\n router: Router,\n value: LinkDirectiveValue,\n): void {\n const click = createClickHandler(router, value);\n const keydown = createKeydownHandler(router, value, element);\n\n element.addEventListener(\"click\", click);\n element.addEventListener(\"keydown\", keydown);\n\n handlers.set(element, { click, keydown });\n}\n\nfunction detachHandlers(element: HTMLElement): void {\n const entry = handlers.get(element);\n\n if (entry) {\n element.removeEventListener(\"click\", entry.click);\n element.removeEventListener(\"keydown\", entry.keydown);\n handlers.delete(element);\n }\n}\n\nexport const vLink: Directive<HTMLElement, LinkDirectiveValue> = {\n mounted(element, binding) {\n const router = getDirectiveRouter();\n\n applyLinkA11y(element);\n\n element.style.cursor = \"pointer\";\n\n if (!isValidBinding(binding.value)) {\n return;\n }\n\n attachHandlers(element, router, binding.value);\n },\n\n updated(element, binding) {\n // Hot-path guard: Vue invokes `updated` on every parent re-render even\n // when the directive's binding value reference has not changed. Without\n // this short-circuit, every parent rerender (which is the common case on\n // Link-heavy pages — any unrelated state change triggers the parent's\n // render fn) would detach + reattach the click/keydown listeners.\n // Comparing references is enough: when consumers pass a stable\n // `LinkDirectiveValue` object (the recommended pattern, since Vue's\n // template compiler hoists `v-link=\"{ name: 'home' }\"` to a stable\n // literal), this guard collapses the work to zero.\n if (binding.value === binding.oldValue) {\n return;\n }\n\n const router = getDirectiveRouter();\n\n detachHandlers(element);\n\n if (!isValidBinding(binding.value)) {\n return;\n }\n\n attachHandlers(element, router, binding.value);\n },\n\n beforeUnmount(element) {\n detachHandlers(element);\n },\n};\n","import { inject } from \"vue\";\n\nimport { NavigatorKey } from \"../context\";\n\nimport type { Navigator } from \"@real-router/core\";\n\nexport const useNavigator = (): Navigator => {\n const navigator = inject(NavigatorKey);\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\nexport const useRouteUtils = (): RouteUtils => {\n const router = useRouter();\n\n return getRouteUtils(getPluginApi(router).getTree());\n};\n","import { getTransitionSource } from \"@real-router/sources\";\n\nimport { useRefFromSource } from \"../useRefFromSource\";\nimport { useRouter } from \"./useRouter\";\n\nimport type { RouterTransitionSnapshot } from \"@real-router/sources\";\nimport type { ShallowRef } from \"vue\";\n\nexport function useRouterTransition(): ShallowRef<RouterTransitionSnapshot> {\n const router = useRouter();\n const source = getTransitionSource(router);\n\n return useRefFromSource(source);\n}\n","import { guardLeaveListener } from \"@real-router/sources\";\nimport { onActivated, onDeactivated, onScopeDispose } from \"vue\";\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.\n * - **Same-route skip**: by default, `route.name === nextRoute.name`\n * short-circuits the handler — query-only navigations skip the work.\n * Opt out with `skipSameRoute: false`.\n *\n * Cleanup is bound to the component's effect scope via `onScopeDispose`.\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` (that\n * arises only when the navigation's `signal` aborts).\n *\n * **Handler reactivity (Vue):** Vue composables run **once** during\n * `setup()`; `handler` is captured in closure at the call site. To vary\n * behavior over time, read refs/computeds inside the handler body — do\n * not rely on swapping the handler reference.\n *\n * **Under `<KeepAlive>` (#1221):** a deactivated (sleeping) page does not run\n * the handler on unrelated navigations — critically, its async exit is not\n * spliced into every navigation's leave cycle (where it would block the app).\n *\n * @example Animation\n * ```ts\n * const ref = useTemplateRef<HTMLDivElement>(\"box\");\n *\n * useRouteExit(async ({ signal }) => {\n * const el = ref.value;\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();\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 * ```ts\n * useRouteExit(async ({ signal }) => {\n * if (formState.value.dirty) {\n * await api.saveDraft(formState.value, { signal });\n * }\n * });\n * ```\n *\n * @example Reading rich transition metadata via `nextRoute.transition`\n * ```ts\n * useRouteExit(({ route, nextRoute }) => {\n * if (nextRoute.transition.segments.deactivated.includes(\"products\")) {\n * productCache.clear();\n * }\n * if (nextRoute.transition.redirected) return;\n * });\n * ```\n */\nexport function useRouteExit(\n handler: RouteExitHandler,\n options?: UseRouteExitOptions,\n): void {\n const router = useRouter();\n const skipSameRoute = options?.skipSameRoute ?? true;\n\n // #1221 — under <KeepAlive> a deactivated component keeps its effect scope\n // (and this subscription) alive. Gate on deactivated state so a sleeping page\n // does not run its exit handler on unrelated navigations — critically, a\n // sleeping page's async (Promise-returning) exit would otherwise be spliced\n // into every navigation's leave cycle and BLOCK it. `onActivated` /\n // `onDeactivated` only fire under KeepAlive; without it the flag stays `false`\n // and the subscription runs as before. The page being LEFT is still active\n // when its own leave window runs (deactivation happens on the subsequent\n // commit), so a genuine exit still fires.\n let isDeactivated = false;\n\n onActivated(() => {\n isDeactivated = false;\n });\n onDeactivated(() => {\n isDeactivated = true;\n });\n\n // The same-route + reentrant-abort guards and the Promise passthrough live in\n // the shared listener (@real-router/sources, #1435); the handler is captured\n // at init (Vue's setup runs once).\n const guardedLeave = guardLeaveListener(handler, { skipSameRoute });\n\n const off = router.subscribeLeave((leaveState) => {\n // The #1221 KeepAlive pre-gate stays adapter-side and composes BEFORE the\n // shared guards — a deactivated (sleeping) page must never enter the leave\n // cycle (its async exit would otherwise be spliced into every navigation and\n // block it).\n if (isDeactivated) {\n return;\n }\n\n return guardedLeave(leaveState);\n });\n\n onScopeDispose(off);\n}\n","import { createRouteEnterGate } from \"@real-router/sources\";\nimport { onActivated, onDeactivated, watch } from \"vue\";\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 composable covers that an ad-hoc `watch` + `useRoute()`\n * doesn't:\n *\n * - **Skip-initial**: `watch` (with default `immediate: false`) plus the\n * explicit `route.transition.from` guard ensures the handler doesn't\n * fire on the very first state committed by `router.start()`.\n * - **Same-route skip** (default): handler is skipped when\n * `route.transition.from === route.name`. Sort/filter/query-only\n * navigations re-trigger the watcher, but they are not \"entries\" in\n * the animation / analytics sense. Opt out with\n * `skipSameRoute: false`.\n * - **Mount-time `route` / `previousRoute` snapshot**: handler receives\n * the values that were live at the moment of the new state, not the\n * latest ones (which may have moved on if the user navigated again\n * before the watcher drained).\n *\n * **Handler reactivity (Vue):** Vue composables run **once** during\n * `setup()`; `handler` is captured in closure at the call site. To vary\n * behavior over time, read refs/computeds inside the handler body.\n *\n * **Under `<KeepAlive>` (#1221):** a deactivated (sleeping) page does not fire\n * the handler on unrelated navigations, and waking it does not re-fire —\n * reactivation is not a mount (use Vue's native `onActivated` to re-run on show).\n *\n * @example Direction-aware entry animation\n * ```ts\n * useRouteEnter(({ route }) => {\n * const direction = route.context.browser?.direction;\n * ref.value?.classList.add(\n * direction === \"back\" ? \"slide-from-left\" : \"slide-from-right\",\n * );\n * });\n * ```\n *\n * @example Analytics page-enter event (skip-initial built-in)\n * ```ts\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 * ```ts\n * useRouteEnter(({ route }) => {\n * if (route.transition.redirected) {\n * showToast(`Redirected from ${route.transition.from}`);\n * }\n * });\n * ```\n */\nexport function useRouteEnter(\n handler: RouteEnterHandler,\n options?: UseRouteEnterOptions,\n): void {\n const { route, previousRoute } = useRoute();\n const skipSameRoute = options?.skipSameRoute ?? true;\n // The canonical enter-guard set + `lastHandledRoute` dedupe live in the shared\n // gate (@real-router/sources, #1435). Vue's setup runs once, so a plain const\n // holds the gate across watcher runs. The gate owns skip-initial / same-route\n // / dedupe / the `!previousRoute` guard — the sole defense of the non-nullable\n // `RouteEnterContext.previousRoute` contract (#1218), now tested once in\n // sources rather than v8-ignored per adapter. (In Vue both skip-initial and\n // `!prev` are in fact unreachable — `watch` defaults to `immediate: false`, so\n // the initial commit and the undefined-`previousRoute` baseline are never\n // observed — but the gate arms them uniformly for cross-adapter parity.)\n const gate = createRouteEnterGate();\n\n // #1221 — under <KeepAlive> a deactivated component keeps its effect scope\n // (and this watcher) alive, so a sleeping page would otherwise fire `handler`\n // on every unrelated app navigation. This pre-gate stays adapter-side: the\n // framework-free gate has no channel to observe Vue's deactivation lifecycle.\n // `onActivated` / `onDeactivated` only fire under KeepAlive; without it the\n // flag stays `false` and the watcher runs exactly as before. Reactivating a\n // kept-alive page does NOT re-fire enter (strict-mount): this watcher flushes\n // before `onActivated`, so the flag is still `true` when the reactivating\n // navigation lands — waking a never-unmounted page is not a mount.\n let isDeactivated = false;\n\n onActivated(() => {\n isDeactivated = false;\n });\n onDeactivated(() => {\n isDeactivated = true;\n });\n\n watch(route, (newRoute) => {\n if (isDeactivated) {\n return;\n }\n\n const context = gate(newRoute, previousRoute.value, skipSameRoute);\n\n if (context) {\n handler(context);\n }\n });\n}\n","// packages/vue/src/setupRouteProvision.ts\n\nimport { getNavigator } from \"@real-router/core\";\nimport { createRouteSource } from \"@real-router/sources\";\nimport { shallowRef } from \"vue\";\n\nimport type { Router, Navigator, State } from \"@real-router/core\";\nimport type { ShallowRef } from \"vue\";\n\n/**\n * Shared setup for `RouterProvider` (component-scoped) and\n * `createRouterPlugin` (app-scoped). Builds the reactive route refs +\n * subscription bookkeeping in one place; callers wire the result into their\n * provide/inject mechanism and own teardown lifecycle.\n *\n * @internal\n */\nexport interface RouteProvision {\n navigator: Navigator;\n route: ShallowRef<State | undefined>;\n previousRoute: ShallowRef<State | undefined>;\n /** Call when the owning scope tears down to release the router subscription. */\n unsubscribe: () => void;\n}\n\nexport function setupRouteProvision(router: Router): RouteProvision {\n const navigator = getNavigator(router);\n const source = createRouteSource(router);\n const initial = source.getSnapshot();\n\n const route = shallowRef<State | undefined>(initial.route);\n const previousRoute = shallowRef<State | undefined>(initial.previousRoute);\n\n const unsubscribe = source.subscribe(() => {\n const snapshot = source.getSnapshot();\n\n route.value = snapshot.route;\n previousRoute.value = snapshot.previousRoute;\n });\n\n return { navigator, route, previousRoute, unsubscribe };\n}\n","import { NavigatorKey, RouteKey, RouterKey } from \"./context\";\nimport { pushDirectiveRouter } from \"./directives/vLink\";\nimport { setupRouteProvision } from \"./setupRouteProvision\";\n\nimport type { Router } from \"@real-router/core\";\nimport type { App, Plugin } from \"vue\";\n\nexport function createRouterPlugin(router: Router): Plugin<[]> {\n return {\n install(app): void {\n const releaseDirective = pushDirectiveRouter(router);\n\n const { navigator, route, previousRoute, unsubscribe } =\n setupRouteProvision(router);\n\n // Vue 3.5+ exposes app.onUnmount for plugin cleanup.\n // On older versions (3.3–3.4), the subscription is cleaned up\n // when the router is garbage-collected (same as vue-router).\n if (\"onUnmount\" in app) {\n (app as App & { onUnmount: (fn: () => void) => void }).onUnmount(() => {\n releaseDirective();\n unsubscribe();\n });\n }\n\n app.provide(RouterKey, router);\n app.provide(NavigatorKey, navigator);\n app.provide(RouteKey, { navigator, route, previousRoute });\n },\n };\n}\n","import { primeErrorSource } from \"@real-router/sources\";\nimport { defineComponent, onScopeDispose, provide, watch } from \"vue\";\n\nimport { NavigatorKey, RouteKey, RouterKey } from \"./context\";\nimport { pushDirectiveRouter } from \"./directives/vLink\";\nimport {\n createRouteAnnouncer,\n createScrollRestoration,\n createScrollSpy,\n createViewTransitions,\n} from \"./dom-utils\";\nimport { setupRouteProvision } from \"./setupRouteProvision\";\n\nimport type {\n RouteAnnouncerOptions,\n ScrollRestorationOptions,\n ScrollSpyOptions,\n} from \"./dom-utils\";\nimport type { Router } from \"@real-router/core\";\nimport type { PropType } from \"vue\";\n\ninterface Disposable {\n destroy: () => void;\n}\n\n/**\n * Watch a dependency tuple and (re)create a toggleable utility (announcer /\n * scroll-restorer / view-transitions). The factory returns `undefined` to\n * mean \"feature disabled\" — no utility is created and no cleanup is wired.\n * When a utility IS returned, its `destroy()` is registered via `onCleanup`,\n * so flipping any dep (incl. the feature flag) tears down the previous\n * instance before constructing the next.\n *\n * Extracted from three near-identical `watch(... { immediate: true })` blocks\n * (announceNavigation / scrollRestoration / viewTransitions) — DRY without\n * losing the per-utility dep tuple shape.\n */\nfunction watchToggleableUtility<D extends readonly unknown[]>(\n deps: () => D,\n factory: (current: D) => Disposable | undefined,\n): void {\n watch(\n deps,\n (current, _prev, onCleanup) => {\n const utility = factory(current);\n\n if (utility) {\n onCleanup(() => {\n utility.destroy();\n });\n }\n },\n { immediate: true },\n );\n}\n\nexport const RouterProvider = defineComponent({\n name: \"RouterProvider\",\n props: {\n router: {\n type: Object as PropType<Router>,\n required: true,\n },\n announceNavigation: {\n type: [Boolean, Object] as PropType<boolean | RouteAnnouncerOptions>,\n default: false,\n },\n scrollRestoration: {\n type: Object as PropType<ScrollRestorationOptions>,\n },\n scrollSpy: {\n type: Object as PropType<ScrollSpyOptions>,\n },\n viewTransitions: {\n type: Boolean,\n default: false,\n },\n },\n setup(props, { slots }) {\n // Reactive announceNavigation: setting prop true/false at runtime\n // creates/destroys the announcer accordingly. Prior implementation read\n // the prop only inside onMounted, so toggling it post-mount silently no-op'd.\n // `announceNavigation` accepts `true` (default announcer) or a\n // `RouteAnnouncerOptions` object (`{ prefix, getAnnouncementText }`) for\n // custom announcement text. `false` / `undefined` disables it. Watched by\n // primitives (enabled + prefix) so inline-object identity churn doesn't\n // re-create the announcer; getAnnouncementText is captured once by the\n // utility (same rationale as scrollContainer below).\n watchToggleableUtility(\n () => {\n const nav = props.announceNavigation;\n const enabled = nav !== false;\n const prefix = typeof nav === \"object\" ? nav.prefix : undefined;\n\n return [props.router, enabled, prefix] as const;\n },\n ([router, enabled]) => {\n const nav = props.announceNavigation;\n const options = typeof nav === \"object\" ? nav : undefined;\n\n return enabled ? createRouteAnnouncer(router, options) : undefined;\n },\n );\n\n // Watch by primitives so inline `{ mode: \"restore\" }` doesn't thrash.\n // scrollContainer is a getter invoked lazily on every event inside the\n // utility — swapping its reference doesn't change the resolved element,\n // so we intentionally omit it from watched sources.\n watchToggleableUtility(\n () =>\n [\n props.router,\n props.scrollRestoration !== undefined,\n props.scrollRestoration?.mode,\n props.scrollRestoration?.anchorScrolling,\n props.scrollRestoration?.behavior,\n props.scrollRestoration?.storageKey,\n ] as const,\n ([router, enabled, mode, anchorScrolling, behavior, storageKey]) => {\n if (!enabled) {\n return;\n }\n\n return createScrollRestoration(router, {\n mode,\n anchorScrolling,\n behavior,\n storageKey,\n scrollContainer: props.scrollRestoration?.scrollContainer,\n });\n },\n );\n\n // Reactive scrollSpy: watch by primitives, omit scrollContainer getter\n // identity for the same reason scrollRestoration does.\n watchToggleableUtility(\n () =>\n [\n props.router,\n props.scrollSpy !== undefined && props.scrollSpy.selector !== \"\",\n props.scrollSpy?.selector,\n props.scrollSpy?.rootMargin,\n ] as const,\n ([router, enabled, selector, rootMargin]) => {\n if (!enabled || !selector) {\n return;\n }\n\n return createScrollSpy(router, {\n selector,\n rootMargin,\n scrollContainer: props.scrollSpy?.scrollContainer,\n });\n },\n );\n\n // Reactive viewTransitions: toggling prop creates/destroys the utility.\n watchToggleableUtility(\n () => [props.router, props.viewTransitions] as const,\n ([router, enabled]) =>\n enabled ? createViewTransitions(router) : undefined,\n );\n\n // Push this provider's router on the v-link directive stack so nested\n // RouterProviders behave like nested DI scopes (LIFO). Release on unmount\n // restores the outer router for any v-link still mounted in the parent.\n //\n // #779: only push in the browser. The v-link directive runs solely in\n // mounted client DOM, so the server never reads the stack — while\n // onScopeDispose (the release hook) never fires during renderToString, so a\n // server-side push would strand every per-request router in this\n // module-level array, a leak router.dispose() cannot clear. `typeof\n // document` mirrors the SSR guard used across shared/dom-utils. The release\n // gets its own onScopeDispose so the server path leaves no dead teardown\n // branch (a combined callback would only ever run on the client).\n const releaseDirective =\n typeof document === \"undefined\"\n ? undefined\n : pushDirectiveRouter(props.router);\n\n if (releaseDirective) {\n onScopeDispose(releaseDirective);\n }\n\n // #778 P2: eagerly create the per-router error source at Provider mount so a\n // navigation error that fires BEFORE a RouterErrorBoundary mounts (a lazy app\n // shell, a failed boot navigation) is still captured. The boundary's\n // createDismissableError reuses this cached source and catches up (#765);\n // without it the error source is created lazily on boundary mount — after the\n // error — and never sees it.\n primeErrorSource(props.router);\n\n const { navigator, route, previousRoute, unsubscribe } =\n setupRouteProvision(props.router);\n\n onScopeDispose(unsubscribe);\n\n provide(RouterKey, props.router);\n provide(NavigatorKey, navigator);\n provide(RouteKey, { navigator, route, previousRoute });\n\n return () => slots.default?.();\n },\n});\n"],"mappings":"4QAKA,SAAS,GAAa,CACpB,OAAO,IACT,CAEA,MAAa,GAAA,EAAA,EAAA,gBAAA,CAAwB,CACnC,KAAM,kBACN,MAAO,CACL,QAAS,CACP,KAAM,OACN,SAAU,EACZ,EACA,MAAO,CACL,KAAM,QACN,QAAS,EACX,EACA,SAAU,CACR,KAAM,CAAC,OAAQ,QAAQ,EACvB,QAAS,IAAA,EACX,EACA,UAAW,CACT,KAAM,QACN,QAAS,EACX,CACF,EACA,OAAQ,CACV,CAAC,EAiBY,GAXP,EAAA,EAAA,gBAAA,CAA2B,CAC/B,KAAM,iBACN,MAAO,CACL,SAAU,CACR,KAAM,CAAC,OAAQ,QAAQ,EACvB,QAAS,IAAA,EACX,CACF,EACA,OAAQ,CACV,CAEoB,EAEP,GAAA,EAAA,EAAA,gBAAA,CAA2B,CACtC,KAAM,qBACN,OAAQ,CACV,CAAC,EC5CK,EAAqC,IAAI,IAAI,CAAC,EAAO,EAAM,CAAQ,CAAC,EACpE,EAA0C,IAAI,IAAI,CACtD,GACA,GACA,YACF,CAAC,EAUD,SAAgB,EACd,EACA,EACA,EACS,CAKT,OAJI,EACK,IAAc,GAGvB,EAAA,EAAA,kBAAA,CAAyB,EAAW,CAAe,CACrD,CASA,SAAgB,EAAmB,EAAyB,CAC1D,OAAO,EAAkB,IAAI,CAAK,CACpC,CAEA,SAAS,EAAkB,EAA4B,CACrD,GAAI,MAAM,QAAQ,CAAQ,EAAG,CAC3B,IAAM,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AAA,QAAA,CAAQC,EAAAA,EAAW,EAAM,MAAM,GAC/B,EAAA,EAAA,QAAA,CAAQC,EAAAA,EAAc,CAAS,GAC/B,EAAA,EAAA,QAAA,CAAQC,EAAAA,EAAU,CAAE,YAAW,QAAO,eAAc,CAAC,MAExC,EAAM,UAAU,CAC/B,CACF,CAAC"}
1
+ {"version":3,"file":"index.js","names":["Fragment","UNKNOWN_ROUTE","RouterKey","suspenseComponent","KeepAlive","Fragment","NOOP_INSTANCE","objectKeys","NOOP_INSTANCE","NOOP_INSTANCE","Fragment","NavigatorKey","useRoute","RouterKey","NavigatorKey","RouteKey","RouterKey","NavigatorKey","RouteKey"],"sources":["../../src/components/RouteView/components.ts","../../src/components/RouteView/helpers.ts","../../src/useRefFromSource.ts","../../src/composables/useRouter.ts","../../src/composables/useRouteNode.ts","../../src/components/RouteView/RouteView.ts","../../src/constants.ts","../../../../shared/dom-utils/route-announcer.ts","../../../../shared/dom-utils/scroll-restore.ts","../../../../shared/dom-utils/scroll-spy.ts","../../../../shared/dom-utils/view-transitions.ts","../../../../shared/dom-utils/link-utils.ts","../../src/components/Link.ts","../../src/components/RouterErrorBoundary.ts","../../src/directives/vLink.ts","../../src/composables/useNavigator.ts","../../src/composables/useRouteUtils.ts","../../src/composables/useRouterTransition.ts","../../src/composables/useRouteExit.ts","../../src/composables/useRouteEnter.ts","../../src/setupRouteProvision.ts","../../src/createRouterPlugin.ts","../../src/RouterProvider.ts"],"sourcesContent":["import { defineComponent } from \"vue\";\n\nimport type { SelfProps } from \"./types\";\nimport type { FunctionalComponent, PropType, VNode } from \"vue\";\n\nfunction renderNull() {\n return null;\n}\n\nexport const Match = defineComponent({\n name: \"RouteView.Match\",\n props: {\n segment: {\n type: String as PropType<string>,\n required: true,\n },\n exact: {\n type: Boolean,\n default: false,\n },\n fallback: {\n type: [Object, Function] as PropType<VNode | (() => VNode)>,\n default: undefined,\n },\n keepAlive: {\n type: Boolean,\n default: false,\n },\n },\n render: renderNull,\n});\n\n// Type Self via FunctionalComponent<SelfProps> so the SelfProps interface\n// is anchored to the component contract — knip otherwise flags SelfProps\n// as unused even though it's re-exported as RouteViewSelfProps for\n// consumers wrapping Self in custom HOCs.\nconst SelfImpl = defineComponent({\n name: \"RouteView.Self\",\n props: {\n fallback: {\n type: [Object, Function] as PropType<VNode | (() => VNode)>,\n default: undefined,\n },\n },\n render: renderNull,\n});\n\nexport const Self = SelfImpl as unknown as FunctionalComponent<SelfProps>;\n\nexport const NotFound = defineComponent({\n name: \"RouteView.NotFound\",\n render: renderNull,\n});\n","import { UNKNOWN_ROUTE } from \"@real-router/core\";\nimport { startsWithSegment } from \"@real-router/route-utils\";\nimport { Fragment, isVNode } from \"vue\";\n\nimport { Match, NotFound, Self } from \"./components\";\n\nimport type { VNode } from \"vue\";\n\nconst MARKER_TYPES: ReadonlySet<unknown> = new Set([Match, Self, NotFound]);\nconst KEEP_ALIVE_VALUES: ReadonlySet<unknown> = new Set([\n true,\n \"\",\n \"keep-alive\",\n]);\n\ntype FallbackType = VNode | (() => VNode) | undefined;\n\ninterface FallbackSlots {\n selfVNode: VNode | null;\n selfFallback: FallbackType;\n notFoundVNode: VNode | null;\n}\n\nexport function isSegmentMatch(\n routeName: string,\n fullSegmentName: string,\n exact: boolean,\n): boolean {\n if (exact) {\n return routeName === fullSegmentName;\n }\n\n return startsWithSegment(routeName, fullSegmentName);\n}\n\n// Vue compiles boolean-shorthand template attributes (`<Match keepAlive>`) to\n// an empty string instead of `true`, and converts them to `true` only when the\n// receiving component's prop is declared with `type: Boolean`. `Match` is a\n// marker component (`render: null`) — its props are inspected on the VNode\n// without ever going through Vue's prop-casting pipeline, so the raw `\"\"` (or\n// the hyphenated attribute name) reaches us here. Accept the same trio Vue's\n// runtime does.\nexport function isKeepAliveEnabled(value: unknown): boolean {\n return KEEP_ALIVE_VALUES.has(value);\n}\n\nfunction normalizeChildren(children: unknown): VNode[] {\n if (Array.isArray(children)) {\n const result: VNode[] = [];\n\n for (const child of children) {\n if (Array.isArray(child)) {\n result.push(...normalizeChildren(child));\n } else if (isVNode(child)) {\n result.push(child);\n }\n }\n\n return result;\n }\n\n if (isVNode(children)) {\n return [children];\n }\n\n return [];\n}\n\nexport function collectElements(children: unknown, result: VNode[]): void {\n const vnodes = normalizeChildren(children);\n\n for (const child of vnodes) {\n if (MARKER_TYPES.has(child.type)) {\n result.push(child);\n } else if (child.type === Fragment) {\n collectElements(child.children, result);\n }\n }\n}\n\nfunction recordFallback(child: VNode, slots: FallbackSlots): boolean {\n if (child.type === NotFound) {\n // First-wins: store the FIRST NotFound VNode, ignore later ones — symmetric\n // with <Self> below and the React/Preact/Solid adapters (#1439). Store the\n // VNode (never null for a real marker), not `child.children` (null for a\n // childless <NotFound/>), so the assign-once guard cannot be defeated.\n slots.notFoundVNode ??= child;\n\n return true;\n }\n\n if (child.type === Self) {\n if (slots.selfVNode === null) {\n slots.selfVNode = child;\n const props = child.props as { fallback?: FallbackType } | null;\n\n slots.selfFallback = props?.fallback;\n }\n\n return true;\n }\n\n return false;\n}\n\nfunction evaluateMatch(\n child: VNode,\n routeName: string,\n nodeName: string,\n): { isActive: boolean; fallback: FallbackType } {\n const props = child.props as {\n segment: string;\n exact?: boolean;\n fallback?: FallbackType;\n } | null;\n const segment = props?.segment ?? \"\";\n const exact = props?.exact ?? false;\n const fullSegmentName = nodeName ? `${nodeName}.${segment}` : segment;\n const isActive = isSegmentMatch(routeName, fullSegmentName, exact);\n\n return { isActive, fallback: props?.fallback };\n}\n\nfunction appendFallback(\n rendered: VNode[],\n routeName: string,\n nodeName: string,\n slots: FallbackSlots,\n): FallbackType {\n if (slots.selfVNode !== null && routeName === nodeName) {\n rendered.push(slots.selfVNode);\n\n return slots.selfFallback;\n }\n\n if (routeName === UNKNOWN_ROUTE && slots.notFoundVNode !== null) {\n rendered.push(slots.notFoundVNode);\n }\n\n return undefined;\n}\n\nexport function buildRenderList(\n elements: VNode[],\n routeName: string,\n nodeName: string,\n): {\n rendered: VNode[];\n activeMatchFound: boolean;\n fallback?: FallbackType;\n /**\n * True iff any `<Match>` child in the input has its `keepAlive` prop set\n * to one of Vue's accepted boolean-shorthand forms. Surfaced as a\n * side-channel from the single pipeline pass so the caller doesn't have\n * to re-iterate `elements` after `buildRenderList` returns — closes a MED\n * code-quality finding (audit §8.1).\n */\n hasPerMatchKA: boolean;\n} {\n const slots: FallbackSlots = {\n selfVNode: null,\n selfFallback: undefined,\n notFoundVNode: null,\n };\n let activeMatchFound = false;\n let fallback: FallbackType;\n let hasPerMatchKA = false;\n const rendered: VNode[] = [];\n\n for (const child of elements) {\n // Match-only side-channel: scan for the keepAlive shorthand in the same\n // pass that already inspects every child. Short-circuits once a positive\n // is found to avoid redundant prop reads in big slot trees.\n if (!hasPerMatchKA && child.type === Match) {\n const matchProps = child.props as { keepAlive?: unknown } | null;\n\n if (isKeepAliveEnabled(matchProps?.keepAlive)) {\n hasPerMatchKA = true;\n }\n }\n\n if (recordFallback(child, slots)) {\n continue;\n }\n\n if (activeMatchFound) {\n continue;\n }\n\n const result = evaluateMatch(child, routeName, nodeName);\n\n if (result.isActive) {\n activeMatchFound = true;\n fallback = result.fallback;\n rendered.push(child);\n }\n }\n\n if (!activeMatchFound) {\n fallback = appendFallback(rendered, routeName, nodeName, slots);\n }\n\n return { rendered, activeMatchFound, fallback, hasPerMatchKA };\n}\n","import { shallowRef, onScopeDispose } from \"vue\";\n\nimport type { RouterSource } from \"@real-router/sources\";\nimport type { ShallowRef } from \"vue\";\n\nexport function useRefFromSource<T>(\n // Only `subscribe` + `getSnapshot` are consumed — teardown goes through the\n // `subscribe` unsub via `onScopeDispose`, never `source.destroy`. Narrowing to\n // this shape lets the #1250 name-selector fast path pass a 2-method wrapper\n // (no dead `destroy` needed); full `RouterSource`s still satisfy it.\n source: Pick<RouterSource<T>, \"subscribe\" | \"getSnapshot\">,\n): ShallowRef<T> {\n const ref = shallowRef(source.getSnapshot());\n\n const unsub = source.subscribe(() => {\n ref.value = source.getSnapshot();\n });\n\n onScopeDispose(unsub);\n\n return ref;\n}\n","import { inject } from \"vue\";\n\nimport { RouterKey } from \"../context\";\n\nimport type { Router } from \"@real-router/core\";\n\nexport const useRouter = (): Router => {\n const router = inject(RouterKey);\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 { computed } from \"vue\";\n\nimport { useRefFromSource } from \"../useRefFromSource\";\nimport { useRouter } from \"./useRouter\";\n\nimport type { RouteContext } from \"../types\";\n\nexport function useRouteNode(nodeName: string): RouteContext {\n const router = useRouter();\n\n const source = createRouteNodeSource(router, nodeName);\n const snapshot = useRefFromSource(source);\n\n // getNavigator is WeakMap-cached in core; no useMemo equivalent needed.\n const navigator = getNavigator(router);\n\n // Derive route/previousRoute via computed instead of mirroring with a sync\n // watch into two extra shallowRefs. computed shares snapshot's identity so\n // when the underlying source emits the same reference (idempotent or\n // out-of-node nav), consumers don't see a new ref.\n const route = computed(() => snapshot.value.route);\n const previousRoute = computed(() => snapshot.value.previousRoute);\n\n return {\n navigator,\n route,\n previousRoute,\n };\n}\n","import {\n Fragment,\n defineComponent,\n h,\n KeepAlive,\n markRaw,\n Suspense,\n} from \"vue\";\n\nimport { Match, NotFound, Self } from \"./components\";\nimport {\n buildRenderList,\n collectElements,\n isKeepAliveEnabled,\n} from \"./helpers\";\nimport { useRouteNode } from \"../../composables/useRouteNode\";\n\nimport type { Component, VNode } from \"vue\";\n\ntype SlotChildren = Record<string, (() => VNode[]) | undefined> | null;\n\nfunction getSlotContent(vnode: VNode): VNode[] | null {\n const slots = vnode.children as SlotChildren;\n\n return slots?.default?.() ?? null;\n}\n\nfunction getOrCreateWrapper(\n cache: Map<string, Component>,\n segment: string,\n): Component {\n const existing = cache.get(segment);\n\n if (existing) {\n return existing;\n }\n\n const wrapper = markRaw(\n defineComponent({\n name: `KeepAlive-${segment}`,\n setup(_wrapperProps, wrapperCtx) {\n return () => wrapperCtx.slots.default?.();\n },\n }),\n );\n\n cache.set(segment, wrapper);\n\n return wrapper;\n}\n\nfunction wrapWithSuspense(content: VNode, fallback: unknown): VNode {\n if (fallback === undefined) {\n return content;\n }\n\n const fallbackContent =\n typeof fallback === \"function\" ? (fallback as () => VNode)() : fallback;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment\n const suspenseComponent = Suspense as any;\n\n return h(\n suspenseComponent,\n {},\n {\n default: () => content,\n fallback: () => fallbackContent,\n },\n );\n}\n\n// Lazy-initialised — only allocated when a per-Match keepAlive path needs to\n// keep the cache slot \"occupied\" with a no-render placeholder. Apps without\n// keepAlive never pay the markRaw + defineComponent allocation at import.\nlet emptyKeepAlivePlaceholderInstance: Component | null = null;\n\nfunction getEmptyKeepAlivePlaceholder(): Component {\n emptyKeepAlivePlaceholderInstance ??= markRaw(\n defineComponent({\n name: \"KeepAlive-placeholder\",\n render() {\n return null;\n },\n }),\n );\n\n return emptyKeepAlivePlaceholderInstance;\n}\n\nfunction renderWithRootKA(\n activeChild: VNode,\n wrapperCache: Map<string, Component>,\n fallback: unknown,\n): VNode {\n const activeProps = activeChild.props as { segment?: string } | null;\n const segment = activeProps?.segment ?? \"__not-found__\";\n const WrapperComponent = getOrCreateWrapper(wrapperCache, segment);\n const slotContent = getSlotContent(activeChild) ?? [];\n const keepAliveContent = h(KeepAlive, null, {\n default: () =>\n h(WrapperComponent, { key: segment }, { default: () => slotContent }),\n });\n\n return wrapWithSuspense(keepAliveContent, fallback);\n}\n\nfunction renderWithPerMatchKA(\n activeChild: VNode,\n wrapperCache: Map<string, Component>,\n fallback: unknown,\n): VNode | null {\n const matchProps = activeChild.props as {\n segment?: string;\n keepAlive?: unknown;\n } | null;\n\n if (isKeepAliveEnabled(matchProps?.keepAlive) && activeChild.type === Match) {\n /* v8 ignore start */\n const segment = matchProps?.segment ?? \"__not-found__\";\n /* v8 ignore stop */\n const WrapperComponent = getOrCreateWrapper(wrapperCache, segment);\n const slotContent = getSlotContent(activeChild) ?? [];\n\n return h(Fragment, [\n h(KeepAlive, null, {\n default: () =>\n h(WrapperComponent, { key: segment }, { default: () => slotContent }),\n }),\n ]);\n }\n\n const content = getSlotContent(activeChild);\n\n /* v8 ignore start */\n if (!content) {\n return null;\n }\n /* v8 ignore stop */\n\n return h(Fragment, [\n h(KeepAlive, null, {\n default: () => h(getEmptyKeepAlivePlaceholder()),\n }),\n wrapWithSuspense(h(Fragment, content), fallback),\n ]);\n}\n\nconst RouteViewComponent = defineComponent({\n name: \"RouteView\",\n props: {\n nodeName: {\n type: String,\n required: true,\n },\n keepAlive: {\n type: Boolean,\n default: false,\n },\n },\n setup(props, { slots }) {\n const routeContext = useRouteNode(props.nodeName);\n const wrapperCache = new Map<string, Component>();\n\n return (): VNode | null => {\n const route = routeContext.route.value;\n\n if (!route) {\n return null;\n }\n\n const slotOutput = slots.default?.();\n const elements: VNode[] = [];\n\n collectElements(slotOutput, elements);\n\n // `hasPerMatchKA` is a side-channel produced by the same pipeline pass\n // that builds `rendered` — closes the audit §8.1 \"double iteration\"\n // finding. The previous identity-cache on `slotOutput` is no longer\n // needed: per-render cost is one O(n) walk instead of two.\n const { rendered, fallback, hasPerMatchKA } = buildRenderList(\n elements,\n route.name,\n props.nodeName,\n );\n\n if (rendered.length === 0) {\n return null;\n }\n\n const activeChild = rendered[0];\n\n if (props.keepAlive) {\n return renderWithRootKA(activeChild, wrapperCache, fallback);\n }\n\n /* v8 ignore start */\n if (\n activeChild.type !== Match &&\n activeChild.type !== Self &&\n activeChild.type !== NotFound\n ) {\n return null;\n }\n /* v8 ignore stop */\n\n if (hasPerMatchKA) {\n return renderWithPerMatchKA(activeChild, wrapperCache, fallback);\n }\n\n const content = getSlotContent(activeChild);\n\n if (!content) {\n return null;\n }\n\n return wrapWithSuspense(h(Fragment, content), fallback);\n };\n },\n});\n\nexport const RouteView = Object.assign(RouteViewComponent, {\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","/**\n * Stable empty object for default params\n */\nexport const EMPTY_PARAMS = Object.freeze({});\n\n/**\n * Stable empty options object\n */\nexport const EMPTY_OPTIONS = Object.freeze({});\n","import type { Router, State } from \"@real-router/core\";\n\nconst CLEAR_DELAY = 7000;\nconst SAFARI_READY_DELAY = 100;\nconst ANNOUNCER_ATTR = \"data-real-router-announcer\";\nconst INTERNAL_ROUTE_PREFIX = \"@@\";\nconst VISUALLY_HIDDEN =\n \"position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);clip-path:inset(50%);white-space:nowrap;border:0\";\n\nexport interface RouteAnnouncerOptions {\n prefix?: string;\n getAnnouncementText?: (route: State) => string;\n}\n\nconst NOOP_INSTANCE: { destroy: () => void } = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\n// Live (non-NOOP) instances sharing the single `[data-real-router-announcer]`\n// aria-live element. The element is created once by the first instance\n// (`getOrCreateAnnouncer`) and reused by the rest; it must be removed only when\n// the LAST holder is destroyed. Without this count the first provider's\n// destroy() would detach the shared node while sibling providers (micro-\n// frontends — the same multi-provider scenario `scroll-restore`'s `storageKey`\n// exists for) keep writing to the now-orphaned node → silent screen reader (#783).\nlet announcerRefCount = 0;\n// Generation token (#1217): bumped each time a FRESH shared element is created.\n// Each instance captures the generation live at construction; on destroy it\n// touches the shared refcount / element ONLY if its generation is still current.\n// A stale instance — whose element a host wiped without calling destroy() — must\n// not decrement the new generation's refcount (→ negative) or remove its live\n// element (removeAnnouncer used to query by selector = whoever is in the DOM).\nlet announcerGeneration = 0;\n\nexport function createRouteAnnouncer(\n router: Router,\n options?: RouteAnnouncerOptions,\n): { destroy: () => void } {\n // Defensive SSR / non-browser guard: in SSR (Node.js) or non-DOM\n // environments, `document` is undefined and the announcer cannot\n // attach its aria-live region. Return a frozen NOOP_INSTANCE — same\n // pattern as `createDirectionTracker`, `createScrollRestoration`, and\n // `createViewTransitions`. Without this guard, `NavigationAnnouncer`\n // component construction would throw `ReferenceError: document is not\n // defined` under `@angular/ssr` rendering, tearing down the whole SSR\n // bootstrap. Closes review-2026-05-10 §5.10 ⛔ \"NavigationAnnouncer\n // SSR mode\" MED.\n if (typeof document === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n const prefix = options?.prefix ?? \"Navigated to \";\n const getCustomText = options?.getAnnouncementText;\n\n let isInitialNavigation = true;\n let isReady = false;\n let isDestroyed = false;\n let lastAnnouncedText = \"\";\n let pendingText: string | null = null;\n let clearTimeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const { element: announcer, generation: myGeneration } =\n getOrCreateAnnouncer();\n\n announcerRefCount += 1;\n\n const doAnnounce = (text: string, h1: HTMLElement | null): void => {\n lastAnnouncedText = text;\n clearTimeout(clearTimeoutId);\n announcer.textContent = text;\n clearTimeoutId = setTimeout(() => {\n announcer.textContent = \"\";\n lastAnnouncedText = \"\";\n }, CLEAR_DELAY);\n\n manageFocus(h1);\n };\n\n // Safari-ready delay: announcing before VoiceOver wires up the aria-live region\n // causes the first announcement to be silently dropped. Wait SAFARI_READY_DELAY ms\n // before marking the announcer \"ready\" — any navigation during that window is\n // buffered in pendingText and flushed once the delay expires.\n const safariTimeoutId = setTimeout(() => {\n isReady = true;\n\n if (pendingText !== null && !isDestroyed) {\n const text = pendingText;\n\n pendingText = null;\n doAnnounce(text, document.querySelector<HTMLElement>(\"h1\"));\n }\n }, SAFARI_READY_DELAY);\n\n const unsubscribe = router.subscribe(({ route }) => {\n if (isInitialNavigation) {\n isInitialNavigation = false;\n\n return;\n }\n\n // Double rAF: waits for two paint frames so the incoming route's DOM\n // (including the new <h1>) is fully rendered before resolveText reads it.\n // Single rAF fires before the new route's template has been attached,\n // which would cause resolveText to pick up the OLD h1 or fall back to\n // document.title / route.name prematurely.\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n if (isDestroyed) {\n return;\n }\n\n const h1 = document.querySelector<HTMLElement>(\"h1\");\n const text = resolveText(route, prefix, getCustomText, h1);\n\n if (!text || text === lastAnnouncedText) {\n return;\n }\n\n if (!isReady) {\n // Defer announcement until Safari-ready window elapses (see safariTimeoutId).\n pendingText = text;\n\n return;\n }\n\n doAnnounce(text, h1);\n });\n });\n });\n\n return {\n destroy() {\n // Idempotency guard — required so the ref-count is decremented EXACTLY\n // once per instance. A double destroy() must not drop the count below the\n // number of live holders (which would detach a sibling's element, or\n // leave it attached forever).\n if (isDestroyed) {\n return;\n }\n\n isDestroyed = true;\n unsubscribe();\n clearTimeout(clearTimeoutId);\n clearTimeout(safariTimeoutId);\n\n // Ownership guard (#1217): if a host wiped the shared element out from\n // under us, the next getOrCreateAnnouncer bumped the generation for the\n // fresh element. A stale instance must NOT decrement the new generation's\n // refcount (→ negative) or remove its live element — bail if not current.\n if (myGeneration !== announcerGeneration) {\n return;\n }\n\n announcerRefCount -= 1;\n\n // Only the last holder tears down the shared element — via our captured\n // ref, not a selector query (which would delete whoever's element is\n // currently in the DOM, i.e. a newer generation's).\n if (announcerRefCount === 0) {\n removeAnnouncer(announcer);\n }\n },\n };\n}\n\nfunction getOrCreateAnnouncer(): {\n element: HTMLElement;\n generation: number;\n} {\n const existing = document.querySelector<HTMLElement>(`[${ANNOUNCER_ATTR}]`);\n\n if (existing) {\n return { element: existing, generation: announcerGeneration };\n }\n\n // Creating a FRESH element means no live instance is validly sharing one, so\n // the ref-count restarts from zero (the caller increments immediately after).\n // Without this, an element removed out from under live instances — a host\n // wiping the subtree, or a consumer test whose teardown clears the DOM\n // without calling every instance's destroy() — would leave a stale positive\n // count that prevents the new element from ever being torn down (#783).\n // The generation bump (#1217) lets the wiped element's instances recognize\n // themselves as stale so their destroy() does not touch this fresh element.\n announcerRefCount = 0;\n announcerGeneration += 1;\n\n const element = document.createElement(\"div\");\n\n element.setAttribute(\"style\", VISUALLY_HIDDEN);\n element.setAttribute(\"aria-live\", \"assertive\");\n element.setAttribute(\"aria-atomic\", \"true\");\n element.setAttribute(ANNOUNCER_ATTR, \"\");\n\n // Defensive SSR / pre-`<body>` guard: in some environments (early\n // injection, deferred-body documents, certain SSR rehydration paths)\n // `document.body` can be null when the announcer is constructed.\n // `document.body.prepend(...)` would throw `TypeError: Cannot read\n // properties of null`, tearing down the consumer's RouterProvider /\n // NavigationAnnouncer mount. Fallback to `documentElement` keeps the\n // announcer working for SR users; visual-hidden styling means there is\n // no visible artifact regardless of mount point.\n //\n // TS dom lib types `document.body` as `HTMLElement` (non-null), but\n // runtime can return null per spec. The `as` cast narrows the type to\n // include null so the `??` short-circuit is type-safe.\n ((document.body as HTMLElement | null) ?? document.documentElement).prepend(\n element,\n );\n\n return { element, generation: announcerGeneration };\n}\n\nfunction removeAnnouncer(element: HTMLElement): void {\n element.remove();\n}\n\nfunction resolveText(\n route: State,\n prefix: string,\n getCustomText: ((route: State) => string) | undefined,\n h1: HTMLElement | null,\n): string {\n if (getCustomText) {\n try {\n const customText = getCustomText(route);\n\n // Mini-sprint E.4 (audit-5 §4.2 #4) — empty-string fallback.\n // A consumer pattern like\n // getAnnouncementText: (route) => myMap[route.name] ?? \"\"\n // returns `\"\"` for routes outside the map. The subscribe loop\n // then sees an empty text and silently no-announces — screen\n // readers stay quiet without any signal to the developer. Treat\n // a falsy custom result (`\"\"` / `null` / `undefined`) as\n // \"consumer doesn't have a name for this route\" and fall through\n // to the default resolution chain (h1 → title → route name).\n if (customText) {\n return customText;\n }\n } catch (error) {\n // A throwing consumer callback inside the router's subscribe loop\n // would tear down sibling listeners — log and fall through to the\n // built-in resolution chain so the announcer keeps working.\n console.error(\n \"[real-router] getAnnouncementText threw; falling back to default resolution.\",\n error,\n );\n }\n }\n\n const h1Text = (h1?.textContent ?? \"\").trim();\n const routeName = route.name.startsWith(INTERNAL_ROUTE_PREFIX)\n ? \"\"\n : route.name;\n const rawText =\n h1Text || document.title || routeName || globalThis.location.pathname;\n\n return `${prefix}${rawText}`;\n}\n\nfunction manageFocus(h1: HTMLElement | null): void {\n if (!h1) {\n return;\n }\n\n if (!h1.hasAttribute(\"tabindex\")) {\n h1.setAttribute(\"tabindex\", \"-1\");\n }\n\n h1.focus({ preventScroll: true });\n}\n","import type { Router, State } from \"@real-router/core\";\n\n/**\n * Intrinsics captured at module load (#1971).\n *\n * ⚑ These DECIDE — they answer \"what is on this object\" for a value this module\n * did not build. Read off the live global they can be re-pointed after boot, and\n * `shared/` is the half where that fails OPEN: measured in `browser-env`, a\n * re-pointed `getPrototypeOf` admits a `Date` into `state.params` and a\n * re-pointed `keys` skips option validation entirely.\n *\n * ⚠ Capture narrows the window from \"any time after boot\" to \"before this module\n * loads\". It does not close it (#1798).\n */\nconst objectKeys = Object.keys;\n\nconst DEFAULT_STORAGE_KEY = \"real-router:scroll\";\n\n// Bounded retry budget for resolving a late-mounting scroll container on the\n// restore path. A per-route container (e.g. an `overflow:auto` div rendered\n// only on one route) can be committed to the DOM a few frames after the\n// navigation settles — heavier routes paint later than the subscribe's rAF.\n// ~10 frames (≈160ms at 60fps) comfortably covers a React commit of a large\n// route without being perceptible. See the doc-block on `restorePos`.\nconst RESTORE_RETRY_FRAMES = 10;\n\nconst NOOP_INSTANCE: { destroy: () => void } = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\nexport type ScrollRestorationMode = \"restore\" | \"top\" | \"native\";\n\nexport interface ScrollRestorationOptions {\n mode?: ScrollRestorationMode | undefined;\n anchorScrolling?: boolean | undefined;\n scrollContainer?: (() => HTMLElement | null) | undefined;\n /**\n * Scroll behavior passed to `scrollTo({ behavior })` and\n * `scrollIntoView({ behavior })`.\n *\n * - `\"auto\"` (default) — browser-defined, usually instant.\n * - `\"instant\"` — explicit instant jump (no animation).\n * - `\"smooth\"` — animated transition. Note: smooth restore on back/traverse\n * can feel disorienting if the user expects to land at the saved position\n * immediately. Recommended for `mode: \"top\"` or anchor scroll only.\n *\n * See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/ScrollToOptions/behavior).\n */\n behavior?: ScrollBehavior | undefined;\n /**\n * sessionStorage key used to persist saved scroll positions. Default:\n * `\"real-router:scroll\"`. Override only when multiple independent\n * `RouterProvider` instances share the same document and you need to\n * isolate their scroll stores (e.g. micro-frontends, embedded widgets,\n * or testing). For a single app with one provider the default is fine.\n */\n storageKey?: string | undefined;\n}\n\ninterface NavigationContext {\n direction?: \"forward\" | \"back\" | \"unknown\";\n navigationType?: \"push\" | \"replace\" | \"traverse\" | \"reload\";\n}\n\nexport function createScrollRestoration(\n router: Router,\n options?: ScrollRestorationOptions,\n): { destroy: () => void } {\n if (typeof globalThis.window === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n const mode = options?.mode ?? \"restore\";\n\n // mode \"native\" = utility does nothing. Don't flip history.scrollRestoration,\n // don't subscribe, don't register pagehide — `history.scrollRestoration`\n // stays at the browser default (\"auto\") so the browser handles scroll\n // restore natively. (Note: this is the OPPOSITE of `history.scrollRestoration\n // === \"manual\"` — utility's \"native\" leaves the DOM property at \"auto\" so\n // the browser is in charge.)\n if (mode === \"native\") {\n return NOOP_INSTANCE;\n }\n\n const anchorEnabled = options?.anchorScrolling ?? true;\n const getContainer = options?.scrollContainer;\n const behavior: ScrollBehavior = options?.behavior ?? \"auto\";\n const storageKey = options?.storageKey ?? DEFAULT_STORAGE_KEY;\n\n // Write-through in-memory cache: parse sessionStorage once per provider\n // mount, then mutate in-memory. Avoids a JSON.parse + JSON.stringify pair\n // on every subscribeLeave / pagehide event.\n let store: Record<string, number> | undefined;\n\n const loadStore = (): Record<string, number> => {\n if (store !== undefined) {\n return store;\n }\n\n // ⚑ A PROTOTYPE-LESS record, and here that is the cheap fix rather than the\n // expensive one (#1852). The key is `${route}:${json}`, so both the\n // skip-same-value READ and the write below consult a chain under a name the\n // page never chose; with no chain there is nothing to consult. Core pays for\n // the same guarantee with `putField` because its bags are read on every\n // render and V8 keeps a prototype-less object in dictionary mode — this one\n // is a small per-mount cache read a few times per navigation, so the tax is\n // expected to be negligible and no primitive needs importing.\n //\n // ⚠ \"Expected\", not measured — and the distinction is written here because\n // the sibling claim in `putField`'s docblock was published as \"not\n // measurable\" and then refuted by a better instrument. Nothing benches this\n // cache; if that changes, measure before repeating the word.\n //\n // ⚠ `JSON.parse` DEFINES, so a stored `\"__proto__\"` key arrives as ordinary\n // data either way; what this closes is the ambient half.\n try {\n const raw = sessionStorage.getItem(storageKey);\n const parsed = raw\n ? (JSON.parse(raw) as Record<string, number>)\n : undefined;\n\n store = Object.assign(\n Object.create(null) as Record<string, number>,\n parsed,\n );\n } catch {\n store = Object.create(null) as Record<string, number>;\n }\n\n return store;\n };\n\n const putPos = (key: string, pos: number): void => {\n try {\n const cached = loadStore();\n\n // Skip-same-value: when a route is left at the same scroll position it\n // already holds in the cache (e.g. tab-switching without scrolling),\n // both the in-memory write and the JSON.stringify + setItem pair are\n // no-ops. Eliminates redundant serialization on the navigation hot\n // path for the common \"click tabs without scrolling\" case.\n if (cached[key] === pos) {\n return;\n }\n\n cached[key] = pos;\n sessionStorage.setItem(storageKey, JSON.stringify(cached));\n } catch {\n // Ignore quota / security errors.\n }\n };\n\n const prevScrollRestoration = history.scrollRestoration;\n\n try {\n history.scrollRestoration = \"manual\";\n } catch {\n // Ignore — some embedded contexts may reject the assignment.\n }\n\n // Resolve the container lazily on every event so containers mounted AFTER\n // the provider still get correct scroll handling. Falls back to window when\n // the getter is absent or returns null (pre-mount).\n const readPos = (): number => {\n const element = getContainer?.();\n\n return element ? element.scrollTop : globalThis.scrollY;\n };\n\n const writePos = (top: number): void => {\n const element = getContainer?.();\n\n if (element) {\n element.scrollTo({ top, left: 0, behavior });\n } else {\n globalThis.scrollTo({ top, left: 0, behavior });\n }\n };\n\n // Restore path (back / traverse / reload). Unlike `writePos`, this tolerates a\n // scroll container that both MOUNTS and LAYS OUT a few frames AFTER the\n // navigation settles.\n //\n // The capture-side `readPos` always runs against an already-mounted DOM (the\n // route being left). On restore the target route — and its container — is\n // still being committed by the view layer. The subscribe callback schedules a\n // single rAF; for a heavy route (e.g. a long virtual list) the framework's\n // commit can land AFTER that frame. Two distinct failures follow, each losing\n // the saved position (Scenario 6 e2e, reproduced under CI's slower runner):\n //\n // 1. Container not mounted yet → `getContainer()` is `null`, the scroll\n // silently falls back to `window`, which on a container-only route has\n // nothing to scroll.\n // 2. Container mounted but its content not laid out yet → `scrollHeight`\n // is still small, so a single `scrollTo({ top })` clamps short of the\n // saved position and never re-applies once layout grows.\n //\n // With no `scrollContainer` getter the target is always `window`, present\n // from the first frame — restore in a single shot (unchanged behaviour). When\n // a getter is configured we cannot tell \"this route legitimately uses window\"\n // from \"the container is still mounting\", so re-apply the scroll on every\n // frame for a bounded budget: window as a fallback while the container is\n // absent (harmless clamp on container routes), the container itself once it\n // appears. For instant restores we stop early the moment the position sticks;\n // smooth restores animate asynchronously, so they run the full budget. The\n // frame budget is the hard backstop against an unreachable target (saved\n // position taller than the restored content).\n const restorePos = (top: number): void => {\n if (!getContainer) {\n globalThis.scrollTo({ top, left: 0, behavior });\n\n return;\n }\n\n let frames = 0;\n\n const attempt = (): void => {\n if (destroyed) {\n return;\n }\n\n const element = getContainer();\n\n if (element) {\n element.scrollTo({ top, left: 0, behavior });\n\n // Instant restore landed within rounding tolerance → done; no point\n // re-applying. Smooth restore never matches synchronously, so let it\n // ride the budget.\n if (behavior !== \"smooth\" && Math.abs(element.scrollTop - top) <= 1) {\n return;\n }\n } else {\n globalThis.scrollTo({ top, left: 0, behavior });\n }\n\n if (frames >= RESTORE_RETRY_FRAMES) {\n return;\n }\n\n frames += 1;\n requestAnimationFrame(attempt);\n };\n\n attempt();\n };\n\n const scrollToHashOrTop = (route: State): void => {\n // URL plugin path (#532): `state.context.url.hash` is the source of truth\n // when one of the URL plugins (browser-plugin / navigation-plugin) is\n // installed. The value is already DECODED — feeding it through\n // `decodeURIComponent` again would throw on a bare `%`.\n const ctxHash = (route.context as { url?: { hash?: string } } | undefined)\n ?.url?.hash;\n\n if (ctxHash !== undefined) {\n if (anchorEnabled && ctxHash.length > 0) {\n // eslint-disable-next-line unicorn/prefer-query-selector -- ids may contain CSS-unsafe chars\n const element = document.getElementById(ctxHash);\n\n if (element) {\n element.scrollIntoView({ behavior });\n\n return;\n }\n }\n\n writePos(0);\n\n return;\n }\n\n // Fallback path: no URL plugin, read the DOM. `location.hash` is\n // percent-encoded; ids in the DOM are the raw string, so decode for the\n // match. Fall back to the raw slice if the hash contains a malformed\n // escape sequence (decodeURIComponent throws on those).\n const hash = globalThis.location.hash;\n\n if (anchorEnabled && hash.length > 1) {\n let id: string;\n\n try {\n id = decodeURIComponent(hash.slice(1));\n } catch {\n id = hash.slice(1);\n }\n\n // eslint-disable-next-line unicorn/prefer-query-selector -- ids may contain CSS-unsafe chars\n const element = document.getElementById(id);\n\n if (element) {\n element.scrollIntoView({ behavior });\n\n return;\n }\n }\n\n writePos(0);\n };\n\n let destroyed = false;\n let unserializableWarned = false;\n // Capture/effect seam guard (#782). previousRoute's position is captured\n // synchronously in `subscribe`, but the snap/restore effect runs a frame\n // later in rAF. Across that window the viewport still shows the route BEFORE\n // previousRoute, so a second navigation landing in the same frame would\n // capture that foreign position under previousRoute's key. `scrollSettled` is\n // false across the window — capture is skipped (previousRoute's own stored\n // value survives the transit). A real user scroll in this <16ms window is\n // physically impossible.\n let scrollSettled = true;\n\n // `keyOf` defers to `canonicalJson` which calls `JSON.stringify`. Two\n // realistic inputs blow up the serializer and would otherwise crash the\n // subscribe callback (taking scroll-restore offline for the whole session):\n // - `BigInt` params → `TypeError: Do not know how to serialize a BigInt`\n // - cyclic params (reactive proxies, DOM-ref back-pointers) → stack\n // overflow.\n // The defensive wrapper drops capture/restore for that specific navigation\n // and warns once per provider — the rest of the cache stays usable.\n const safeKeyOf = (state: State): string | null => {\n try {\n return keyOf(state);\n } catch {\n if (!unserializableWarned) {\n unserializableWarned = true;\n console.error(\n `[real-router] scroll-restore: route \"${state.name}\" has params that cannot be canonicalized (e.g. BigInt or cyclic structure). Scroll position will not be captured or restored for this route.`,\n );\n }\n\n return null;\n }\n };\n\n const unsubscribe = router.subscribe(({ route, previousRoute }) => {\n const nav = (route.context as { navigation?: NavigationContext })\n .navigation;\n\n // Browsers dispatch reload as the initial navigation after refresh, so\n // previousRoute is undefined and capture is naturally skipped. The\n // pre-refresh position was already persisted via pagehide. Capture is also\n // skipped while the scroll is unsettled — a second navigation in the same\n // frame, before the prior nav's rAF snap (see `scrollSettled`, #782).\n if (previousRoute && scrollSettled) {\n const prevKey = safeKeyOf(previousRoute);\n\n if (prevKey !== null) {\n putPos(prevKey, readPos());\n }\n }\n\n // This navigation's scroll effect is now pending: the viewport position no\n // longer belongs to `route` until the rAF below runs and settles it.\n scrollSettled = false;\n\n requestAnimationFrame(() => {\n if (destroyed) {\n return;\n }\n\n // Effect running — the position now belongs to `route`, so the next\n // capture is honest again.\n scrollSettled = true;\n\n if (mode === \"top\") {\n scrollToHashOrTop(route);\n\n return;\n }\n\n // Restore branches (reload, back/traverse) MUST be evaluated before the\n // replace-skip below. Since #657 lifted `replace` into TransitionMeta, a\n // history TRAVERSAL (back/forward) under navigation-plugin carries\n // `transition.replace === true` — a traversal reuses an existing history\n // entry, which is replace-shaped at the history level. If the replace-skip\n // ran first it would swallow every back/forward navigation and restore\n // would never fire (the Scenario 6 e2e regression). Genuine in-place\n // replaces (`router.navigate({ replace: true })`, navigateToNotFound) are\n // not traversals and fall through to the skip below.\n //\n // Both arms of each check are required: `transition.reload` only fires for\n // programmatic `router.navigate({reload:true})`. F5 under navigation-plugin\n // primes `nav.navigationType === \"reload\"` via #531 getActivationType but\n // leaves opts.reload undefined, so dropping the plugin arm would regress F5\n // scroll-restore. Browser-plugin's F5 is not covered (no priming, out of\n // scope).\n // `?.` on a required field: core commits a foreign State's ABSENT\n // `transition` rather than fabricating one (#1792 / #1976), and this runs\n // on whatever `subscribe` hands over. Absent falls through to the plugin\n // arm, which is the pre-#1976 answer for a state carrying no meta.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- the required field is genuinely absent on a foreign committed State\n if (route.transition?.reload || nav?.navigationType === \"reload\") {\n const key = safeKeyOf(route);\n\n restorePos(key === null ? 0 : (loadStore()[key] ?? 0));\n\n return;\n }\n\n if (nav?.direction === \"back\" || nav?.navigationType === \"traverse\") {\n const key = safeKeyOf(route);\n\n restorePos(key === null ? 0 : (loadStore()[key] ?? 0));\n\n return;\n }\n\n // Genuine in-place replace (not a traversal) — leave scroll untouched.\n // `?.` for the same reason as the reload arm above.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- the required field is genuinely absent on a foreign committed State\n if (route.transition?.replace || nav?.navigationType === \"replace\") {\n return;\n }\n\n scrollToHashOrTop(route);\n });\n });\n\n const onPageHide = (): void => {\n const current = router.getState();\n\n if (current) {\n const key = safeKeyOf(current);\n\n if (key !== null) {\n putPos(key, readPos());\n }\n }\n };\n\n globalThis.addEventListener(\"pagehide\", onPageHide);\n\n return {\n destroy: () => {\n // No `if (destroyed) return` guard: every teardown below is idempotent —\n // `unsubscribe()` is a `set.delete` in the core EventEmitter, DOM\n // `removeEventListener` is spec-idempotent, and the history assignment is\n // a plain re-set. There is no ref-count to protect (unlike\n // route-announcer's shared announcer element), so a double `destroy()` is\n // harmless. `destroyed = true` still gates any pending restore rAF / retry.\n destroyed = true;\n unsubscribe();\n globalThis.removeEventListener(\"pagehide\", onPageHide);\n\n try {\n history.scrollRestoration = prevScrollRestoration;\n } catch {\n // Ignore.\n }\n },\n };\n}\n\n/**\n * Internal cache-key builder for scroll-position storage.\n *\n * **Exported for testing only — not part of the public API** (intentionally\n * excluded from `index.ts` barrel). Adapter property tests import it via\n * the direct path to lock the `(name, canonicalJson(params))` key shape\n * as a regression guard (§8b H20 / audit-2026-05-16 #S3). A change to\n * key format would silently lose scroll positions across an upgrade —\n * the test set is the contract.\n *\n * ## Identity-based memoization (audit-2026-05-17 §8b #2)\n *\n * `State` objects emitted by core are frozen per-navigation: their\n * `name` / `params` are immutable for the lifetime of the snapshot, and\n * any change produces a new `State` reference. A `WeakMap<State, string>`\n * therefore safely caches the canonicalised key by identity — repeat\n * `keyOf(state)` calls on the same snapshot (typical on\n * back/forward/traverse where the same prior `State` is re-emitted)\n * skip the recursive `canonicalJson` pass entirely.\n *\n * The cache key is the `State` reference, so entries auto-release when\n * the snapshot is GC'd — no eviction needed.\n */\nconst KEY_CACHE = new WeakMap<State, string>();\n\nexport function keyOf(state: State): string {\n const cached = KEY_CACHE.get(state);\n\n if (cached !== undefined) {\n return cached;\n }\n\n // Key over BOTH channels — path params AND query (RFC-4 M2 / #1548). Merged\n // (not `params:search`) so a query-less route keeps its v1 key shape\n // (`name:{}`), and an unserializable value (BigInt / cyclic) in EITHER channel\n // still throws in `canonicalJson` → `safeKeyOf` drops+warns.\n const key = `${state.name}:${canonicalJson({ ...state.params, ...state.search })}`;\n\n KEY_CACHE.set(state, key);\n\n return key;\n}\n\n/**\n * Stable JSON serializer with sorted object keys.\n *\n * **Exported for testing only — not part of the public API** (intentionally\n * excluded from `index.ts` barrel). Adapter property tests import it via\n * the direct path to lock the key-order-insensitive property\n * (`canonicalJson({a:1,b:2}) === canonicalJson({b:2,a:1})`).\n *\n * ## Divergence from `@real-router/sources/canonicalJson` — by design\n *\n * Two independent implementations live in the monorepo:\n *\n * - **`shared/dom-utils/scroll-restore.canonicalJson`** (this file) — scroll\n * cache key builder. Uses `localeCompare` and a plain-object accumulator;\n * tolerates `__proto__`-keyed inputs only insofar as `JSON.stringify`'s\n * replacer happens to sort them; relies on `JSON.stringify`'s native cycle\n * detector. Designed to be cheap on the navigation hot path. The\n * surrounding [[safeKeyOf]] wrapper catches the two crash inputs (`BigInt`,\n * cyclic) and skips the offending capture/restore.\n *\n * - **`@real-router/sources/canonicalJson`** — sources cache key builder.\n * Uses byte-order compare (`< / >`) for locale-independence, a\n * `Object.create(null)` accumulator to prevent prototype pollution, and a\n * bespoke path-based cycle detector (the native one cannot see the cloned\n * graph). Throws eagerly on `Map`/`Set`/`RegExp`/cycles — the caller falls\n * back to a non-cached source.\n *\n * **They are intentionally NOT interchangeable.** Aligning them would either\n * regress scroll-restore performance (byte-order + recursive clone is heavier\n * per call) or weaken the sources cache (locale dependence breaks\n * deterministic cache keys across machines). No cross-package equivalence\n * test exists or should be added; the relationship is \"different invariants,\n * different costs, different consumers.\" Audit-2 / audit-2026-05-17 §2\n * documents the choice.\n */\nexport function canonicalJson(value: unknown): string {\n return JSON.stringify(value, canonicalReplacer);\n}\n\nfunction canonicalReplacer(_key: string, val: unknown): unknown {\n // audit-2026-05-17 §5 MEDIUM (Sprint A.3) — function/Symbol marker.\n // `JSON.stringify` silently drops function and symbol values from\n // object output. Two routes that differ ONLY in a function/Symbol\n // value would canonicalize to the same string → silent scroll-cache\n // key collision (positions clobber each other). Replacing the value\n // with a sentinel string breaks the collision while keeping the\n // canonical form deterministic. The sentinels are intentionally\n // ASCII-only and lexically distinct from valid JSON-stringified\n // values; consumers will see `\"<fn>\"` / `\"<sym>\"` if they ever\n // round-trip the cache key, signalling the substitution clearly.\n if (typeof val === \"function\") {\n return \"<fn>\";\n }\n if (typeof val === \"symbol\") {\n return \"<sym>\";\n }\n\n if (val !== null && typeof val === \"object\" && !Array.isArray(val)) {\n // Null-prototype accumulator: a plain `{}` would interpret\n // `sorted[\"__proto__\"] = x` as a prototype assignment (silently dropped\n // from JSON.stringify output AND a prototype-pollution vector). Mirrors\n // the same guard in `@real-router/sources/canonicalJson`. The two\n // implementations are still intentionally divergent (see the doc-block\n // on [[canonicalJson]] above), but prototype-safety is non-negotiable\n // on both. Lock-test: scrollRestoreKey.properties.ts Invariant 11.\n const sorted = Object.create(null) as Record<string, unknown>;\n // eslint-disable-next-line unicorn/no-array-sort -- ng-packagr uses pre-ES2023 lib; toSorted unavailable\n const keys = objectKeys(val).sort((left: string, right: string) =>\n left.localeCompare(right),\n );\n\n for (const key of keys) {\n sorted[key] = (val as Record<string, unknown>)[key];\n }\n\n return sorted;\n }\n\n return val;\n}\n","import { getTransitionSource } from \"@real-router/sources\";\n\nimport type { NavigationOptions, Router } from \"@real-router/core\";\n\n/**\n * Router-coordinated scroll spy (#575).\n *\n * On `IntersectionObserver` notifications the utility picks the topmost\n * visible anchor inside the configured scroll container and emits a forced\n * same-route transition with `{ hash, replace: true, force: true, hashChange:\n * true }` through `router.navigate(...)`. The URL plugin\n * (`@real-router/browser-plugin` or `@real-router/navigation-plugin`) updates\n * `state.context.url.hash` so sibling hash-aware `<Link hash>` re-highlights\n * via the standard `createActiveRouteSource` pipeline.\n *\n * **Anti-flicker gates** (RFC §5.2):\n * 1. `getTransitionSource(router).getSnapshot().isTransitioning` — skip emits\n * while a transition is in-flight (re-entrant lock).\n * 2. `coolingDown` — set on a user-driven hash transition (e.g. `<Link hash>`\n * click + smooth `scrollIntoView`). Cleared on `scrollend` or after a\n * 500ms safety timeout. Spy's own emits are excluded via the synchronous\n * `selfEmitting` flag — required so the spy doesn't rate-limit itself.\n *\n * **Self-healing** (RFC §7.3): if the initial URL contains a hash without a\n * matching `id` (e.g. `/page#nonexistent`), the first IO event emitted right\n * after observe()-ing picks the topmost real anchor and corrects the URL.\n *\n * **Hash-only transition pipeline cost** (RFC §5.3): for same-route same-\n * params hash-only navigations, `getTransitionPath` returns empty\n * `toDeactivate` / `toActivate` arrays, so `runGuards` is a no-op. The only\n * work is the URL plugin's `onTransitionSuccess` write and the\n * `getTransitionSource` flip — cheap.\n *\n * **Architecture**: decomposed into 4 private subsystem closure factories\n * (`createUrlPluginDetector`, `createCooldown`, `createDebouncer`,\n * `createObserverPair`). The main `createScrollSpy` wires them together\n * around the shared `silenced` / `destroyed` / `selfEmitting` flags and the\n * `flush()` emit logic. Each subsystem owns its state + cleanup; `destroy()`\n * delegates to each. See section banners below.\n *\n * @returns A `ScrollSpy` handle whose `destroy()` is idempotent.\n */\nexport interface ScrollSpyOptions {\n /**\n * CSS selector for anchor candidates. Empty string `\"\"` or `undefined`\n * disables the spy (returns a NOOP handle). Common values:\n * `\"[id]\"`, `\"[id]:is(h1,h2,h3)\"`, `\"section[id]\"`.\n */\n selector: string;\n\n /**\n * `IntersectionObserver` `rootMargin`. Default\n * `\"-20% 0px -60% 0px\"` — an anchor is considered \"active\" once it crosses\n * into the top 20 % of the viewport (or scroll container).\n */\n rootMargin?: string | undefined;\n\n /**\n * Lazy getter for the scrollable container. Consulted at creation and\n * re-consulted on every reconcile (DOM mutation), so a container that\n * MOUNTS or CHANGES after the spy is created is honoured: the\n * `IntersectionObserver` root and `MutationObserver` target — both immutable\n * once constructed — are rebuilt to match (#780). `null` (or a missing\n * getter) falls back to the window viewport (`root: null` on the\n * `IntersectionObserver`).\n */\n scrollContainer?: (() => HTMLElement | null) | undefined;\n}\n\nexport interface ScrollSpy {\n /** Tear down observer + listeners. Idempotent. */\n destroy: () => void;\n}\n\nconst NOOP_INSTANCE: ScrollSpy = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\n// Hardcoded internals (RFC §5.1 — promote only with evidence).\nconst RAF_DEBOUNCE_MS = 150;\nconst MUTATION_DEBOUNCE_MS = 250;\nconst COOLDOWN_TIMEOUT_MS = 500;\nconst DEFAULT_ROOT_MARGIN = \"-20% 0px -60% 0px\";\n\n// Local extension type — browser-plugin / navigation-plugin augment\n// `NavigationOptions` with `hash` and `hashChange`, but `shared/dom-utils`\n// is plugin-agnostic and cannot rely on the augmentation. Mirrors the\n// `HashAwareNavigationOptions` pattern in `link-utils.ts`.\ntype HashAwareNavigationOptions = NavigationOptions & {\n hash?: string;\n hashChange?: boolean;\n};\n\n// The `url` namespace contract is owned by browser-env: both URL plugins\n// (browser-plugin, navigation-plugin) write `{ hash: string; hashChanged }` on\n// every transition. This is a local mirror (keeps dom-utils independent of\n// browser-env) and must match that canonical shape — `hash` is always present,\n// never a partial slice.\ninterface UrlContextSlice {\n hash: string;\n hashChanged: boolean;\n}\n\nconst getUrlContext = (state: {\n context?: unknown;\n}): UrlContextSlice | undefined =>\n (state.context as { url?: UrlContextSlice } | undefined)?.url;\n\n// =============================================================================\n// Picker — pure, no state. RFC §5.2 selection rule.\n// =============================================================================\n\n// Pick the anchor closest to the active zone top in viewport coordinates.\n// `entry.rootBounds.top` already reflects `rootMargin` (per W3C IO spec\n// §3.3) — for `rootMargin: \"-20% 0px -60% 0px\"` it returns 20% of root\n// height, for `\"-50% 0px -50% 0px\"` it returns the center, etc. Distance\n// = boundingClientRect.top − zoneTop in viewport pixels: positive = anchor\n// below zone top (just entered), negative = anchor above zone top (body\n// crossing zone from above). We prefer smallest non-negative; fall back to\n// least-negative when no entry has crossed yet.\n// Falls back to zoneTop = 0 when rootBounds is null (cross-origin roots,\n// unit tests). Single pass — handles `Iterable` so flushes can pass\n// `Map.values()` directly without realising the array.\nconst pickTopmost = (\n entries: Iterable<IntersectionObserverEntry>,\n): IntersectionObserverEntry | null => {\n let bestPositive: IntersectionObserverEntry | null = null;\n let bestPositiveDist = Number.POSITIVE_INFINITY;\n let bestNegative: IntersectionObserverEntry | null = null;\n let bestNegativeDist = Number.NEGATIVE_INFINITY;\n\n for (const entry of entries) {\n if (!entry.isIntersecting) {\n continue;\n }\n\n const zoneTop = entry.rootBounds?.top ?? 0;\n const distance = entry.boundingClientRect.top - zoneTop;\n\n if (distance >= 0) {\n if (distance < bestPositiveDist) {\n bestPositive = entry;\n bestPositiveDist = distance;\n }\n } else if (distance > bestNegativeDist) {\n bestNegative = entry;\n bestNegativeDist = distance;\n }\n }\n\n return bestPositive ?? bestNegative;\n};\n\n// =============================================================================\n// Subsystem: URL plugin detector (RFC §5.5)\n// Calls `onMissing` if `state.context` is published but `url` key is missing\n// (i.e. no URL plugin installed). Either synchronous on start, or deferred\n// via a one-shot `router.subscribe` if the router has not started yet.\n// `silenced` flag itself lives in main scope — detector signals via callback\n// (per Oracle Q1 — `silenced` has multiple unrelated triggers; main scope\n// owns the kill switch).\n// =============================================================================\n\ninterface UrlPluginDetector {\n destroy: () => void;\n}\n\nconst createUrlPluginDetector = (\n router: Router,\n onMissing: () => void,\n): UrlPluginDetector => {\n let detectionUnsub: (() => void) | null = null;\n\n const verify = (state: { context?: unknown }): void => {\n const context = state.context as\n (Record<string, unknown> & { url?: unknown }) | undefined;\n\n if (context && context.url === undefined) {\n console.warn(\n \"[real-router] scroll-spy: state.context.url is not claimed. \" +\n \"Spy requires browser-plugin or navigation-plugin. Disabling.\",\n );\n onMissing();\n }\n };\n\n const peekState = router.getState();\n\n if (peekState) {\n verify(peekState);\n } else {\n // Re-entry guard: `router.subscribe` MAY invoke the callback synchronously\n // from inside `.subscribe(...)` before the function returns. In that case\n // `detectionUnsub` is still `null` when the callback fires. Without this\n // boolean, a hypothetical multi-fire would double-warn.\n let detectionConsumed = false;\n\n detectionUnsub = router.subscribe(({ route }) => {\n /* v8 ignore next 3 -- @preserve: the multi-fire is hypothetical (see above) — the real router never invokes a subscriber synchronously twice before unsub; defensive guard, not testable without a contract-violating fake */\n if (detectionConsumed) {\n return;\n }\n\n detectionConsumed = true;\n verify(route);\n\n detectionUnsub?.();\n detectionUnsub = null;\n });\n }\n\n return {\n destroy(): void {\n detectionUnsub?.();\n detectionUnsub = null;\n },\n };\n};\n\n// =============================================================================\n// Subsystem: Cooldown gate (RFC §5.2 — anti-flicker for smooth scrollIntoView)\n// Set on user-driven `<Link hash>` click → smooth scroll. Cleared on\n// `scrollend` (Baseline 2026) or 500ms safety timeout (older Safari).\n// =============================================================================\n\ninterface Cooldown {\n readonly active: boolean;\n start: () => void;\n destroy: () => void;\n}\n\nconst createCooldown = (getContainer: () => HTMLElement | null): Cooldown => {\n let active = false;\n let timeout: ReturnType<typeof setTimeout> | null = null;\n let listenerContainer: HTMLElement | null = null;\n let listener: (() => void) | null = null;\n\n const clear = (): void => {\n if (timeout !== null) {\n clearTimeout(timeout);\n timeout = null;\n }\n\n if (listener) {\n const target: EventTarget = listenerContainer ?? globalThis;\n\n target.removeEventListener(\"scrollend\", listener);\n }\n\n listener = null;\n listenerContainer = null;\n active = false;\n };\n\n return {\n get active(): boolean {\n return active;\n },\n start(): void {\n // Reset rather than stack timers if cooldown is already active.\n clear();\n\n active = true;\n\n const lift = (): void => {\n clear();\n };\n\n listener = lift;\n listenerContainer = getContainer();\n\n const target: EventTarget = listenerContainer ?? globalThis;\n\n target.addEventListener(\"scrollend\", lift, { once: true });\n\n timeout = setTimeout(lift, COOLDOWN_TIMEOUT_MS);\n },\n destroy(): void {\n clear();\n },\n };\n};\n\n// =============================================================================\n// Subsystem: rAF + trailing debounce (RFC §5.1)\n// Coalesces a burst of IO events into ≤ 1 callback per debounce window.\n// rAF reduces N setTimeout creations to 1 per animation frame; the trailing\n// 150ms setTimeout waits for the IO stream to quiesce.\n// =============================================================================\n\ninterface Debouncer {\n schedule: () => void;\n destroy: () => void;\n}\n\nconst createDebouncer = (\n callback: () => void,\n trailingMs: number,\n): Debouncer => {\n let raf: number | null = null;\n let timeout: ReturnType<typeof setTimeout> | null = null;\n\n return {\n schedule(): void {\n if (raf !== null) {\n return;\n }\n\n raf = requestAnimationFrame(() => {\n raf = null;\n\n if (timeout !== null) {\n clearTimeout(timeout);\n }\n\n timeout = setTimeout(() => {\n timeout = null;\n callback();\n }, trailingMs);\n });\n },\n destroy(): void {\n if (raf !== null) {\n cancelAnimationFrame(raf);\n raf = null;\n }\n\n if (timeout !== null) {\n clearTimeout(timeout);\n timeout = null;\n }\n },\n };\n};\n\n// =============================================================================\n// Subsystem: Observer pair (IntersectionObserver + MutationObserver)\n// IO + MO genuinely form one subsystem — both write/read `observed` set and\n// `pending` map, and reconcile flow couples them. Per Oracle Q10, splitting\n// would force cross-subsystem references that re-introduce the wiring\n// problem we're trying to solve.\n//\n// Exposes `pending` directly (per Oracle Q4: hiding behind `consume()` adds\n// boilerplate without isolating the shared mutable state — observers write\n// from IO callbacks while main scope reads in `flush()`).\n// =============================================================================\n\ninterface ObserverPair {\n readonly pending: Map<Element, IntersectionObserverEntry>;\n /** True when a resolved container has since detached from the DOM (#1216). */\n isContainerDetached: () => boolean;\n /** Re-resolve the container + re-observe matches (rebuilds the pair on change). */\n reconcile: () => void;\n destroy: () => void;\n}\n\nconst createObserverPair = (\n selector: string,\n rootMargin: string,\n getContainer: () => HTMLElement | null,\n onIntersection: () => void,\n onInvalidSelector: () => void,\n isStopped: () => boolean,\n): ObserverPair => {\n const observed = new Set<Element>();\n // Latest IO entry per target — accumulated across batches. IO delivers\n // entries only for targets whose intersection state CHANGED (W3C IO\n // §3.2.1), so a fast scroll that lands two callbacks inside the same\n // debounce window must merge by target, not overwrite. Entries are\n // dropped from the map when their target leaves the DOM (see `reconcile`)\n // and on `destroy()`.\n const pending = new Map<Element, IntersectionObserverEntry>();\n\n let duplicateIdWarned = false;\n let mutationTimer: ReturnType<typeof setTimeout> | null = null;\n\n const handleIntersection: IntersectionObserverCallback = (entries) => {\n // Defensive: IO callback may fire AFTER `destroy()` if a queued event\n // was already scheduled by the browser before `disconnect()`. Cheap\n // belt-and-suspenders.\n if (isStopped()) {\n return;\n }\n\n for (const entry of entries) {\n pending.set(entry.target, entry);\n }\n\n onIntersection();\n };\n\n // Build (and rebuild) the IntersectionObserver for a given root. A root is\n // immutable once its IO is constructed, so `reconcile` recreates the IO via\n // this same factory when the resolved container changes (#780) — one\n // definition, two call sites.\n const makeIo = (container: HTMLElement | null): IntersectionObserver =>\n new IntersectionObserver(handleIntersection, {\n root: container,\n rootMargin,\n threshold: 0,\n });\n\n // Container the IntersectionObserver root + MutationObserver target are\n // built with. Both are immutable once the observer is constructed (W3C), so\n // a `scrollContainer` that resolves to a different element after creation —\n // most importantly one that MOUNTS after the spy starts (Angular wires the\n // spy at bootstrap, before any component renders; a docs route's container\n // mounts on navigation) — is only honoured by rebuilding the pair in\n // `reconcile`. Tracked here so `reconcile` can compare on every run (#780).\n let observerContainer = getContainer();\n\n let io = makeIo(observerContainer);\n\n const observeMatches = (): void => {\n const scope = getContainer() ?? document;\n let candidates: NodeListOf<Element>;\n\n try {\n candidates = scope.querySelectorAll(selector);\n } catch {\n onInvalidSelector();\n\n return;\n }\n\n const seenIds = new Set<string>();\n\n for (const element of candidates) {\n // Detect duplicate ids once (RFC §7.7). The DOM permits duplicate ids\n // even though it is a markup bug; the spy keeps working but picks the\n // first one deterministically via the topmost-visible rule.\n const id = (element as HTMLElement).id;\n\n if (id && !duplicateIdWarned) {\n if (seenIds.has(id)) {\n duplicateIdWarned = true;\n\n console.warn(\n `[real-router] scroll-spy: duplicate id \"${id}\" observed. ` +\n \"Selection picks the topmost visible match deterministically.\",\n );\n }\n\n seenIds.add(id);\n }\n\n if (observed.has(element)) {\n continue;\n }\n\n io.observe(element);\n observed.add(element);\n }\n };\n\n // MutationObserver init — reused when the observer is re-pointed at a new\n // container in `reconcile`. `childList: true, subtree: true` catches\n // structural changes; `attributes: true, attributeFilter: [\"id\"]` catches\n // anchor id renames (typical for client-rendered docs). The MO targets the\n // scroll container (or document.body for the window viewport).\n const MUTATION_OBSERVE_INIT: MutationObserverInit = {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: [\"id\"],\n };\n\n // Null-then-assigned — the same forward-reference idiom as `flush` in the\n // main scope. `reconcile` re-points it on a container change, so it must be\n // in scope above its assignment; it is non-null by the time any async\n // mutation callback (or `reconcile`) runs.\n let mo: MutationObserver | null = null;\n\n const reconcile = (): void => {\n // Drop observed elements that left the DOM. Avoids observer holding\n // strong refs to detached nodes. Also drop their accumulated entry so\n // stale \"was intersecting\" state for a removed node cannot be picked\n // by `pickTopmost` after the node is gone.\n for (const element of observed) {\n if (element.isConnected) {\n continue;\n }\n\n io.unobserve(element);\n observed.delete(element);\n pending.delete(element);\n }\n\n // Honour a container that mounted (or changed) after construction (#780).\n // The IntersectionObserver root and MutationObserver target cannot be\n // mutated in place, so rebuild the pair under the new container. Clearing\n // `observed` + `pending` makes the rebuild equivalent to constructing the\n // spy with this container from the start: `observeMatches` below\n // re-populates the tracked set from the new container's scope, and the\n // stale merged snapshot (computed against the old root's geometry) is\n // dropped — one empty debounce window, acceptable for a rare event.\n const nextContainer = getContainer();\n\n if (nextContainer !== observerContainer) {\n observerContainer = nextContainer;\n\n io.disconnect();\n io = makeIo(nextContainer);\n observed.clear();\n pending.clear();\n\n mo?.disconnect();\n mo?.observe(nextContainer ?? document.body, MUTATION_OBSERVE_INIT);\n }\n\n observeMatches();\n };\n\n observeMatches();\n\n mo = new MutationObserver(() => {\n if (mutationTimer !== null) {\n clearTimeout(mutationTimer);\n }\n\n mutationTimer = setTimeout(() => {\n mutationTimer = null;\n reconcile();\n }, MUTATION_DEBOUNCE_MS);\n });\n\n mo.observe(observerContainer ?? document.body, MUTATION_OBSERVE_INIT);\n\n return {\n pending,\n // #1216: the MutationObserver is pointed at the container's OWN subtree, so\n // the container's removal (a mutation of its PARENT) is invisible — reconcile\n // never fires on it and a remounted container is never re-observed. Expose a\n // detach check + reconcile so the router.subscribe callback can re-resolve on\n // navigation (exactly when route-tied containers mount/die). When\n // `observerContainer` is null the MO already watches `document.body`, which\n // sees container mounts directly — so only a resolved-then-detached container\n // needs this nav-time nudge.\n isContainerDetached: (): boolean =>\n observerContainer !== null && !observerContainer.isConnected,\n reconcile,\n destroy(): void {\n io.disconnect();\n mo.disconnect();\n\n if (mutationTimer !== null) {\n clearTimeout(mutationTimer);\n mutationTimer = null;\n }\n\n observed.clear();\n pending.clear();\n },\n };\n};\n\n// =============================================================================\n// Main: compositional wiring\n// =============================================================================\n\nexport function createScrollSpy(\n router: Router,\n options: ScrollSpyOptions,\n): ScrollSpy {\n // SSR guard (RFC §7.5) — return early without warnings.\n if (typeof document === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n // Feature-detect IntersectionObserver — no polyfill ships (RFC §4).\n if (typeof IntersectionObserver === \"undefined\") {\n return NOOP_INSTANCE;\n }\n\n const { selector } = options;\n\n // Empty selector → disabled. Documented opt-out for conditional enabling\n // (RFC §5.4 `scrollSpy={{ selector: enable ? \"[id]\" : \"\" }}`).\n if (!selector) {\n return NOOP_INSTANCE;\n }\n\n const rootMargin = options.rootMargin ?? DEFAULT_ROOT_MARGIN;\n const getContainer = options.scrollContainer;\n const resolveContainer = (): HTMLElement | null => getContainer?.() ?? null;\n\n // Shared lifecycle flags (Oracle Q1 — `silenced` has multiple unrelated\n // triggers; Oracle Q3 — `selfEmitting` synchronously bracketed around\n // `router.navigate()` cannot cleanly extract). Kept in main scope.\n let destroyed = false;\n let silenced = false;\n let selfEmitting = false;\n\n const isStopped = (): boolean => silenced || destroyed;\n\n // Symmetric late-binding (Oracle Q2): declare `flush` as nullable, wire\n // debouncer + observers, then assign the real implementation. Reads as\n // intentional wiring rather than accidental closure capture ordering.\n // The `flush?.()` call below safely no-ops if a callback somehow fires\n // before assignment (impossible in practice — IO/debounce are async).\n let flush: (() => void) | null = null;\n\n const transitionSource = getTransitionSource(router);\n\n const detector = createUrlPluginDetector(router, () => {\n silenced = true;\n });\n\n const cooldown = createCooldown(resolveContainer);\n\n const debouncer = createDebouncer(() => {\n flush?.();\n }, RAF_DEBOUNCE_MS);\n\n const observers = createObserverPair(\n selector,\n rootMargin,\n resolveContainer,\n () => {\n debouncer.schedule();\n },\n () => {\n if (silenced) {\n return;\n }\n\n silenced = true;\n\n console.warn(\n `[real-router] scroll-spy: invalid selector \"${selector}\". Disabling.`,\n );\n },\n isStopped,\n );\n\n flush = (): void => {\n if (destroyed || silenced) {\n observers.pending.clear();\n\n return;\n }\n\n // Gate-skipped flushes keep `pendingEntries` populated — the merged\n // state is still the best-known snapshot, and the next non-gated flush\n // consumes it. Clearing under a gate would re-introduce the overwrite\n // bug for any anchor whose intersection state did not change during\n // the gate window.\n if (transitionSource.getSnapshot().isTransitioning) {\n return;\n }\n\n if (cooldown.active) {\n return;\n }\n\n // No `if (pending.size === 0) return` fast-path: `pending` is never empty\n // here via any real path (a real IntersectionObserver always delivers ≥1\n // entry, so `handleIntersection` populates `pending` before scheduling; the\n // mutation reconcile that could drop entries runs at MUTATION_DEBOUNCE_MS\n // 250 > RAF_DEBOUNCE_MS 150, i.e. always AFTER the flush). And an empty map\n // is already handled identically below — `pickTopmost(∅)` is `null` → the\n // `if (!picked) return` guard — so the fast-path was both unreachable and\n // redundant.\n\n // Successful flush consumes the merged snapshot. We clear so that the\n // next debounce window starts fresh; an anchor that is still\n // intersecting will only stay observable if IO emits another event for\n // it (which it does whenever the anchor's intersection state actually\n // changes). Skipping the clear here would leak state from one user-\n // perceived \"scroll stop\" into the next.\n const picked = pickTopmost(observers.pending.values());\n\n observers.pending.clear();\n\n if (!picked) {\n // No anchor visible / above zone — preserve last hash (RFC §10 #5).\n return;\n }\n\n const newHash = (picked.target as HTMLElement).id;\n\n if (!newHash) {\n return;\n }\n\n const state = router.getState();\n\n if (!state) {\n return;\n }\n\n // `getUrlContext` is guaranteed present here (the URL-plugin detector\n // silences the spy otherwise), so `?.` only satisfies the `| undefined`\n // slice type. `newHash` is a non-empty id (guarded above), so it can never\n // equal an absent hash — no `?? \"\"` normalization needed for the compare.\n const currentHash = getUrlContext(state)?.hash;\n\n if (newHash === currentHash) {\n return;\n }\n\n // Emit the same-route same-params hash-only transition. URL plugin\n // writes `state.context.url.hash = newHash` + `hashChanged = true` in\n // its `onTransitionSuccess` claim.\n const opts: HashAwareNavigationOptions = {\n hash: newHash,\n replace: true,\n force: true,\n hashChange: true,\n };\n\n // Self-emit guard (RFC §5.2): set synchronously around our own\n // `router.navigate()` so the `router.subscribe` callback skips the\n // cooldown setup for spy-emitted transitions — otherwise spy would\n // rate-limit itself to ≤ 2 emits/s, contradicting the ≤ 10/s benchmark\n // target. Test coupling (Q8): preserve exact `.catch(noop).finally(reset)`\n // chain — migrating to `try/finally` over `await router.navigate(...)`\n // changes microtask schedule and breaks \"spy continues after rejection\".\n selfEmitting = true;\n router\n // Both channels of the CURRENT state, not just the path bag (RFC-4 M2 /\n // #1548): this is a same-route re-navigation to move the hash, so\n // whatever query the user is already looking at has to survive it.\n // Passing `undefined` in slot 3 dropped it — scrolling a page at\n // `/docs?tab=api` silently rewrote the URL to `/docs`. Options stay at\n // slot 4.\n .navigate(state.name, state.params, state.search, opts)\n .catch(() => {\n // Fire-and-forget — suppress expected rejections (concurrent\n // navigate, router stopped, etc.) consistent with `<Link>` adapter\n // patterns.\n })\n .finally(() => {\n selfEmitting = false;\n });\n };\n\n // Cooldown setup on user-driven hash transitions. Spy's own emits are\n // distinguished via the synchronous `selfEmitting` flag (see `flush`).\n const unsubscribeRouter = router.subscribe(({ route }) => {\n if (selfEmitting) {\n return;\n }\n\n // #1216: a route-tied scroll container may have unmounted since the last\n // navigation. The container-scoped MutationObserver can't observe its own\n // removal (a mutation of its parent), so re-resolve + re-observe here —\n // navigation is exactly when such containers mount / die.\n if (observers.isContainerDetached()) {\n observers.reconcile();\n }\n\n if (getUrlContext(route)?.hashChanged) {\n cooldown.start();\n }\n });\n\n return {\n destroy(): void {\n // No `if (destroyed) return` idempotency guard: every subsystem teardown\n // below is itself idempotent (null-guarded timers, `set.delete` on the\n // router unsubscribe, spec-idempotent `IntersectionObserver.disconnect`),\n // and `destroy()` is not a hot path — so a redundant guard would only add\n // an unreachable branch. `destroyed = true` is still set to gate any\n // late-arriving IO/router callback via `isStopped()`.\n destroyed = true;\n\n // Unsubscribe FIRST to prevent late-arriving router transition\n // callback from calling `cooldown.start()` on a half-destroyed\n // instance. Without this ordering, a transition with `hashChanged:\n // true` firing between subsystem teardown and `unsubscribeRouter()`\n // would re-install a 500ms timer that survives `destroy()`. Verified\n // via Oracle review (Q5/Q7).\n unsubscribeRouter();\n\n observers.destroy();\n debouncer.destroy();\n cooldown.destroy();\n detector.destroy();\n },\n };\n}\n","import type { Router } from \"@real-router/core\";\n\nexport interface ViewTransitions {\n destroy: () => void;\n}\n\nconst NOOP_INSTANCE: ViewTransitions = Object.freeze({\n destroy: () => {\n /* no-op */\n },\n});\n\nexport function createViewTransitions(router: Router): ViewTransitions {\n if (\n typeof document === \"undefined\" ||\n typeof document.startViewTransition !== \"function\"\n ) {\n return NOOP_INSTANCE;\n }\n\n let closeVT: (() => void) | null = null;\n let currentVT: { skipTransition?: () => void } | null = null;\n // Tracks whether TRANSITION_SUCCESS fired for the current leave. Used to\n // distinguish \"benign cleanup abort\" (router's async path aborts its own\n // controller in a finally block after successful navigation) from \"real\n // cancellation\" (concurrent navigate, guard rejection, dispose).\n let successFired = false;\n\n const resolveAndClear = (): void => {\n closeVT?.();\n closeVT = null;\n };\n\n const offLeave = router.subscribeLeave(({ signal }) => {\n // Reentrant abort: signal already aborted when we're called. Open no VT\n // — router will fall through to TRANSITION_CANCELLED via isCurrentNav()\n // after leave resolves. addEventListener(\"abort\", ...) does not re-fire\n // for past events, so skipping startViewTransition is the safe path.\n if (signal.aborted) {\n return;\n }\n\n successFired = false;\n resolveAndClear();\n\n // Return a Promise so the router awaits until the browser invokes\n // updateCallback. This ensures old DOM snapshot is captured BEFORE the\n // router commits the new state — giving correct exit→state→entry\n // ordering (vs fire-and-forget, where URL changes before VT captures).\n return new Promise<void>((resolveLeave) => {\n // Capture the resolver synchronously BEFORE startViewTransition() is\n // called. The browser invokes updateCallback in a later task, but\n // router.subscribe (TRANSITION_SUCCESS) can fire before that. If we\n // captured `resolve` inside the callback, subscribe would see closeVT\n // still null and skip resolving — the deferred would hang for 4s\n // until the VT API aborts with TimeoutError.\n // eslint-disable-next-line unicorn/prefer-promise-with-resolvers -- frozen shared primitive; resolver captured synchronously before startViewTransition() by design (see comment above)\n const deferred = new Promise<void>((resolve) => {\n closeVT = resolve;\n });\n\n signal.addEventListener(\n \"abort\",\n () => {\n if (successFired) {\n // Router's async path (#finishAsyncNavigation) aborts its own\n // controller in a finally block AFTER completeTransition (and\n // thus AFTER subscribe fired). This is cleanup, not\n // cancellation — VT is progressing normally, do nothing.\n return;\n }\n\n // Real cancellation (concurrent navigate, dispose). Resolve the\n // deferred so updateCallback can complete, skip the VT so no\n // stale animation leaks, and unblock the router if the abort\n // fires before updateCallback was invoked.\n resolveAndClear();\n currentVT?.skipTransition?.();\n resolveLeave();\n },\n { once: true },\n );\n\n try {\n currentVT = document.startViewTransition(() => {\n // Resolving here unblocks the router at the moment the browser\n // enters updateCallback — by spec, old DOM snapshot is captured\n // before this callback runs. Router now proceeds through\n // activation guards and setState; the VT animation waits on\n // `deferred`, which is resolved from router.subscribe after a\n // task-queue tick (see NOTE on setTimeout below).\n resolveLeave();\n\n return deferred;\n });\n } catch {\n // Defensive: spec says startViewTransition doesn't throw under\n // normal conditions, but Chromium has had edge cases (detached\n // document, extension interference). Clean up and unblock router.\n resolveAndClear();\n resolveLeave();\n }\n });\n });\n\n const offSuccess = router.subscribe(() => {\n const resolver = closeVT;\n\n successFired = true;\n closeVT = null;\n\n if (resolver === null) {\n currentVT = null;\n } else {\n // The VT this resolver belongs to. If the next navigation opens a new VT\n // in the task-queue window before this setTimeout runs, the stale\n // resolver must NOT null the new `currentVT` — otherwise a later\n // cancellation reads `null` and skips nothing, leaking a stale animation\n // (#781). Same identity-guard technique the navigation-plugin uses to\n // heal its seams.\n const scheduledVT = currentVT;\n\n // CRITICAL: CANNOT use requestAnimationFrame here. When the router\n // takes the async path (leave returned a Promise), subscribe fires\n // AFTER the browser has already transitioned VT into the\n // \"update-callback-called\" phase. In that phase Chromium sets\n // rendering suppression to true, which ALSO blocks rAF callbacks.\n // rAF would never fire → deferred never resolves → browser aborts\n // vt.ready with TimeoutError after 4s (observed in Chromium).\n //\n // setTimeout runs on the task queue independent of the rendering\n // pipeline, so it fires regardless of suppression. React's scheduler\n // uses MessageChannel tasks, which are queued before our setTimeout,\n // so the new DOM is committed by the time our callback runs.\n setTimeout(() => {\n resolver();\n\n if (currentVT === scheduledVT) {\n currentVT = null;\n }\n }, 0);\n }\n });\n\n return {\n destroy: () => {\n offLeave();\n offSuccess();\n currentVT?.skipTransition?.();\n currentVT = null;\n resolveAndClear();\n },\n };\n}\n","import type {\n NavigationOptions,\n NavigationTarget,\n Params,\n Router,\n SearchParams,\n State,\n} from \"@real-router/core\";\n\n/**\n * Intrinsics captured at module load (#1971).\n *\n * ⚑ These DECIDE — they answer \"what is on this object\" for a value this module\n * did not build. Read off the live global they can be re-pointed after boot, and\n * `shared/` is the half where that fails OPEN: measured in `browser-env`, a\n * re-pointed `getPrototypeOf` admits a `Date` into `state.params` and a\n * re-pointed `keys` skips option validation entirely.\n *\n * ⚠ Capture narrows the window from \"any time after boot\" to \"before this module\n * loads\". It does not close it (#1798).\n */\nconst objectKeys = Object.keys;\n\n/**\n * Resolved navigation channels for a `<Link>` — the single `{ name, params,\n * search }` shape every adapter feeds into `buildHref` / `navigateWithHash` /\n * the active-route source, regardless of which prop form the consumer used.\n */\nexport interface ResolvedLinkTarget {\n name: string;\n params: Params | undefined;\n search: SearchParams | undefined;\n}\n\n/**\n * Collapses a `<Link>`'s two prop forms (RFC-4 M2 B2, #1548) into one channel\n * triple:\n *\n * - **Descriptor** — `to={{ name, params?, search? }}` (a `NavigationTarget`).\n * - **Channel props** — `routeName` + `routeParams?` + `routeSearch?`.\n *\n * The forms are mutually exclusive: the TS union on each adapter's `LinkProps`\n * rejects mixing them at compile time, and this helper is the runtime backstop —\n * when `to` is present it **wins**, and a `dev`-visible `console.warn` fires if\n * channel props were also supplied (a JS consumer, an object spread, or an\n * adapter without a strict union can still slip both through). `routeOptions` /\n * `hash` are separate props under BOTH forms (hash is not part of\n * `NavigationTarget` — #532), so they are resolved by the caller, not here.\n */\nexport function resolveLinkTarget(\n to: NavigationTarget | undefined,\n routeName: string,\n routeParams: Params | undefined,\n routeSearch: SearchParams | undefined,\n): ResolvedLinkTarget {\n if (to !== undefined) {\n if (\n routeName !== \"\" ||\n routeParams !== undefined ||\n routeSearch !== undefined\n ) {\n console.warn(\n \"[real-router] <Link> received both `to` and channel props \" +\n \"(routeName / routeParams / routeSearch). `to` wins; the channel \" +\n \"props are ignored. Use one form or the other.\",\n );\n }\n\n return { name: to.name, params: to.params, search: to.search };\n }\n\n return { name: routeName, params: routeParams, search: routeSearch };\n}\n\nexport function shouldNavigate(evt: MouseEvent): boolean {\n return (\n evt.button === 0 &&\n !evt.metaKey &&\n !evt.altKey &&\n !evt.ctrlKey &&\n !evt.shiftKey\n );\n}\n\n/**\n * RFC 3986 fragment encoding: preserve sub-delims (`&`, `=`, `?`, `:`),\n * encode space, `%`, control chars, non-ASCII via encodeURI; defensively\n * escape `#` (encodeURI does not). Kept BYTE-FOR-BYTE identical to\n * `encodeHashFragment` in `shared/browser-env/url-context.ts` — duplicated\n * because the shared/dom-utils symlink graph does not reach shared/browser-env;\n * a sync test (`link-utils` functional suite) asserts the two stay identical.\n *\n * **STRICTLY-DECODED contract (#1211 / D1=A).** The `<Link hash>` value is a\n * DECODED fragment (no leading `#`) and is encoded verbatim. This OVERTURNS\n * audit-2026-05-17 §5 E.1 — the earlier percent-escape probe (decode + re-encode\n * for copy-from-`location.hash` tolerance) is REMOVED, so both the adapter and\n * the plugin layer obey one contract: `<Link hash=\"a%20b\">` renders `#a%2520b`\n * (the literal fragment `a%20b`) under every runtime. Consumers who want the\n * fragment `a b` pass `hash=\"a b\"`; passing raw `location.hash` (percent-encoded)\n * is no longer supported — it was the source of the plugin↔adapter divergence.\n */\nfunction encodeFragmentInline(decoded: string): string {\n return encodeURI(decoded).replaceAll(\"#\", \"%23\");\n}\n\ntype BuildUrlFn = (\n name: string,\n params: Params,\n search?: SearchParams,\n options?: { hash?: string },\n) => string | undefined;\n\n/**\n * Builds an href for a `<Link>` element.\n *\n * - Prefers the URL plugin's `buildUrl` (browser-plugin, navigation-plugin,\n * hash-plugin) when present.\n * - Falls back to `router.buildPath` for runtimes without a URL plugin\n * (memory-plugin, console UIs, NativeScript). In that fallback the hash\n * is appended manually so the rendered href is still correct.\n * - The optional 4th argument is the decoded hash fragment (no leading \"#\";\n * `<Link hash=\"#section\">` is accepted defensively — leading \"#\" stripped),\n * passed positionally to mirror `navigateWithHash(router, name, params, hash)`\n * (#1442). Previous 3-arg call sites continue to work unchanged.\n */\nexport function buildHref(\n router: Router,\n routeName: string,\n routeParams: Params,\n routeSearch?: SearchParams,\n hash?: string,\n): string | undefined {\n try {\n let normHash: string | undefined;\n\n if (hash !== undefined) {\n normHash = hash.startsWith(\"#\") ? hash.slice(1) : hash;\n }\n\n const buildUrl = router.buildUrl as BuildUrlFn | undefined;\n\n if (buildUrl) {\n const url = buildUrl(\n routeName,\n routeParams,\n // Query channel at position 3 (RFC-4 M2 / #1548) — from the `routeSearch`\n // prop; hash options at position 4. `undefined` when the link has no\n // `routeSearch` (its query, if any, still rides in routeParams).\n routeSearch,\n normHash === undefined ? undefined : { hash: normHash },\n );\n\n // Accept only non-empty strings. The BuildUrlFn type contract is\n // `string | undefined`, but defensive against:\n // - `\"\"` (empty string) → would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - `null` (type-contract violation) → would render `<a href={null}>`,\n // stringified to `\"null\"` in some renderers.\n // Either case falls through to the `router.buildPath` fallback below.\n if (typeof url === \"string\" && url.length > 0) {\n return url;\n }\n }\n\n const path = router.buildPath(routeName, routeParams, routeSearch);\n\n // Symmetric to the buildUrl guard above (#S1 audit, Invariant 12).\n // `router.buildPath` is typed `string`, but defends against:\n // - `\"\"` (empty string) — would render `<a href=\"\">`, which resolves\n // to the current page URL → silent self-navigation on click.\n // - non-string type-contract violations from custom path-matchers.\n // Both yield `undefined` (renderer drops the attribute) with a warning.\n if (typeof path !== \"string\" || path.length === 0) {\n console.error(\n `[real-router] Route \"${routeName}\" yielded an empty path. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n\n return normHash ? `${path}#${encodeFragmentInline(normHash)}` : path;\n } catch {\n console.error(\n `[real-router] Route \"${routeName}\" is not defined. The element will render without an href attribute.`,\n );\n\n return undefined;\n }\n}\n\n/**\n * `<Link>` click-handler navigation helper (#532).\n *\n * Wraps `router.navigate(name, params, opts)` with same-route different-hash\n * detection: when the consumer clicks a hash-bearing Link that targets the\n * current route with the same params but a different fragment, core's\n * SAME_STATES check would otherwise reject the navigation. The helper adds\n * `force: true` and `hashChange: true` automatically — subscribers can then\n * disambiguate via `state.context.url.hashChanged`.\n *\n * For pure programmatic same-route hash-only navigation, callers are\n * documented to pass `{ force: true }` themselves; the auto-bypass here is\n * a UX convenience for `<Link hash>` that all 6 framework adapters share.\n */\n/**\n * Local extended-options type. Adapters that depend only on `@real-router/core`\n * (without a URL plugin) do not see the `NavigationOptions` augmentation that\n * declares `hash` / `hashChange`. Casting to this widened type inside the\n * helper keeps shared/dom-utils self-contained — adapters do not need to\n * augment NavigationOptions themselves to consume `<Link hash>`.\n */\ntype HashAwareNavigationOptions = NavigationOptions & {\n hash?: string;\n hashChange?: boolean;\n};\n\nexport function navigateWithHash(\n router: Router,\n routeName: string,\n routeParams: Params,\n routeSearch: SearchParams | undefined,\n hash: string | undefined,\n extraOptions?: NavigationOptions,\n): Promise<State> {\n const opts: HashAwareNavigationOptions = { ...extraOptions };\n\n if (hash !== undefined) {\n opts.hash = hash;\n }\n\n const current = router.getState();\n\n // \"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 writing\n // `routeSearch={{ page: \"2\" }}` never matched a state parsed from `?page=2`,\n // where the value is the NUMBER 2 — the bypass silently did not fire, core\n // rejected the navigation as SAME_STATES, and `<Link hash>` looked dead. The\n // predicate carries the provenance-tolerant comparison (#1554) that makes the\n // two forms equal because they print the same URL.\n //\n // It also compared the caller's whole `routeParams` bag against `state.params`,\n // which stopped meaning anything once the channels split (#1548) — the\n // predicate applies the channel rule instead of re-deriving it.\n //\n // `strictEquality: true` — a link to a PARENT route is a different location, so\n // the hierarchical arm must not match. `ignoreQueryParams: false` — the query is\n // part of the location here; ignoring it would fire the bypass across a real\n // query change and let `force: true` smuggle it through as a hash change.\n if (\n current !== undefined &&\n router.isActiveRoute(\n routeName,\n routeParams,\n routeSearch ?? current.search,\n true,\n false,\n )\n ) {\n const currentHash =\n (current.context as { url?: { hash?: string } } | undefined)?.url?.hash ??\n \"\";\n const newHash = hash ?? currentHash;\n\n if (currentHash !== newHash) {\n opts.force = true;\n opts.hashChange = true;\n }\n }\n\n // Query channel at position 3 (RFC-4 M2 / #1548) — from the `routeSearch`\n // prop; opts at position 4. `undefined` when the link has no `routeSearch`.\n return router.navigate(routeName, routeParams, routeSearch, opts);\n}\n\n// Match-any-whitespace regex shared across calls. RegExp literals at\n// call-site recompile in some engines; lifting it avoids that microcost\n// for the slow-path branch.\nconst WHITESPACE_PROBE = /\\s/;\nconst WHITESPACE_SPLIT = /\\S+/g;\n\n// `value` is always a truthy class string: both call sites narrow it first\n// (`if (isActive && activeClassName)` / `if (!baseClassName) return …`), so the\n// former `if (!value) return []` guard was unreachable dead code (#809).\nfunction parseTokens(value: string): string[] {\n // Hot-path fast-path (audit-2026-05-17 §8b #1): >99% of active-class\n // inputs at `<Link>` emit are single-token strings like `\"active\"` or\n // `\"is-current\"` — no whitespace, no leading/trailing pad. Skip the\n // regex match and Array result allocation: a literal `[value]` works\n // because the slow-path `match(/\\S+/g)` would return exactly `[value]`\n // for the same input. PBT lock: linkUtils.properties.ts Invariant 13.\n if (!WHITESPACE_PROBE.test(value)) {\n return [value];\n }\n\n return value.match(WHITESPACE_SPLIT) ?? [];\n}\n\nexport function buildActiveClassName(\n isActive: boolean,\n activeClassName: string | undefined,\n baseClassName: string | undefined,\n): string | undefined {\n if (isActive && activeClassName) {\n const activeTokens = parseTokens(activeClassName);\n\n if (activeTokens.length === 0) {\n return baseClassName ?? undefined;\n }\n if (!baseClassName) {\n return activeTokens.join(\" \");\n }\n\n const baseTokens = parseTokens(baseClassName);\n const seen = new Set(baseTokens);\n\n for (const token of activeTokens) {\n if (seen.has(token)) {\n continue;\n }\n\n seen.add(token);\n baseTokens.push(token);\n }\n\n return baseTokens.join(\" \");\n }\n\n return baseClassName ?? undefined;\n}\n\n/**\n * One-level structural equality using `Object.is` per key.\n *\n * **String-keyed properties only (Mini-sprint E.3 — audit-5 §4.2 #3).**\n * Implementation walks `Object.keys()` which by spec returns only\n * enumerable own STRING keys. Symbol-keyed properties — created via\n * `obj[Symbol(\"brand\")] = value` or `{ [Symbol(...)]: value }` — are\n * NOT compared. Two records that differ only in a Symbol-keyed value\n * will compare as equal.\n *\n * This is intentional: route params and Link options are documented as\n * string-keyed primitives (string | number | boolean) — Symbol-keyed\n * metadata (e.g. brand markers, private state) doesn't belong in a\n * cache-key comparison. Switching to `Reflect.ownKeys()` would extend\n * the contract to symbols at the cost of one extra allocation per call\n * (Reflect.ownKeys composes string-keys + symbol-keys arrays). If a\n * consumer relies on symbol-keyed metadata for navigation\n * disambiguation, they should encode it into a string key instead.\n *\n * Mirrors React's `shallowEqual` (packages/shared/shallowEqual.js) in\n * both the string-keys-only semantics and the `hasOwnProperty` guard\n * below.\n */\nexport function shallowEqual(\n prev: object | undefined,\n next: object | undefined,\n): boolean {\n if (Object.is(prev, next)) {\n return true;\n }\n if (!prev || !next) {\n return false;\n }\n\n const prevKeys = objectKeys(prev);\n\n if (prevKeys.length !== objectKeys(next).length) {\n return false;\n }\n\n const prevRecord = prev as Record<string, unknown>;\n const nextRecord = next as Record<string, unknown>;\n\n for (const key of prevKeys) {\n // hasOwnProperty guard: without it, a key missing in `next` reads as\n // `undefined` and falsely matches `prev[key] === undefined`. Same shape\n // as React's shallowEqual (packages/shared/shallowEqual.js).\n if (\n !Object.prototype.hasOwnProperty.call(next, key) ||\n !Object.is(prevRecord[key], nextRecord[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function applyLinkA11y(element: HTMLElement | null | undefined): void {\n if (!element) {\n return;\n }\n\n // Cross-realm safety (audit-2026-05-17 §5 HIGH #4):\n // `instanceof HTMLAnchorElement` compares against the constructor from\n // the CURRENT realm. An element created in a different window (iframe\n // contentDocument, micro-frontend, embedded widget) fails the check\n // even when it IS a real anchor — the helper would then inject\n // role=\"link\" + tabindex=\"0\" on top of native anchor semantics,\n // breaking screen reader output (\"link link\") and focus order.\n //\n // tagName is realm-agnostic and is uppercase for HTML-namespaced\n // elements in any document. SVG `<a>` has lowercase tagName plus a\n // different prototype (SVGAElement) — skipping it here is wrong by\n // accident: SVG anchors don't have keyboard activation semantics the\n // helper would add. But they also don't reach this helper in\n // practice (router Link components emit HTML anchors). Lock the\n // uppercase compare to keep the contract narrow.\n const tag = element.tagName;\n\n if (tag === \"A\" || tag === \"BUTTON\") {\n return;\n }\n if (!element.hasAttribute(\"role\")) {\n element.setAttribute(\"role\", \"link\");\n }\n if (!element.hasAttribute(\"tabindex\")) {\n element.setAttribute(\"tabindex\", \"0\");\n }\n}\n","import { createActiveSource } from \"@real-router/sources\";\nimport { defineComponent, h, computed, shallowRef, watch } from \"vue\";\n\nimport { useRouter } from \"../composables/useRouter\";\nimport { EMPTY_PARAMS, EMPTY_OPTIONS } from \"../constants\";\nimport {\n shouldNavigate,\n buildHref,\n buildActiveClassName,\n navigateWithHash,\n resolveLinkTarget,\n shallowEqual,\n} from \"../dom-utils\";\n\nimport type {\n Params,\n NavigationOptions,\n NavigationTarget,\n SearchParams,\n} from \"@real-router/core\";\nimport type { PropType } from \"vue\";\n\ntype OnClickHandler = (evt: MouseEvent) => void;\n\n/**\n * Invoke ONE user `@click` handler in isolation (#1352). A throwing handler must\n * NOT skip the Link's own navigation (which `handleClick` runs after this\n * returns) or — in the array form — abort the remaining sibling handlers. Native\n * `<a>` logs a throwing click listener and still performs the default action;\n * this matches the codebase's adapter-callback isolation norm\n * (`RouterErrorBoundary.onError`, `EventEmitter.emit`). The user's own\n * `preventDefault()` still takes effect (it runs before any throw), so the\n * `defaultPrevented` contract below is unchanged.\n */\nfunction invokeUserOnClick(fn: OnClickHandler, evt: MouseEvent): void {\n try {\n fn(evt);\n } catch (error) {\n console.error(\n \"[real-router] A <Link> @click handler threw; navigation is unaffected.\",\n error,\n );\n }\n}\n\n/**\n * Vue's compiled template binds multiple `@click` handlers as an array.\n * Single render-function `onClick` is a function. Both must be invoked, each\n * isolated via `invokeUserOnClick` (#1352).\n *\n * The function-branch deliberately omits a `defaultPrevented` check: the\n * single call short-circuits naturally and control returns to the caller\n * (`handleClick`), which then re-reads `evt.defaultPrevented` on the same\n * MouseEvent. The array-branch needs the per-iteration check because the\n * caller cannot observe intermediate handlers — without it, later handlers\n * would still run after an earlier one called `preventDefault()`.\n */\nfunction invokeAttributesOnClick(value: unknown, evt: MouseEvent): void {\n if (typeof value === \"function\") {\n invokeUserOnClick(value as OnClickHandler, evt);\n\n return;\n }\n if (Array.isArray(value)) {\n const handlers = value as OnClickHandler[];\n\n for (const fn of handlers) {\n if (typeof fn !== \"function\") {\n continue;\n }\n\n invokeUserOnClick(fn, evt);\n\n if (evt.defaultPrevented) {\n return;\n }\n }\n }\n}\n\nexport const Link = defineComponent({\n name: \"Link\",\n // Disable Vue's automatic attribute fallthrough. Without this, attrs.onClick\n // (function OR array) is auto-attached as a native click listener AND our\n // explicit onClick fires too — user handlers are double-invoked. We invoke\n // attrs.onClick manually inside handleClick to preserve preventDefault.\n inheritAttrs: false,\n props: {\n // Optional (was required) since the descriptor form (`to`) omits it — the\n // two forms are mutually exclusive, enforced at runtime by resolveLinkTarget.\n routeName: {\n type: String,\n default: undefined,\n },\n // Descriptor form (RFC-4 M2 B2, #1548): `to={{ name, params?, search? }}`,\n // mutually exclusive with the routeName/routeParams/routeSearch channels.\n to: {\n type: Object as PropType<NavigationTarget>,\n default: undefined,\n },\n // Default `undefined` (NOT EMPTY_PARAMS): an omitted `routeParams` must reach\n // `createActiveRouteSource` as `undefined` so it keys the active source as \"\"\n // and shares ONE cached source (one router subscription) with a manual\n // `useIsActiveRoute(routeName)`. Defaulting to EMPTY_PARAMS ({}) here would key\n // \"{}\" and split the same logical question into a second eager subscription\n // (#776). Navigation/href default to EMPTY_PARAMS locally where a concrete\n // object is required.\n routeParams: {\n type: Object as PropType<Params>,\n default: undefined,\n },\n // Query (search) channel (RFC-4 M2, #1548) — parallel to routeParams.\n routeSearch: {\n type: Object as PropType<SearchParams>,\n default: undefined,\n },\n routeOptions: {\n type: Object as PropType<NavigationOptions>,\n default: () => EMPTY_OPTIONS,\n },\n class: {\n type: String,\n default: undefined,\n },\n activeClassName: {\n type: String,\n default: \"active\",\n },\n activeStrict: {\n type: Boolean,\n default: false,\n },\n ignoreQueryParams: {\n type: Boolean,\n default: true,\n },\n target: {\n type: String,\n default: undefined,\n },\n /**\n * URL fragment (decoded form, no leading \"#\") (#532).\n * - omitted/`undefined` → preserve current fragment on same-route navigation\n * - `\"\"` → clear fragment\n * - non-empty → set fragment\n */\n hash: {\n type: String,\n default: undefined,\n },\n },\n setup(props, { slots, attrs }) {\n const router = useRouter();\n\n const isActive = shallowRef(false);\n\n // Content-stable `routeParams` reference. A parent that hands an inline\n // `:routeParams=\"{ id: 1 }\"` literal allocates a fresh object on every\n // render; keying the derivations below off that raw reference would re-run\n // `buildHref` and re-subscribe the ActiveRouteSource on every unrelated\n // parent update. `shallowEqual` collapses structurally-equal params to a\n // stable reference (Object.is per key, order-insensitive — the same\n // contract as the React adapter's Link `memo` comparator), so the `href`\n // computed and the active `watch` bail out until params content actually\n // changes.\n //\n // Hot path on Link-heavy pages: this replaces a per-navigation\n // `canonicalJson` (JSON.stringify + key sort) with a per-navigation\n // `shallowEqual` (no allocation), and lets same-shape navigations skip\n // `buildHref` entirely. Nested-object param VALUES fall back to per-render\n // recompute (shallowEqual compares them by reference) — stabilize with a\n // `ref`/`computed` if it matters, exactly as documented for the React Link.\n // `Params | undefined`: `undefined` (no params) is preserved end-to-end so the\n // active source keys \"\" (see the `routeParams` prop default note, #776).\n let cachedParams: Params | undefined = props.routeParams;\n const stableParams = computed<Params | undefined>(() => {\n const next = props.routeParams;\n\n if (!shallowEqual(cachedParams, next)) {\n cachedParams = next;\n }\n\n return cachedParams;\n });\n\n // Recreate the ActiveRouteSource ONLY when the Link's identity\n // (routeName / params content / strict / ignoreQueryParams / hash) changes.\n // `stableParams` already absorbs same-content param churn, so this dep\n // array is reference-stable across navigations that don't change shape and\n // the subscription persists.\n watch(\n () =>\n [\n props.routeName,\n stableParams.value,\n props.routeSearch,\n props.to,\n props.activeStrict,\n props.ignoreQueryParams,\n props.hash,\n ] as const,\n (\n [\n routeName,\n routeParams,\n routeSearch,\n to,\n activeStrict,\n ignoreQueryParams,\n hash,\n ],\n _prev,\n onCleanup,\n ) => {\n // Resolve the two prop forms (RFC-4 M2 B2, #1548): `to` supersedes the\n // channel props (dev-warn on conflict).\n const resolved = resolveLinkTarget(\n to,\n routeName ?? \"\",\n routeParams,\n routeSearch,\n );\n\n // Hash-aware active (#532): pass hash through so tab links with the\n // same routeName but different `hash` props don't all light up.\n const source = createActiveSource(\n router,\n resolved.name,\n resolved.params,\n resolved.search,\n activeStrict,\n ignoreQueryParams,\n hash,\n );\n\n isActive.value = source.getSnapshot();\n\n const unsub = source.subscribe(() => {\n isActive.value = source.getSnapshot();\n });\n\n onCleanup(unsub);\n },\n { immediate: true, flush: \"sync\" },\n );\n\n const href = computed(() => {\n const resolved = resolveLinkTarget(\n props.to,\n props.routeName ?? \"\",\n stableParams.value,\n props.routeSearch,\n );\n\n return buildHref(\n router,\n resolved.name,\n resolved.params ?? EMPTY_PARAMS,\n resolved.search,\n props.hash,\n );\n });\n\n const finalClassName = computed(() =>\n buildActiveClassName(isActive.value, props.activeClassName, props.class),\n );\n\n const handleClick = (evt: MouseEvent) => {\n // Vue allows attrs.onClick to be a function or an array of functions\n // (compiled templates with multiple @click bindings produce arrays).\n // Both must be invoked; treating arrays as \"no handler\" silently drops\n // user code.\n if (attrs.onClick !== undefined && attrs.onClick !== null) {\n invokeAttributesOnClick(attrs.onClick, evt);\n\n if (evt.defaultPrevented) {\n return;\n }\n }\n\n if (!shouldNavigate(evt) || props.target === \"_blank\") {\n return;\n }\n\n evt.preventDefault();\n\n const resolved = resolveLinkTarget(\n props.to,\n props.routeName ?? \"\",\n props.routeParams,\n props.routeSearch,\n );\n\n navigateWithHash(\n router,\n resolved.name,\n resolved.params ?? EMPTY_PARAMS,\n resolved.search,\n props.hash,\n props.routeOptions,\n ).catch(() => {});\n };\n\n return () => {\n // Build forwarded attrs without `onClick`. Vue's runtime auto-attaches\n // attrs.onClick (function OR array) as a native DOM listener, which would\n // double-invoke user handlers when combined with our explicit `onClick`.\n // We invoke the original attrs.onClick manually inside handleClick so the\n // preventDefault contract is preserved.\n //\n // Spread + delete avoids the per-key copy loop on every render — one\n // allocation + one property deletion instead of N iterations across\n // data-*, aria-*, role, etc. Hot-path optimisation for Link-heavy pages.\n const restAttributes = { ...attrs };\n\n delete restAttributes.onClick;\n\n return h(\n \"a\",\n {\n ...restAttributes,\n href: href.value,\n class: finalClassName.value,\n target: props.target,\n onClick: handleClick,\n },\n slots.default?.(),\n );\n };\n },\n});\n","import { createDismissableError } from \"@real-router/sources\";\nimport { defineComponent, h, watch, Fragment } from \"vue\";\n\nimport { useRouter } from \"../composables/useRouter\";\nimport { useRefFromSource } from \"../useRefFromSource\";\n\nimport type { RouterError, State } from \"@real-router/core\";\nimport type { VNode, PropType } from \"vue\";\n\nexport const RouterErrorBoundary = defineComponent({\n name: \"RouterErrorBoundary\",\n props: {\n fallback: {\n type: Function as PropType<\n (error: RouterError, resetError: () => void) => VNode\n >,\n required: true,\n },\n onError: {\n type: Function as PropType<\n (\n error: RouterError,\n toRoute: State | null,\n fromRoute: State | null,\n ) => void\n >,\n default: undefined,\n },\n },\n setup(props, { slots }) {\n const router = useRouter();\n const snapshot = useRefFromSource(createDismissableError(router));\n\n watch(\n () => snapshot.value.version,\n () => {\n if (snapshot.value.error) {\n props.onError?.(\n snapshot.value.error,\n snapshot.value.toRoute,\n snapshot.value.fromRoute,\n );\n }\n },\n { immediate: true },\n );\n\n return () => {\n const children = slots.default?.() ?? [];\n const errorVNode = snapshot.value.error\n ? props.fallback(snapshot.value.error, snapshot.value.resetError)\n : null;\n\n return h(Fragment, null, [...children, errorVNode]);\n };\n },\n});\n\nexport type RouterErrorBoundaryProps = InstanceType<\n typeof RouterErrorBoundary\n>[\"$props\"];\n","import { shouldNavigate, applyLinkA11y } from \"../dom-utils\";\n\nimport type { Router, NavigationOptions, Params } from \"@real-router/core\";\nimport type { Directive } from \"vue\";\n\nexport interface LinkDirectiveValue {\n name: string;\n params?: Params;\n options?: NavigationOptions;\n}\n\n/**\n * Router stack for nested RouterProviders. The active router is the top of\n * the stack. RouterProvider pushes its router on mount and pops it on unmount,\n * which preserves the parent context when an inner provider tears down.\n *\n * Without the stack, an unmounted child provider would leave the directive\n * pointing at a disposed router, and v-link in the still-mounted parent would\n * navigate via the wrong (or torn-down) instance.\n */\nconst routerStack: Router[] = [];\n\n/**\n * Pushes a router onto the active stack. Returns a release function that\n * removes that exact router from the stack regardless of position — safe\n * across out-of-order provider unmount sequences.\n *\n * @internal Used by RouterProvider during setup/teardown.\n */\nexport function pushDirectiveRouter(router: Router): () => void {\n routerStack.push(router);\n\n return () => {\n const idx = routerStack.lastIndexOf(router);\n\n if (idx !== -1) {\n routerStack.splice(idx, 1);\n }\n };\n}\n\n/**\n * Backwards-compatible alias. Replaces the active router unconditionally and\n * does NOT participate in the stack — use {@link pushDirectiveRouter} from\n * provider code instead. Not exported from the package entry; retained for\n * unit tests and rare standalone-directive setups (where v-link is mounted\n * outside any RouterProvider).\n *\n * @internal\n */\nexport function setDirectiveRouter(router: Router | null): void {\n if (router === null) {\n routerStack.length = 0;\n\n return;\n }\n if (routerStack.length === 0) {\n routerStack.push(router);\n\n return;\n }\n\n routerStack[routerStack.length - 1] = router;\n}\n\nexport function getDirectiveRouter(): Router {\n const top = routerStack.at(-1);\n\n if (!top) {\n throw new Error(\n \"v-link directive requires a RouterProvider ancestor. Make sure RouterProvider is mounted.\",\n );\n }\n\n return top;\n}\n\ninterface Handlers {\n click: (evt: MouseEvent) => void;\n keydown: (evt: KeyboardEvent) => void;\n}\n\n// Single WeakMap halves per-element bookkeeping vs two parallel maps.\nconst handlers = new WeakMap<HTMLElement, Handlers>();\n\n/**\n * Validates a directive binding value before attaching handlers.\n * Returns false (and warns once per call) when the value is missing or\n * has no `name` — silently doing nothing is preferable to a runtime crash\n * inside a click handler.\n */\nfunction isValidBinding(value: unknown): value is LinkDirectiveValue {\n if (value === null || value === undefined) {\n console.error(\n \"[real-router] v-link directive received null/undefined value. The element will not be wired for navigation.\",\n );\n\n return false;\n }\n if (typeof (value as { name?: unknown }).name !== \"string\") {\n console.error(\n \"[real-router] v-link directive value is missing a string `name` field. The element will not be wired for navigation.\",\n );\n\n return false;\n }\n\n return true;\n}\n\nfunction createClickHandler(\n router: Router,\n value: LinkDirectiveValue,\n): (evt: MouseEvent) => void {\n return (evt: MouseEvent) => {\n if (!shouldNavigate(evt)) {\n return;\n }\n\n evt.preventDefault();\n router\n .navigate(value.name, value.params ?? {}, undefined, value.options ?? {})\n .catch(() => {});\n };\n}\n\nfunction createKeydownHandler(\n router: Router,\n value: LinkDirectiveValue,\n element: HTMLElement,\n): (evt: KeyboardEvent) => void {\n return (evt: KeyboardEvent) => {\n if (evt.key === \"Enter\" && !(element instanceof HTMLButtonElement)) {\n router\n .navigate(\n value.name,\n value.params ?? {},\n undefined,\n value.options ?? {},\n )\n .catch(() => {});\n }\n };\n}\n\nfunction attachHandlers(\n element: HTMLElement,\n router: Router,\n value: LinkDirectiveValue,\n): void {\n const click = createClickHandler(router, value);\n const keydown = createKeydownHandler(router, value, element);\n\n element.addEventListener(\"click\", click);\n element.addEventListener(\"keydown\", keydown);\n\n handlers.set(element, { click, keydown });\n}\n\nfunction detachHandlers(element: HTMLElement): void {\n const entry = handlers.get(element);\n\n if (entry) {\n element.removeEventListener(\"click\", entry.click);\n element.removeEventListener(\"keydown\", entry.keydown);\n handlers.delete(element);\n }\n}\n\nexport const vLink: Directive<HTMLElement, LinkDirectiveValue> = {\n mounted(element, binding) {\n const router = getDirectiveRouter();\n\n applyLinkA11y(element);\n\n element.style.cursor = \"pointer\";\n\n if (!isValidBinding(binding.value)) {\n return;\n }\n\n attachHandlers(element, router, binding.value);\n },\n\n updated(element, binding) {\n // Hot-path guard: Vue invokes `updated` on every parent re-render even\n // when the directive's binding value reference has not changed. Without\n // this short-circuit, every parent rerender (which is the common case on\n // Link-heavy pages — any unrelated state change triggers the parent's\n // render fn) would detach + reattach the click/keydown listeners.\n // Comparing references is enough: when consumers pass a stable\n // `LinkDirectiveValue` object (the recommended pattern, since Vue's\n // template compiler hoists `v-link=\"{ name: 'home' }\"` to a stable\n // literal), this guard collapses the work to zero.\n if (binding.value === binding.oldValue) {\n return;\n }\n\n const router = getDirectiveRouter();\n\n detachHandlers(element);\n\n if (!isValidBinding(binding.value)) {\n return;\n }\n\n attachHandlers(element, router, binding.value);\n },\n\n beforeUnmount(element) {\n detachHandlers(element);\n },\n};\n","import { inject } from \"vue\";\n\nimport { NavigatorKey } from \"../context\";\n\nimport type { Navigator } from \"@real-router/core\";\n\nexport const useNavigator = (): Navigator => {\n const navigator = inject(NavigatorKey);\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\nexport const useRouteUtils = (): RouteUtils => {\n const router = useRouter();\n\n return getRouteUtils(getPluginApi(router).getTree());\n};\n","import { getTransitionSource } from \"@real-router/sources\";\n\nimport { useRefFromSource } from \"../useRefFromSource\";\nimport { useRouter } from \"./useRouter\";\n\nimport type { RouterTransitionSnapshot } from \"@real-router/sources\";\nimport type { ShallowRef } from \"vue\";\n\nexport function useRouterTransition(): ShallowRef<RouterTransitionSnapshot> {\n const router = useRouter();\n const source = getTransitionSource(router);\n\n return useRefFromSource(source);\n}\n","import { guardLeaveListener } from \"@real-router/sources\";\nimport { onActivated, onDeactivated, onScopeDispose } from \"vue\";\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.\n * - **Same-route skip**: by default, `route.name === nextRoute.name`\n * short-circuits the handler — query-only navigations skip the work.\n * Opt out with `skipSameRoute: false`.\n *\n * Cleanup is bound to the component's effect scope via `onScopeDispose`.\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` (that\n * arises only when the navigation's `signal` aborts).\n *\n * **Handler reactivity (Vue):** Vue composables run **once** during\n * `setup()`; `handler` is captured in closure at the call site. To vary\n * behavior over time, read refs/computeds inside the handler body — do\n * not rely on swapping the handler reference.\n *\n * **Under `<KeepAlive>` (#1221):** a deactivated (sleeping) page does not run\n * the handler on unrelated navigations — critically, its async exit is not\n * spliced into every navigation's leave cycle (where it would block the app).\n *\n * @example Animation\n * ```ts\n * const ref = useTemplateRef<HTMLDivElement>(\"box\");\n *\n * useRouteExit(async ({ signal }) => {\n * const el = ref.value;\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();\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 * ```ts\n * useRouteExit(async ({ signal }) => {\n * if (formState.value.dirty) {\n * await api.saveDraft(formState.value, { signal });\n * }\n * });\n * ```\n *\n * @example Detecting that you are leaving a subtree\n * ```ts\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 skipSameRoute = options?.skipSameRoute ?? true;\n\n // #1221 — under <KeepAlive> a deactivated component keeps its effect scope\n // (and this subscription) alive. Gate on deactivated state so a sleeping page\n // does not run its exit handler on unrelated navigations — critically, a\n // sleeping page's async (Promise-returning) exit would otherwise be spliced\n // into every navigation's leave cycle and BLOCK it. `onActivated` /\n // `onDeactivated` only fire under KeepAlive; without it the flag stays `false`\n // and the subscription runs as before. The page being LEFT is still active\n // when its own leave window runs (deactivation happens on the subsequent\n // commit), so a genuine exit still fires.\n let isDeactivated = false;\n\n onActivated(() => {\n isDeactivated = false;\n });\n onDeactivated(() => {\n isDeactivated = true;\n });\n\n // The same-route + reentrant-abort guards and the Promise passthrough live in\n // the shared listener (@real-router/sources, #1435); the handler is captured\n // at init (Vue's setup runs once).\n const guardedLeave = guardLeaveListener(handler, { skipSameRoute });\n\n const off = router.subscribeLeave((leaveState) => {\n // The #1221 KeepAlive pre-gate stays adapter-side and composes BEFORE the\n // shared guards — a deactivated (sleeping) page must never enter the leave\n // cycle (its async exit would otherwise be spliced into every navigation and\n // block it).\n if (isDeactivated) {\n return;\n }\n\n return guardedLeave(leaveState);\n });\n\n onScopeDispose(off);\n}\n","import { createRouteEnterGate } from \"@real-router/sources\";\nimport { onActivated, onDeactivated, watch } from \"vue\";\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 composable covers that an ad-hoc `watch` + `useRoute()`\n * doesn't:\n *\n * - **Skip-initial**: `watch` (with default `immediate: false`) plus the\n * explicit `route.transition.from` guard ensures the handler doesn't\n * fire on the very first state committed by `router.start()`.\n * - **Same-route skip** (default): handler is skipped when\n * `route.transition.from === route.name`. Sort/filter/query-only\n * navigations re-trigger the watcher, but they are not \"entries\" in\n * the animation / analytics sense. Opt out with\n * `skipSameRoute: false`.\n * - **Mount-time `route` / `previousRoute` snapshot**: handler receives\n * the values that were live at the moment of the new state, not the\n * latest ones (which may have moved on if the user navigated again\n * before the watcher drained).\n *\n * **Handler reactivity (Vue):** Vue composables run **once** during\n * `setup()`; `handler` is captured in closure at the call site. To vary\n * behavior over time, read refs/computeds inside the handler body.\n *\n * **Under `<KeepAlive>` (#1221):** a deactivated (sleeping) page does not fire\n * the handler on unrelated navigations, and waking it does not re-fire —\n * reactivation is not a mount (use Vue's native `onActivated` to re-run on show).\n *\n * @example Direction-aware entry animation\n * ```ts\n * useRouteEnter(({ route }) => {\n * const direction = route.context.browser?.direction;\n * ref.value?.classList.add(\n * direction === \"back\" ? \"slide-from-left\" : \"slide-from-right\",\n * );\n * });\n * ```\n *\n * @example Analytics page-enter event (skip-initial built-in)\n * ```ts\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 * ```ts\n * useRouteEnter(({ route }) => {\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 * });\n * ```\n */\nexport function useRouteEnter(\n handler: RouteEnterHandler,\n options?: UseRouteEnterOptions,\n): void {\n const { route, previousRoute } = useRoute();\n const skipSameRoute = options?.skipSameRoute ?? true;\n // The canonical enter-guard set + `lastHandledRoute` dedupe live in the shared\n // gate (@real-router/sources, #1435). Vue's setup runs once, so a plain const\n // holds the gate across watcher runs. The gate owns skip-initial / same-route\n // / dedupe / the `!previousRoute` guard — the sole defense of the non-nullable\n // `RouteEnterContext.previousRoute` contract (#1218), now tested once in\n // sources rather than v8-ignored per adapter. (In Vue both skip-initial and\n // `!prev` are in fact unreachable — `watch` defaults to `immediate: false`, so\n // the initial commit and the undefined-`previousRoute` baseline are never\n // observed — but the gate arms them uniformly for cross-adapter parity.)\n const gate = createRouteEnterGate();\n\n // #1221 — under <KeepAlive> a deactivated component keeps its effect scope\n // (and this watcher) alive, so a sleeping page would otherwise fire `handler`\n // on every unrelated app navigation. This pre-gate stays adapter-side: the\n // framework-free gate has no channel to observe Vue's deactivation lifecycle.\n // `onActivated` / `onDeactivated` only fire under KeepAlive; without it the\n // flag stays `false` and the watcher runs exactly as before. Reactivating a\n // kept-alive page does NOT re-fire enter (strict-mount): this watcher flushes\n // before `onActivated`, so the flag is still `true` when the reactivating\n // navigation lands — waking a never-unmounted page is not a mount.\n let isDeactivated = false;\n\n onActivated(() => {\n isDeactivated = false;\n });\n onDeactivated(() => {\n isDeactivated = true;\n });\n\n watch(route, (newRoute) => {\n if (isDeactivated) {\n return;\n }\n\n const context = gate(newRoute, previousRoute.value, skipSameRoute);\n\n if (context) {\n handler(context);\n }\n });\n}\n","// packages/vue/src/setupRouteProvision.ts\n\nimport { getNavigator } from \"@real-router/core\";\nimport { createRouteSource } from \"@real-router/sources\";\nimport { shallowRef } from \"vue\";\n\nimport type { Router, Navigator, State } from \"@real-router/core\";\nimport type { ShallowRef } from \"vue\";\n\n/**\n * Shared setup for `RouterProvider` (component-scoped) and\n * `createRouterPlugin` (app-scoped). Builds the reactive route refs +\n * subscription bookkeeping in one place; callers wire the result into their\n * provide/inject mechanism and own teardown lifecycle.\n *\n * @internal\n */\nexport interface RouteProvision {\n navigator: Navigator;\n route: ShallowRef<State | undefined>;\n previousRoute: ShallowRef<State | undefined>;\n /** Call when the owning scope tears down to release the router subscription. */\n unsubscribe: () => void;\n}\n\nexport function setupRouteProvision(router: Router): RouteProvision {\n const navigator = getNavigator(router);\n const source = createRouteSource(router);\n const initial = source.getSnapshot();\n\n const route = shallowRef<State | undefined>(initial.route);\n const previousRoute = shallowRef<State | undefined>(initial.previousRoute);\n\n const unsubscribe = source.subscribe(() => {\n const snapshot = source.getSnapshot();\n\n route.value = snapshot.route;\n previousRoute.value = snapshot.previousRoute;\n });\n\n return { navigator, route, previousRoute, unsubscribe };\n}\n","import { NavigatorKey, RouteKey, RouterKey } from \"./context\";\nimport { pushDirectiveRouter } from \"./directives/vLink\";\nimport { setupRouteProvision } from \"./setupRouteProvision\";\n\nimport type { Router } from \"@real-router/core\";\nimport type { App, Plugin } from \"vue\";\n\nexport function createRouterPlugin(router: Router): Plugin<[]> {\n return {\n install(app): void {\n const releaseDirective = pushDirectiveRouter(router);\n\n const { navigator, route, previousRoute, unsubscribe } =\n setupRouteProvision(router);\n\n // Vue 3.5+ exposes app.onUnmount for plugin cleanup.\n // On older versions (3.3–3.4), the subscription is cleaned up\n // when the router is garbage-collected (same as vue-router).\n if (\"onUnmount\" in app) {\n (app as App & { onUnmount: (fn: () => void) => void }).onUnmount(() => {\n releaseDirective();\n unsubscribe();\n });\n }\n\n app.provide(RouterKey, router);\n app.provide(NavigatorKey, navigator);\n app.provide(RouteKey, { navigator, route, previousRoute });\n },\n };\n}\n","import { primeErrorSource } from \"@real-router/sources\";\nimport { defineComponent, onScopeDispose, provide, watch } from \"vue\";\n\nimport { NavigatorKey, RouteKey, RouterKey } from \"./context\";\nimport { pushDirectiveRouter } from \"./directives/vLink\";\nimport {\n createRouteAnnouncer,\n createScrollRestoration,\n createScrollSpy,\n createViewTransitions,\n} from \"./dom-utils\";\nimport { setupRouteProvision } from \"./setupRouteProvision\";\n\nimport type {\n RouteAnnouncerOptions,\n ScrollRestorationOptions,\n ScrollSpyOptions,\n} from \"./dom-utils\";\nimport type { Router } from \"@real-router/core\";\nimport type { PropType } from \"vue\";\n\ninterface Disposable {\n destroy: () => void;\n}\n\n/**\n * Watch a dependency tuple and (re)create a toggleable utility (announcer /\n * scroll-restorer / view-transitions). The factory returns `undefined` to\n * mean \"feature disabled\" — no utility is created and no cleanup is wired.\n * When a utility IS returned, its `destroy()` is registered via `onCleanup`,\n * so flipping any dep (incl. the feature flag) tears down the previous\n * instance before constructing the next.\n *\n * Extracted from three near-identical `watch(... { immediate: true })` blocks\n * (announceNavigation / scrollRestoration / viewTransitions) — DRY without\n * losing the per-utility dep tuple shape.\n */\nfunction watchToggleableUtility<D extends readonly unknown[]>(\n deps: () => D,\n factory: (current: D) => Disposable | undefined,\n): void {\n watch(\n deps,\n (current, _prev, onCleanup) => {\n const utility = factory(current);\n\n if (utility) {\n onCleanup(() => {\n utility.destroy();\n });\n }\n },\n { immediate: true },\n );\n}\n\nexport const RouterProvider = defineComponent({\n name: \"RouterProvider\",\n props: {\n router: {\n type: Object as PropType<Router>,\n required: true,\n },\n announceNavigation: {\n type: [Boolean, Object] as PropType<boolean | RouteAnnouncerOptions>,\n default: false,\n },\n scrollRestoration: {\n type: Object as PropType<ScrollRestorationOptions>,\n },\n scrollSpy: {\n type: Object as PropType<ScrollSpyOptions>,\n },\n viewTransitions: {\n type: Boolean,\n default: false,\n },\n },\n setup(props, { slots }) {\n // Reactive announceNavigation: setting prop true/false at runtime\n // creates/destroys the announcer accordingly. Prior implementation read\n // the prop only inside onMounted, so toggling it post-mount silently no-op'd.\n // `announceNavigation` accepts `true` (default announcer) or a\n // `RouteAnnouncerOptions` object (`{ prefix, getAnnouncementText }`) for\n // custom announcement text. `false` / `undefined` disables it. Watched by\n // primitives (enabled + prefix) so inline-object identity churn doesn't\n // re-create the announcer; getAnnouncementText is captured once by the\n // utility (same rationale as scrollContainer below).\n watchToggleableUtility(\n () => {\n const nav = props.announceNavigation;\n const enabled = nav !== false;\n const prefix = typeof nav === \"object\" ? nav.prefix : undefined;\n\n return [props.router, enabled, prefix] as const;\n },\n ([router, enabled]) => {\n const nav = props.announceNavigation;\n const options = typeof nav === \"object\" ? nav : undefined;\n\n return enabled ? createRouteAnnouncer(router, options) : undefined;\n },\n );\n\n // Watch by primitives so inline `{ mode: \"restore\" }` doesn't thrash.\n // scrollContainer is a getter invoked lazily on every event inside the\n // utility — swapping its reference doesn't change the resolved element,\n // so we intentionally omit it from watched sources.\n watchToggleableUtility(\n () =>\n [\n props.router,\n props.scrollRestoration !== undefined,\n props.scrollRestoration?.mode,\n props.scrollRestoration?.anchorScrolling,\n props.scrollRestoration?.behavior,\n props.scrollRestoration?.storageKey,\n ] as const,\n ([router, enabled, mode, anchorScrolling, behavior, storageKey]) => {\n if (!enabled) {\n return;\n }\n\n return createScrollRestoration(router, {\n mode,\n anchorScrolling,\n behavior,\n storageKey,\n scrollContainer: props.scrollRestoration?.scrollContainer,\n });\n },\n );\n\n // Reactive scrollSpy: watch by primitives, omit scrollContainer getter\n // identity for the same reason scrollRestoration does.\n watchToggleableUtility(\n () =>\n [\n props.router,\n props.scrollSpy !== undefined && props.scrollSpy.selector !== \"\",\n props.scrollSpy?.selector,\n props.scrollSpy?.rootMargin,\n ] as const,\n ([router, enabled, selector, rootMargin]) => {\n if (!enabled || !selector) {\n return;\n }\n\n return createScrollSpy(router, {\n selector,\n rootMargin,\n scrollContainer: props.scrollSpy?.scrollContainer,\n });\n },\n );\n\n // Reactive viewTransitions: toggling prop creates/destroys the utility.\n watchToggleableUtility(\n () => [props.router, props.viewTransitions] as const,\n ([router, enabled]) =>\n enabled ? createViewTransitions(router) : undefined,\n );\n\n // Push this provider's router on the v-link directive stack so nested\n // RouterProviders behave like nested DI scopes (LIFO). Release on unmount\n // restores the outer router for any v-link still mounted in the parent.\n //\n // #779: only push in the browser. The v-link directive runs solely in\n // mounted client DOM, so the server never reads the stack — while\n // onScopeDispose (the release hook) never fires during renderToString, so a\n // server-side push would strand every per-request router in this\n // module-level array, a leak router.dispose() cannot clear. `typeof\n // document` mirrors the SSR guard used across shared/dom-utils. The release\n // gets its own onScopeDispose so the server path leaves no dead teardown\n // branch (a combined callback would only ever run on the client).\n const releaseDirective =\n typeof document === \"undefined\"\n ? undefined\n : pushDirectiveRouter(props.router);\n\n if (releaseDirective) {\n onScopeDispose(releaseDirective);\n }\n\n // #778 P2: eagerly create the per-router error source at Provider mount so a\n // navigation error that fires BEFORE a RouterErrorBoundary mounts (a lazy app\n // shell, a failed boot navigation) is still captured. The boundary's\n // createDismissableError reuses this cached source and catches up (#765);\n // without it the error source is created lazily on boundary mount — after the\n // error — and never sees it.\n primeErrorSource(props.router);\n\n const { navigator, route, previousRoute, unsubscribe } =\n setupRouteProvision(props.router);\n\n onScopeDispose(unsubscribe);\n\n provide(RouterKey, props.router);\n provide(NavigatorKey, navigator);\n provide(RouteKey, { navigator, route, previousRoute });\n\n return () => slots.default?.();\n },\n});\n"],"mappings":"4QAKA,SAAS,GAAa,CACpB,OAAO,IACT,CAEA,MAAa,GAAA,EAAA,EAAA,gBAAA,CAAwB,CACnC,KAAM,kBACN,MAAO,CACL,QAAS,CACP,KAAM,OACN,SAAU,EACZ,EACA,MAAO,CAC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