@real-router/angular 0.23.0 → 0.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2637 +1,1330 @@
1
- import * as i0 from '@angular/core';
2
- import { InjectionToken, inject, DestroyRef, ApplicationRef, signal, provideEnvironmentInitializer, makeEnvironmentProviders, makeStateKey, REQUEST, provideAppInitializer, TransferState, assertInInjectionContext, ChangeDetectorRef, effect, untracked, input, TemplateRef, Directive, contentChildren, computed, Component, output, ElementRef } from '@angular/core';
3
- import { events, getNavigator, UNKNOWN_ROUTE } from '@real-router/core';
4
- import { getTransitionSource, createRouteSource, primeErrorSource, createRouteNodeSource, createActiveSource, guardLeaveListener, createRouteEnterGate, createDismissableError } from '@real-router/sources';
5
- import { getPluginApi, cloneRouter } from '@real-router/core/api';
6
- import { putField } from '@real-router/core/utils';
7
- import { hydrateRouter, serializeRouterState } from '@real-router/ssr-utils';
8
- import { getRouteUtils, startsWithSegment } from '@real-router/route-utils';
9
- import { NgTemplateOutlet } from '@angular/common';
10
-
11
- const NOOP_INSTANCE$4 = Object.freeze({
12
- destroy: () => {
13
- /* no-op */
14
- },
15
- });
16
- /**
17
- * Track navigation direction (forward / back) and write it to
18
- * `<html data-nav-direction>` on every leave. CSS / JS readers consume
19
- * the attribute via `html[data-nav-direction="back"]` selectors or
20
- * `document.documentElement.dataset.navDirection`.
21
- *
22
- * Mechanism-agnostic — works identically whether downstream UI uses CSS
23
- * `@keyframes`, View Transitions pseudo-elements, or library state
24
- * (motion's `motion.div initial={{ x: ... }}`).
25
- *
26
- * Implementation:
27
- * - On install, set `data-nav-direction="forward"` baseline.
28
- * - Attach a `popstate` listener that flips an internal flag to
29
- * `true`. Browser back/forward navigation triggers popstate; user
30
- * clicks on `<Link>` / programmatic `router.navigate(...)` do not.
31
- * - On every `subscribeLeave`, write
32
- * `popstateFlag ? "back" : "forward"` and reset the flag.
33
- *
34
- * Returns `{ destroy }` to clean up the listener and clear the dataset
35
- * attribute.
36
- */
1
+ import * as i0 from "@angular/core";
2
+ import { ApplicationRef, ChangeDetectorRef, Component, DestroyRef, Directive, ElementRef, InjectionToken, REQUEST, TemplateRef, TransferState, assertInInjectionContext, computed, contentChildren, effect, inject, input, makeEnvironmentProviders, makeStateKey, output, provideAppInitializer, provideEnvironmentInitializer, signal, untracked } from "@angular/core";
3
+ import { UNKNOWN_ROUTE, events, getNavigator } from "@real-router/core";
4
+ import { createActiveSource, createDismissableError, createRouteEnterGate, createRouteNodeSource, createRouteSource, getTransitionSource, guardLeaveListener, primeErrorSource } from "@real-router/sources";
5
+ import { cloneRouter, getPluginApi } from "@real-router/core/api";
6
+ import { putField } from "@real-router/core/utils";
7
+ import { hydrateRouter, serializeRouterState } from "@real-router/ssr-utils";
8
+ import { getRouteUtils, startsWithSegment } from "@real-router/route-utils";
9
+ import { NgTemplateOutlet } from "@angular/common";
10
+ const NOOP_INSTANCE$4 = Object.freeze({ destroy: () => {} });
37
11
  function createDirectionTracker(router) {
38
- if (typeof document === "undefined") {
39
- return NOOP_INSTANCE$4;
40
- }
41
- let popstateFlag = false;
42
- document.documentElement.dataset.navDirection = "forward";
43
- let transitionInFlight = false;
44
- let armedMidTransition = false;
45
- // ⚑ The flag is SPENT by the transition it belongs to, whether or not that
46
- // transition reaches a leave phase (#1924). It is armed by any `popstate` on
47
- // `globalThis`, not only one the router consumes, so `history.back()` onto an
48
- // entry that resolves to the current state — core answers `SAME_STATES`, and
49
- // measured, that arc emits `TRANSITION_ERROR` with no `TRANSITION_START` and
50
- // no leave — would otherwise leave it armed indefinitely and publish the next
51
- // FORWARD navigation as "back".
52
- //
53
- // ⚠ A clock has no correct value to be set to. The leave phase is separated
54
- // from its popstate by every deactivation guard, and a guard may await
55
- // anything; the plugin also DEFERS a popstate that arrives during an
56
- // in-flight transition and replays it from that transition's `finally`. The
57
- // gap has no upper bound. Measured on the obvious choice: a task-boundary
58
- // expiry disarms a live navigation on ONE async `canDeactivate`.
59
- const onPopstate = () => {
60
- popstateFlag = true;
61
- // A deferred event belongs to the replay, not to the transition running
62
- // now, so that transition's terminal event must not spend it.
63
- armedMidTransition = transitionInFlight;
64
- };
65
- // IMPORTANT — listener-ordering: `popstate` fires on `window`, which
66
- // has no DOM descendants, so capture phase is moot. Listeners are
67
- // dispatched in registration order. To beat the browser-plugin's own
68
- // popstate handler, this tracker must be installed **before**
69
- // `router.usePlugin(browserPluginFactory())` in user code. Otherwise
70
- // the plugin's handler runs first and synchronously fires
71
- // `subscribeLeave` while `popstateFlag` is still `false`.
72
- globalThis.addEventListener("popstate", onPopstate);
73
- const api = getPluginApi(router);
74
- const onSettled = () => {
75
- transitionInFlight = false;
76
- if (armedMidTransition) {
77
- armedMidTransition = false;
78
- return;
79
- }
80
- popstateFlag = false;
81
- };
82
- const unsubs = [
83
- api.addEventListener(events.TRANSITION_START, () => {
84
- transitionInFlight = true;
85
- }),
86
- api.addEventListener(events.TRANSITION_SUCCESS, onSettled),
87
- api.addEventListener(events.TRANSITION_ERROR, onSettled),
88
- api.addEventListener(events.TRANSITION_CANCEL, onSettled),
89
- router.subscribeLeave(() => {
90
- document.documentElement.dataset.navDirection = popstateFlag
91
- ? "back"
92
- : "forward";
93
- popstateFlag = false;
94
- armedMidTransition = false;
95
- }),
96
- ];
97
- return {
98
- destroy: () => {
99
- for (const unsub of unsubs) {
100
- unsub();
101
- }
102
- globalThis.removeEventListener("popstate", onPopstate);
103
- delete document.documentElement.dataset.navDirection;
104
- },
105
- };
12
+ if (typeof document === "undefined") return NOOP_INSTANCE$4;
13
+ let popstateFlag = false;
14
+ document.documentElement.dataset.navDirection = "forward";
15
+ let transitionInFlight = false;
16
+ let armedMidTransition = false;
17
+ const onPopstate = () => {
18
+ popstateFlag = true;
19
+ armedMidTransition = transitionInFlight;
20
+ };
21
+ globalThis.addEventListener("popstate", onPopstate);
22
+ const api = getPluginApi(router);
23
+ const onSettled = () => {
24
+ transitionInFlight = false;
25
+ if (armedMidTransition) {
26
+ armedMidTransition = false;
27
+ return;
28
+ }
29
+ popstateFlag = false;
30
+ };
31
+ const unsubs = [
32
+ api.addEventListener(events.TRANSITION_START, () => {
33
+ transitionInFlight = true;
34
+ }),
35
+ api.addEventListener(events.TRANSITION_SUCCESS, onSettled),
36
+ api.addEventListener(events.TRANSITION_ERROR, onSettled),
37
+ api.addEventListener(events.TRANSITION_CANCEL, onSettled),
38
+ router.subscribeLeave(() => {
39
+ document.documentElement.dataset.navDirection = popstateFlag ? "back" : "forward";
40
+ popstateFlag = false;
41
+ armedMidTransition = false;
42
+ })
43
+ ];
44
+ return { destroy: () => {
45
+ for (const unsub of unsubs) unsub();
46
+ globalThis.removeEventListener("popstate", onPopstate);
47
+ delete document.documentElement.dataset.navDirection;
48
+ } };
106
49
  }
107
-
108
- const CLEAR_DELAY = 7000;
50
+ const CLEAR_DELAY = 7e3;
109
51
  const SAFARI_READY_DELAY = 100;
110
52
  const ANNOUNCER_ATTR = "data-real-router-announcer";
111
53
  const INTERNAL_ROUTE_PREFIX = "@@";
112
54
  const VISUALLY_HIDDEN = "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";
113
- const NOOP_INSTANCE$3 = Object.freeze({
114
- destroy: () => {
115
- /* no-op */
116
- },
117
- });
118
- // Live (non-NOOP) instances sharing the single `[data-real-router-announcer]`
119
- // aria-live element. The element is created once by the first instance
120
- // (`getOrCreateAnnouncer`) and reused by the rest; it must be removed only when
121
- // the LAST holder is destroyed. Without this count the first provider's
122
- // destroy() would detach the shared node while sibling providers (micro-
123
- // frontends — the same multi-provider scenario `scroll-restore`'s `storageKey`
124
- // exists for) keep writing to the now-orphaned node → silent screen reader (#783).
125
- // ⚑ The ref-count and the generation live ON THE ELEMENT (#1924). The element
126
- // is found with `document.querySelector`, so it is document-scoped, while a
127
- // module variable is bundle-scoped — and a page carrying a second adapter
128
- // bundle, the micro-frontend case the ref-count exists for, shares the element
129
- // and not the scope.
130
- //
131
- // ⚠ Module-scoped counters reach #783 verbatim through that seam: the second
132
- // bundle takes the `existing` branch, reads its own generation, passes the
133
- // #1217 ownership guard, decrements its own count to zero and removes the live
134
- // element.
55
+ const NOOP_INSTANCE$3 = Object.freeze({ destroy: () => {} });
135
56
  const REFS_ATTR = "data-rr-announcer-refs";
136
57
  const GENERATION_ATTR = "data-rr-announcer-generation";
137
58
  function readCount(element) {
138
- // `Number(null)` is 0, so an absent attribute needs no fallback term.
139
- return Number(element.getAttribute(REFS_ATTR));
59
+ return Number(element.getAttribute(REFS_ATTR));
140
60
  }
141
61
  function writeCount(element, value) {
142
- element.setAttribute(REFS_ATTR, String(value));
62
+ element.setAttribute(REFS_ATTR, String(value));
143
63
  }
144
- // Generation token (#1217): bumped each time a FRESH shared element is created.
145
- // Each instance captures the generation live at construction; on destroy it
146
- // touches the shared refcount / element ONLY if its generation is still current.
147
- // A stale instance — whose element a host wiped without calling destroy() — must
148
- // not decrement the new generation's refcount (→ negative) or remove its live
149
- // element (a selector-based removeAnnouncer takes whoever is in the DOM).
150
64
  function createRouteAnnouncer(router, options) {
151
- // Defensive SSR / non-browser guard: in SSR (Node.js) or non-DOM
152
- // environments, `document` is undefined and the announcer cannot
153
- // attach its aria-live region. Return a frozen NOOP_INSTANCE — same
154
- // pattern as `createDirectionTracker`, `createScrollRestoration`, and
155
- // `createViewTransitions`. Without this guard, `NavigationAnnouncer`
156
- // component construction would throw `ReferenceError: document is not
157
- // defined` under `@angular/ssr` rendering, tearing down the whole SSR
158
- // bootstrap. Closes review-2026-05-10 §5.10 ⛔ "NavigationAnnouncer
159
- // SSR mode" MED.
160
- if (typeof document === "undefined") {
161
- return NOOP_INSTANCE$3;
162
- }
163
- const prefix = options?.prefix ?? "Navigated to ";
164
- const getCustomText = options?.getAnnouncementText;
165
- let isInitialNavigation = true;
166
- let isReady = false;
167
- let isDestroyed = false;
168
- let lastAnnouncedText = "";
169
- let pendingText = null;
170
- let clearTimeoutId;
171
- const { element: announcer, generation: myGeneration } = getOrCreateAnnouncer();
172
- writeCount(announcer, readCount(announcer) + 1);
173
- const doAnnounce = (text, h1) => {
174
- lastAnnouncedText = text;
175
- clearTimeout(clearTimeoutId);
176
- announcer.textContent = text;
177
- clearTimeoutId = setTimeout(() => {
178
- announcer.textContent = "";
179
- lastAnnouncedText = "";
180
- }, CLEAR_DELAY);
181
- manageFocus(h1);
182
- };
183
- // Safari-ready delay: announcing before VoiceOver wires up the aria-live region
184
- // causes the first announcement to be silently dropped. Wait SAFARI_READY_DELAY ms
185
- // before marking the announcer "ready" — any navigation during that window is
186
- // buffered in pendingText and flushed once the delay expires.
187
- const safariTimeoutId = setTimeout(() => {
188
- isReady = true;
189
- if (pendingText !== null && !isDestroyed) {
190
- const text = pendingText;
191
- pendingText = null;
192
- doAnnounce(text, document.querySelector("h1"));
193
- }
194
- }, SAFARI_READY_DELAY);
195
- const unsubscribe = router.subscribe(({ route }) => {
196
- if (isInitialNavigation) {
197
- isInitialNavigation = false;
198
- return;
199
- }
200
- // Double rAF: waits for two paint frames so the incoming route's DOM
201
- // (including the new <h1>) is fully rendered before resolveText reads it.
202
- // Single rAF fires before the new route's template has been attached,
203
- // which would cause resolveText to pick up the OLD h1 or fall back to
204
- // document.title / route.name prematurely.
205
- requestAnimationFrame(() => {
206
- requestAnimationFrame(() => {
207
- if (isDestroyed) {
208
- return;
209
- }
210
- const h1 = document.querySelector("h1");
211
- const text = resolveText(route, prefix, getCustomText, h1);
212
- if (!text || text === lastAnnouncedText) {
213
- return;
214
- }
215
- if (!isReady) {
216
- // Defer announcement until Safari-ready window elapses (see safariTimeoutId).
217
- pendingText = text;
218
- return;
219
- }
220
- doAnnounce(text, h1);
221
- });
222
- });
223
- });
224
- return {
225
- destroy() {
226
- // Idempotency guard — required so the ref-count is decremented EXACTLY
227
- // once per instance. A double destroy() must not drop the count below the
228
- // number of live holders (which would detach a sibling's element, or
229
- // leave it attached forever).
230
- if (isDestroyed) {
231
- return;
232
- }
233
- isDestroyed = true;
234
- unsubscribe();
235
- clearTimeout(clearTimeoutId);
236
- clearTimeout(safariTimeoutId);
237
- // Ownership guard (#1217): if a host wiped the shared element out from
238
- // under us, the next getOrCreateAnnouncer bumped the generation for the
239
- // fresh element. A stale instance must NOT decrement the new generation's
240
- // refcount (→ negative) or remove its live element — bail if not current.
241
- // ⚠ Against the DOCUMENT's generation, never the captured element's: the
242
- // element a stale instance holds was removed, and its own attribute
243
- // still reads its own generation, so comparing the two can only ever be
244
- // equal and the guard would be dead.
245
- if (myGeneration !== currentGeneration()) {
246
- return;
247
- }
248
- const remaining = readCount(announcer) - 1;
249
- writeCount(announcer, remaining);
250
- // Only the last holder tears down the shared element — via our captured
251
- // ref, not a selector query (which would delete whoever's element is
252
- // currently in the DOM, i.e. a newer generation's).
253
- if (remaining === 0) {
254
- removeAnnouncer(announcer);
255
- }
256
- },
257
- };
65
+ if (typeof document === "undefined") return NOOP_INSTANCE$3;
66
+ const prefix = options?.prefix ?? "Navigated to ";
67
+ const getCustomText = options?.getAnnouncementText;
68
+ let isInitialNavigation = true;
69
+ let isReady = false;
70
+ let isDestroyed = false;
71
+ let lastAnnouncedText = "";
72
+ let pendingText = null;
73
+ let clearTimeoutId;
74
+ const { element: announcer, generation: myGeneration } = getOrCreateAnnouncer();
75
+ writeCount(announcer, readCount(announcer) + 1);
76
+ const doAnnounce = (text, h1) => {
77
+ lastAnnouncedText = text;
78
+ clearTimeout(clearTimeoutId);
79
+ announcer.textContent = text;
80
+ clearTimeoutId = setTimeout(() => {
81
+ announcer.textContent = "";
82
+ lastAnnouncedText = "";
83
+ }, CLEAR_DELAY);
84
+ manageFocus(h1);
85
+ };
86
+ const safariTimeoutId = setTimeout(() => {
87
+ isReady = true;
88
+ if (pendingText !== null && !isDestroyed) {
89
+ const text = pendingText;
90
+ pendingText = null;
91
+ doAnnounce(text, document.querySelector("h1"));
92
+ }
93
+ }, SAFARI_READY_DELAY);
94
+ const unsubscribe = router.subscribe(({ route }) => {
95
+ if (isInitialNavigation) {
96
+ isInitialNavigation = false;
97
+ return;
98
+ }
99
+ requestAnimationFrame(() => {
100
+ requestAnimationFrame(() => {
101
+ if (isDestroyed) return;
102
+ const h1 = document.querySelector("h1");
103
+ const text = resolveText(route, prefix, getCustomText, h1);
104
+ if (!text || text === lastAnnouncedText) return;
105
+ if (!isReady) {
106
+ pendingText = text;
107
+ return;
108
+ }
109
+ doAnnounce(text, h1);
110
+ });
111
+ });
112
+ });
113
+ return { destroy() {
114
+ if (isDestroyed) return;
115
+ isDestroyed = true;
116
+ unsubscribe();
117
+ clearTimeout(clearTimeoutId);
118
+ clearTimeout(safariTimeoutId);
119
+ if (myGeneration !== currentGeneration()) return;
120
+ const remaining = readCount(announcer) - 1;
121
+ writeCount(announcer, remaining);
122
+ if (remaining === 0) removeAnnouncer(announcer);
123
+ } };
258
124
  }
259
- /**
260
- * The next generation, derived from the document rather than a module counter:
261
- * a wiped element leaves no node to read, so the value is kept on `<html>`.
262
- */
263
125
  function currentGeneration() {
264
- return Number(document.documentElement.getAttribute(GENERATION_ATTR));
126
+ return Number(document.documentElement.getAttribute(GENERATION_ATTR));
265
127
  }
266
128
  function nextGeneration() {
267
- const root = document.documentElement;
268
- const next = currentGeneration() + 1;
269
- root.setAttribute(GENERATION_ATTR, String(next));
270
- return next;
129
+ const root = document.documentElement;
130
+ const next = currentGeneration() + 1;
131
+ root.setAttribute(GENERATION_ATTR, String(next));
132
+ return next;
271
133
  }
272
134
  function getOrCreateAnnouncer() {
273
- const existing = document.querySelector(`[${ANNOUNCER_ATTR}]`);
274
- if (existing) {
275
- return {
276
- element: existing,
277
- generation: Number(existing.getAttribute(GENERATION_ATTR)),
278
- };
279
- }
280
- // Creating a FRESH element means no live instance is validly sharing one, so
281
- // the ref-count restarts from zero (the caller increments immediately after).
282
- // Without this, an element removed out from under live instances — a host
283
- // wiping the subtree, or a consumer test whose teardown clears the DOM
284
- // without calling every instance's destroy() — would leave a stale positive
285
- // count that prevents the new element from ever being torn down (#783).
286
- // The generation bump (#1217) lets the wiped element's instances recognize
287
- // themselves as stale so their destroy() does not touch this fresh element.
288
- const element = document.createElement("div");
289
- element.setAttribute("style", VISUALLY_HIDDEN);
290
- element.setAttribute("aria-live", "assertive");
291
- element.setAttribute("aria-atomic", "true");
292
- element.setAttribute(ANNOUNCER_ATTR, "");
293
- // A fresh element restarts the count at zero (the caller increments straight
294
- // after) and takes the next generation, so instances holding the element a
295
- // host wiped recognise themselves as stale. Both live on the node, so every
296
- // bundle reads the same values.
297
- writeCount(element, 0);
298
- element.setAttribute(GENERATION_ATTR, String(nextGeneration()));
299
- // Defensive SSR / pre-`<body>` guard: in some environments (early
300
- // injection, deferred-body documents, certain SSR rehydration paths)
301
- // `document.body` can be null when the announcer is constructed.
302
- // `document.body.prepend(...)` would throw `TypeError: Cannot read
303
- // properties of null`, tearing down the consumer's RouterProvider /
304
- // NavigationAnnouncer mount. Fallback to `documentElement` keeps the
305
- // announcer working for SR users; visual-hidden styling means there is
306
- // no visible artifact regardless of mount point.
307
- //
308
- // TS dom lib types `document.body` as `HTMLElement` (non-null), but
309
- // runtime can return null per spec. The `as` cast narrows the type to
310
- // include null so the `??` short-circuit is type-safe.
311
- (document.body ?? document.documentElement).prepend(element);
312
- return {
313
- element,
314
- generation: Number(element.getAttribute(GENERATION_ATTR)),
315
- };
135
+ const existing = document.querySelector(`[${ANNOUNCER_ATTR}]`);
136
+ if (existing) return {
137
+ element: existing,
138
+ generation: Number(existing.getAttribute(GENERATION_ATTR))
139
+ };
140
+ const element = document.createElement("div");
141
+ element.setAttribute("style", VISUALLY_HIDDEN);
142
+ element.setAttribute("aria-live", "assertive");
143
+ element.setAttribute("aria-atomic", "true");
144
+ element.setAttribute(ANNOUNCER_ATTR, "");
145
+ writeCount(element, 0);
146
+ element.setAttribute(GENERATION_ATTR, String(nextGeneration()));
147
+ (document.body ?? document.documentElement).prepend(element);
148
+ return {
149
+ element,
150
+ generation: Number(element.getAttribute(GENERATION_ATTR))
151
+ };
316
152
  }
317
153
  function removeAnnouncer(element) {
318
- element.remove();
154
+ element.remove();
319
155
  }
320
156
  function resolveText(route, prefix, getCustomText, h1) {
321
- if (getCustomText) {
322
- try {
323
- const customText = getCustomText(route);
324
- // Mini-sprint E.4 (audit-5 §4.2 #4) — empty-string fallback.
325
- // A consumer pattern like
326
- // getAnnouncementText: (route) => myMap[route.name] ?? ""
327
- // returns `""` for routes outside the map. The subscribe loop
328
- // then sees an empty text and silently no-announces — screen
329
- // readers stay quiet without any signal to the developer. Treat
330
- // a falsy custom result (`""` / `null` / `undefined`) as
331
- // "consumer doesn't have a name for this route" and fall through
332
- // to the default resolution chain (h1 → title → route name).
333
- if (customText) {
334
- return customText;
335
- }
336
- }
337
- catch (error) {
338
- // A throwing consumer callback inside the router's subscribe loop
339
- // would tear down sibling listeners — log and fall through to the
340
- // built-in resolution chain so the announcer keeps working.
341
- console.error("[real-router] getAnnouncementText threw; falling back to default resolution.", error);
342
- }
343
- }
344
- const h1Text = (h1?.textContent ?? "").trim();
345
- const routeName = route.name.startsWith(INTERNAL_ROUTE_PREFIX)
346
- ? ""
347
- : route.name;
348
- const rawText = h1Text || document.title || routeName || globalThis.location.pathname;
349
- return `${prefix}${rawText}`;
157
+ if (getCustomText) try {
158
+ const customText = getCustomText(route);
159
+ if (customText) return customText;
160
+ } catch (error) {
161
+ console.error("[real-router] getAnnouncementText threw; falling back to default resolution.", error);
162
+ }
163
+ const h1Text = (h1?.textContent ?? "").trim();
164
+ const routeName = route.name.startsWith(INTERNAL_ROUTE_PREFIX) ? "" : route.name;
165
+ return `${prefix}${h1Text || document.title || routeName || globalThis.location.pathname}`;
350
166
  }
351
167
  function manageFocus(h1) {
352
- if (!h1) {
353
- return;
354
- }
355
- if (!h1.hasAttribute("tabindex")) {
356
- h1.setAttribute("tabindex", "-1");
357
- }
358
- h1.focus({ preventScroll: true });
168
+ if (!h1) return;
169
+ if (!h1.hasAttribute("tabindex")) h1.setAttribute("tabindex", "-1");
170
+ h1.focus({ preventScroll: true });
359
171
  }
360
-
361
- /** Captured like the deciding seven, but this one BUILDS the guarantee (#2072). */
362
172
  const objectCreate = Object.create;
363
173
  const DEFAULT_STORAGE_KEY = "real-router:scroll";
364
- // Bounded retry budget for resolving a late-mounting scroll container on the
365
- // restore path. A per-route container (e.g. an `overflow:auto` div rendered
366
- // only on one route) can be committed to the DOM a few frames after the
367
- // navigation settles — heavier routes paint later than the subscribe's rAF.
368
- // ~10 frames (≈160ms at 60fps) comfortably covers a React commit of a large
369
- // route without being perceptible. See the doc-block on `restorePos`.
370
174
  const RESTORE_RETRY_FRAMES = 10;
371
- const NOOP_INSTANCE$2 = Object.freeze({
372
- destroy: () => {
373
- /* no-op */
374
- },
375
- });
175
+ const NOOP_INSTANCE$2 = Object.freeze({ destroy: () => {} });
376
176
  function createScrollRestoration(router, options) {
377
- if (typeof globalThis.window === "undefined") {
378
- return NOOP_INSTANCE$2;
379
- }
380
- const mode = options?.mode ?? "restore";
381
- // mode "native" = utility does nothing. Don't flip history.scrollRestoration,
382
- // don't subscribe, don't register pagehide — `history.scrollRestoration`
383
- // stays at the browser default ("auto") so the browser handles scroll
384
- // restore natively. (Note: this is the OPPOSITE of `history.scrollRestoration
385
- // === "manual"` — utility's "native" leaves the DOM property at "auto" so
386
- // the browser is in charge.)
387
- if (mode === "native") {
388
- return NOOP_INSTANCE$2;
389
- }
390
- const anchorEnabled = options?.anchorScrolling ?? true;
391
- const getContainer = options?.scrollContainer;
392
- const behavior = options?.behavior ?? "auto";
393
- const storageKey = options?.storageKey ?? DEFAULT_STORAGE_KEY;
394
- // Write-through in-memory cache: parse sessionStorage once per provider
395
- // mount, then mutate in-memory. Avoids a JSON.parse + JSON.stringify pair
396
- // on every subscribeLeave / pagehide event.
397
- let store;
398
- const loadStore = () => {
399
- if (store !== undefined) {
400
- return store;
401
- }
402
- // ⚑ A PROTOTYPE-LESS record, and here that is the cheap fix rather than the
403
- // expensive one (#1852). The key is `${route}:${json}`, so both the
404
- // skip-same-value READ and the write below consult a chain under a name the
405
- // page never chose; with no chain there is nothing to consult. Core pays for
406
- // the same guarantee with `putField` because its bags are read on every
407
- // render and V8 keeps a prototype-less object in dictionary mode — this one
408
- // is a small per-mount cache read a few times per navigation, so the tax is
409
- // expected to be negligible and no primitive needs importing.
410
- //
411
- // ⚠ "Expected", not measured, and the word is chosen: nothing benches this
412
- // cache. Its sibling in `putField`'s docblock is the reason to be careful —
413
- // "not measurable" there turned out to be a statement about the instrument,
414
- // not the cost. Measure before repeating the word.
415
- //
416
- // ⚠ `JSON.parse` DEFINES, so a stored `"__proto__"` key arrives as ordinary
417
- // data either way; what this closes is the ambient half.
418
- try {
419
- const raw = sessionStorage.getItem(storageKey);
420
- const parsed = raw
421
- ? JSON.parse(raw)
422
- : undefined;
423
- store = Object.assign(objectCreate(null), parsed);
424
- }
425
- catch {
426
- store = objectCreate(null);
427
- }
428
- return store;
429
- };
430
- const putPos = (key, pos) => {
431
- try {
432
- const cached = loadStore();
433
- // Skip-same-value: when a route is left at the same scroll position it
434
- // already holds in the cache (e.g. tab-switching without scrolling),
435
- // both the in-memory write and the JSON.stringify + setItem pair are
436
- // no-ops. Eliminates redundant serialization on the navigation hot
437
- // path for the common "click tabs without scrolling" case.
438
- if (cached[key] === pos) {
439
- return;
440
- }
441
- cached[key] = pos;
442
- sessionStorage.setItem(storageKey, JSON.stringify(cached));
443
- }
444
- catch {
445
- // Ignore quota / security errors.
446
- }
447
- };
448
- const prevScrollRestoration = history.scrollRestoration;
449
- try {
450
- history.scrollRestoration = "manual";
451
- }
452
- catch {
453
- // Ignore — some embedded contexts may reject the assignment.
454
- }
455
- // Resolve the container lazily on every event so containers mounted AFTER
456
- // the provider still get correct scroll handling. Falls back to window when
457
- // the getter is absent or returns null (pre-mount).
458
- const readPos = () => {
459
- const element = getContainer?.();
460
- return element ? element.scrollTop : globalThis.scrollY;
461
- };
462
- const writePos = (top) => {
463
- const element = getContainer?.();
464
- if (element) {
465
- element.scrollTo({ top, left: 0, behavior });
466
- }
467
- else {
468
- globalThis.scrollTo({ top, left: 0, behavior });
469
- }
470
- };
471
- // Restore path (back / traverse / reload). Unlike `writePos`, this tolerates a
472
- // scroll container that both MOUNTS and LAYS OUT a few frames AFTER the
473
- // navigation settles.
474
- //
475
- // The capture-side `readPos` always runs against an already-mounted DOM (the
476
- // route being left). On restore the target route — and its container — is
477
- // still being committed by the view layer. The subscribe callback schedules a
478
- // single rAF; for a heavy route (e.g. a long virtual list) the framework's
479
- // commit can land AFTER that frame. Two distinct failures follow, each losing
480
- // the saved position (Scenario 6 e2e, reproduced under CI's slower runner):
481
- //
482
- // 1. Container not mounted yet → `getContainer()` is `null`, the scroll
483
- // silently falls back to `window`, which on a container-only route has
484
- // nothing to scroll.
485
- // 2. Container mounted but its content not laid out yet → `scrollHeight`
486
- // is still small, so a single `scrollTo({ top })` clamps short of the
487
- // saved position and never re-applies once layout grows.
488
- //
489
- // With no `scrollContainer` getter the target is always `window`, present
490
- // from the first frame — restore in a single shot (unchanged behaviour). When
491
- // a getter is configured we cannot tell "this route legitimately uses window"
492
- // from "the container is still mounting", so re-apply the scroll on every
493
- // frame for a bounded budget: window as a fallback while the container is
494
- // absent (harmless clamp on container routes), the container itself once it
495
- // appears. For instant restores we stop early the moment the position sticks;
496
- // smooth restores animate asynchronously, so they run the full budget. The
497
- // frame budget is the hard backstop against an unreachable target (saved
498
- // position taller than the restored content).
499
- let restoreToken = 0;
500
- const restorePos = (top) => {
501
- if (!getContainer) {
502
- globalThis.scrollTo({ top, left: 0, behavior });
503
- return;
504
- }
505
- let frames = 0;
506
- // ⚑ A per-restore token, the idea `view-transitions.ts` carries as
507
- // `scheduledVT` (#781) and this file already carries as `scrollSettled` on
508
- // the capture side (#782). Without it the budget is gated by `destroyed`
509
- // alone, so a loop whose target is unreachable — a container that clamps
510
- // short and keeps retrying — is still running when the next navigation
511
- // lands, and writes the PREVIOUS route's offset onto the current page the
512
- // moment that container's layout grows (#1924).
513
- const token = (restoreToken += 1);
514
- const attempt = () => {
515
- if (destroyed || token !== restoreToken) {
516
- return;
517
- }
518
- const element = getContainer();
519
- if (element) {
520
- element.scrollTo({ top, left: 0, behavior });
521
- // Instant restore landed within rounding tolerance → done; no point
522
- // re-applying. Smooth restore never matches synchronously, so let it
523
- // ride the budget.
524
- if (behavior !== "smooth" && Math.abs(element.scrollTop - top) <= 1) {
525
- return;
526
- }
527
- }
528
- else {
529
- globalThis.scrollTo({ top, left: 0, behavior });
530
- }
531
- if (frames >= RESTORE_RETRY_FRAMES) {
532
- return;
533
- }
534
- frames += 1;
535
- requestAnimationFrame(attempt);
536
- };
537
- attempt();
538
- };
539
- const scrollToHashOrTop = (route) => {
540
- // URL plugin path (#532): `state.context.url.hash` is the source of truth
541
- // when one of the URL plugins (browser-plugin / navigation-plugin) is
542
- // installed. The value is already DECODED — feeding it through
543
- // `decodeURIComponent` again would throw on a bare `%`.
544
- const ctxHash = route.context
545
- ?.url?.hash;
546
- if (ctxHash !== undefined) {
547
- if (anchorEnabled && ctxHash.length > 0) {
548
- // eslint-disable-next-line unicorn/prefer-query-selector -- ids may contain CSS-unsafe chars
549
- const element = document.getElementById(ctxHash);
550
- if (element) {
551
- element.scrollIntoView({ behavior });
552
- return;
553
- }
554
- }
555
- writePos(0);
556
- return;
557
- }
558
- // Fallback path: no URL plugin, read the DOM. `location.hash` is
559
- // percent-encoded; ids in the DOM are the raw string, so decode for the
560
- // match. Fall back to the raw slice if the hash contains a malformed
561
- // escape sequence (decodeURIComponent throws on those).
562
- const hash = globalThis.location.hash;
563
- if (anchorEnabled && hash.length > 1) {
564
- let id;
565
- try {
566
- id = decodeURIComponent(hash.slice(1));
567
- }
568
- catch {
569
- id = hash.slice(1);
570
- }
571
- // eslint-disable-next-line unicorn/prefer-query-selector -- ids may contain CSS-unsafe chars
572
- const element = document.getElementById(id);
573
- if (element) {
574
- element.scrollIntoView({ behavior });
575
- return;
576
- }
577
- }
578
- writePos(0);
579
- };
580
- let destroyed = false;
581
- // Capture/effect seam guard (#782). previousRoute's position is captured
582
- // synchronously in `subscribe`, but the snap/restore effect runs a frame
583
- // later in rAF. Across that window the viewport still shows the route BEFORE
584
- // previousRoute, so a second navigation landing in the same frame would
585
- // capture that foreign position under previousRoute's key. `scrollSettled` is
586
- // false across the window — capture is skipped (previousRoute's own stored
587
- // value survives the transit). A real user scroll in this <16ms window is
588
- // physically impossible.
589
- let scrollSettled = true;
590
- const unsubscribe = router.subscribe(({ route, previousRoute }) => {
591
- const nav = route.context
592
- .navigation;
593
- // Browsers dispatch reload as the initial navigation after refresh, so
594
- // previousRoute is undefined and capture is naturally skipped. The
595
- // pre-refresh position was already persisted via pagehide. Capture is also
596
- // skipped while the scroll is unsettled — a second navigation in the same
597
- // frame, before the prior nav's rAF snap (see `scrollSettled`, #782).
598
- if (previousRoute && scrollSettled) {
599
- putPos(keyOf(previousRoute), readPos());
600
- }
601
- // This navigation's scroll effect is now pending: the viewport position no
602
- // longer belongs to `route` until the rAF below runs and settles it.
603
- scrollSettled = false;
604
- requestAnimationFrame(() => {
605
- if (destroyed) {
606
- return;
607
- }
608
- // Effect running — the position now belongs to `route`, so the next
609
- // capture is honest again.
610
- scrollSettled = true;
611
- if (mode === "top") {
612
- scrollToHashOrTop(route);
613
- return;
614
- }
615
- // Restore branches (reload, back/traverse) MUST be evaluated before the
616
- // replace-skip below. Since #657 lifted `replace` into TransitionMeta, a
617
- // history TRAVERSAL (back/forward) under navigation-plugin carries
618
- // `transition.replace === true` — a traversal reuses an existing history
619
- // entry, which is replace-shaped at the history level. If the replace-skip
620
- // ran first it would swallow every back/forward navigation and restore
621
- // would never fire (the Scenario 6 e2e regression). Genuine in-place
622
- // replaces (`router.navigate({ replace: true })`, navigateToNotFound) are
623
- // not traversals and fall through to the skip below.
624
- //
625
- // Both arms of each check are required: `transition.reload` only fires for
626
- // programmatic `router.navigate({reload:true})`. F5 under navigation-plugin
627
- // primes `nav.navigationType === "reload"` via #531 getActivationType but
628
- // leaves opts.reload undefined, so dropping the plugin arm would regress F5
629
- // scroll-restore. Browser-plugin's F5 is not covered (no priming, out of
630
- // scope).
631
- // `?.` on a required field: core commits a foreign State's ABSENT
632
- // `transition` rather than fabricating one (#1792 / #1976), and this runs
633
- // on whatever `subscribe` hands over. Absent falls through to the plugin
634
- // arm, which is the pre-#1976 answer for a state carrying no meta.
635
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- the required field is genuinely absent on a foreign committed State
636
- if (route.transition?.reload || nav?.navigationType === "reload") {
637
- restorePos(loadStore()[keyOf(route)] ?? 0);
638
- return;
639
- }
640
- if (nav?.direction === "back" || nav?.navigationType === "traverse") {
641
- restorePos(loadStore()[keyOf(route)] ?? 0);
642
- return;
643
- }
644
- // Genuine in-place replace (not a traversal) — leave scroll untouched.
645
- // `?.` for the same reason as the reload arm above.
646
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- the required field is genuinely absent on a foreign committed State
647
- if (route.transition?.replace || nav?.navigationType === "replace") {
648
- return;
649
- }
650
- scrollToHashOrTop(route);
651
- });
652
- });
653
- const onPageHide = () => {
654
- const current = router.getState();
655
- if (current) {
656
- putPos(keyOf(current), readPos());
657
- }
658
- };
659
- globalThis.addEventListener("pagehide", onPageHide);
660
- return {
661
- destroy: () => {
662
- // No `if (destroyed) return` guard: every teardown below is idempotent —
663
- // `unsubscribe()` is a `set.delete` in the core EventEmitter, DOM
664
- // `removeEventListener` is spec-idempotent, and the history assignment is
665
- // a plain re-set. There is no ref-count to protect (unlike
666
- // route-announcer's shared announcer element), so a double `destroy()` is
667
- // harmless. `destroyed = true` still gates any pending restore rAF / retry.
668
- destroyed = true;
669
- unsubscribe();
670
- globalThis.removeEventListener("pagehide", onPageHide);
671
- try {
672
- history.scrollRestoration = prevScrollRestoration;
673
- }
674
- catch {
675
- // Ignore.
676
- }
677
- },
678
- };
177
+ if (typeof globalThis.window === "undefined") return NOOP_INSTANCE$2;
178
+ const mode = options?.mode ?? "restore";
179
+ if (mode === "native") return NOOP_INSTANCE$2;
180
+ const anchorEnabled = options?.anchorScrolling ?? true;
181
+ const getContainer = options?.scrollContainer;
182
+ const behavior = options?.behavior ?? "auto";
183
+ const storageKey = options?.storageKey ?? DEFAULT_STORAGE_KEY;
184
+ let store;
185
+ const loadStore = () => {
186
+ if (store !== void 0) return store;
187
+ try {
188
+ const raw = sessionStorage.getItem(storageKey);
189
+ const parsed = raw ? JSON.parse(raw) : void 0;
190
+ store = Object.assign(objectCreate(null), parsed);
191
+ } catch {
192
+ store = objectCreate(null);
193
+ }
194
+ return store;
195
+ };
196
+ const putPos = (key, pos) => {
197
+ try {
198
+ const cached = loadStore();
199
+ if (cached[key] === pos) return;
200
+ cached[key] = pos;
201
+ sessionStorage.setItem(storageKey, JSON.stringify(cached));
202
+ } catch {}
203
+ };
204
+ const prevScrollRestoration = history.scrollRestoration;
205
+ try {
206
+ history.scrollRestoration = "manual";
207
+ } catch {}
208
+ const readPos = () => {
209
+ const element = getContainer?.();
210
+ return element ? element.scrollTop : globalThis.scrollY;
211
+ };
212
+ const writePos = (top) => {
213
+ const element = getContainer?.();
214
+ if (element) element.scrollTo({
215
+ top,
216
+ left: 0,
217
+ behavior
218
+ });
219
+ else globalThis.scrollTo({
220
+ top,
221
+ left: 0,
222
+ behavior
223
+ });
224
+ };
225
+ let restoreToken = 0;
226
+ const restorePos = (top) => {
227
+ if (!getContainer) {
228
+ globalThis.scrollTo({
229
+ top,
230
+ left: 0,
231
+ behavior
232
+ });
233
+ return;
234
+ }
235
+ let frames = 0;
236
+ const token = restoreToken += 1;
237
+ const attempt = () => {
238
+ if (destroyed || token !== restoreToken) return;
239
+ const element = getContainer();
240
+ if (element) {
241
+ element.scrollTo({
242
+ top,
243
+ left: 0,
244
+ behavior
245
+ });
246
+ if (behavior !== "smooth" && Math.abs(element.scrollTop - top) <= 1) return;
247
+ } else globalThis.scrollTo({
248
+ top,
249
+ left: 0,
250
+ behavior
251
+ });
252
+ if (frames >= RESTORE_RETRY_FRAMES) return;
253
+ frames += 1;
254
+ requestAnimationFrame(attempt);
255
+ };
256
+ attempt();
257
+ };
258
+ const scrollToHashOrTop = (route) => {
259
+ const ctxHash = route.context?.url?.hash;
260
+ if (ctxHash !== void 0) {
261
+ if (anchorEnabled && ctxHash.length > 0) {
262
+ const element = document.getElementById(ctxHash);
263
+ if (element) {
264
+ element.scrollIntoView({ behavior });
265
+ return;
266
+ }
267
+ }
268
+ writePos(0);
269
+ return;
270
+ }
271
+ const hash = globalThis.location.hash;
272
+ if (anchorEnabled && hash.length > 1) {
273
+ let id;
274
+ try {
275
+ id = decodeURIComponent(hash.slice(1));
276
+ } catch {
277
+ id = hash.slice(1);
278
+ }
279
+ const element = document.getElementById(id);
280
+ if (element) {
281
+ element.scrollIntoView({ behavior });
282
+ return;
283
+ }
284
+ }
285
+ writePos(0);
286
+ };
287
+ let destroyed = false;
288
+ let scrollSettled = true;
289
+ const unsubscribe = router.subscribe(({ route, previousRoute }) => {
290
+ const nav = route.context.navigation;
291
+ if (previousRoute && scrollSettled) putPos(keyOf(previousRoute), readPos());
292
+ scrollSettled = false;
293
+ requestAnimationFrame(() => {
294
+ if (destroyed) return;
295
+ scrollSettled = true;
296
+ if (mode === "top") {
297
+ scrollToHashOrTop(route);
298
+ return;
299
+ }
300
+ if (route.transition?.reload || nav?.navigationType === "reload") {
301
+ restorePos(loadStore()[keyOf(route)] ?? 0);
302
+ return;
303
+ }
304
+ if (nav?.direction === "back" || nav?.navigationType === "traverse") {
305
+ restorePos(loadStore()[keyOf(route)] ?? 0);
306
+ return;
307
+ }
308
+ if (route.transition?.replace || nav?.navigationType === "replace") return;
309
+ scrollToHashOrTop(route);
310
+ });
311
+ });
312
+ const onPageHide = () => {
313
+ const current = router.getState();
314
+ if (current) putPos(keyOf(current), readPos());
315
+ };
316
+ globalThis.addEventListener("pagehide", onPageHide);
317
+ return { destroy: () => {
318
+ destroyed = true;
319
+ unsubscribe();
320
+ globalThis.removeEventListener("pagehide", onPageHide);
321
+ try {
322
+ history.scrollRestoration = prevScrollRestoration;
323
+ } catch {}
324
+ } };
679
325
  }
680
- /**
681
- * Internal cache-key builder for scroll-position storage.
682
- *
683
- * **Exported for testing only — not part of the public API** (intentionally
684
- * excluded from `index.ts` barrel). Adapter property tests import it rather
685
- * than replicating it (§8b H20 / audit-2026-05-16 #S3): a replica drifts
686
- * silently the moment the key changes. A change to the key format loses saved
687
- * positions across an upgrade, so the test set is the contract.
688
- *
689
- * ## Not memoized
690
- *
691
- * The key is a string property read, which is cheaper than the `WeakMap`
692
- * lookup any cache would need — so there is nothing here to cache.
693
- */
694
326
  function keyOf(state) {
695
- // The key is the LOCATION, and `state.path` is the form core prints it in
696
- // (#1923). Deriving it from the bags instead makes this a SECOND place that
697
- // has to know how a value prints — and the two domains disagree there: the
698
- // URL direction parses `?page=2` into the number `2`, an intent keeps `"2"`,
699
- // and `packages/core/src/helpers.ts` says comparison is the single place that
700
- // knows they describe one location. Reading the printed form asks core rather
701
- // than re-deriving it, so a route's query, its `?id` carve-out twin and the
702
- // order its params were written in are all already settled here.
703
- return state.path;
327
+ return state.path;
704
328
  }
705
-
706
- const NOOP_INSTANCE$1 = Object.freeze({
707
- destroy: () => {
708
- /* no-op */
709
- },
710
- });
711
- // Hardcoded internals (RFC §5.1 — promote only with evidence).
329
+ const NOOP_INSTANCE$1 = Object.freeze({ destroy: () => {} });
712
330
  const RAF_DEBOUNCE_MS = 150;
713
331
  const MUTATION_DEBOUNCE_MS = 250;
714
332
  const COOLDOWN_TIMEOUT_MS = 500;
715
333
  const DEFAULT_ROOT_MARGIN = "-20% 0px -60% 0px";
716
334
  const getUrlContext = (state) => state.context?.url;
717
- // =============================================================================
718
- // Picker — pure, no state. RFC §5.2 selection rule.
719
- // =============================================================================
720
- // Pick the anchor closest to the active zone top in viewport coordinates.
721
- // `entry.rootBounds.top` already reflects `rootMargin` (per W3C IO spec
722
- // §3.3) — for `rootMargin: "-20% 0px -60% 0px"` it returns 20% of root
723
- // height, for `"-50% 0px -50% 0px"` it returns the center, etc. Distance
724
- // = boundingClientRect.top − zoneTop in viewport pixels: positive = anchor
725
- // below zone top (just entered), negative = anchor above zone top (body
726
- // crossing zone from above). We prefer smallest non-negative; fall back to
727
- // least-negative when no entry has crossed yet.
728
- // Falls back to zoneTop = 0 when rootBounds is null (cross-origin roots,
729
- // unit tests). Single pass — handles `Iterable` so flushes can pass
730
- // `Map.values()` directly without realising the array.
731
335
  const pickTopmost = (entries) => {
732
- let bestPositive = null;
733
- let bestPositiveDist = Number.POSITIVE_INFINITY;
734
- let bestNegative = null;
735
- let bestNegativeDist = Number.NEGATIVE_INFINITY;
736
- for (const entry of entries) {
737
- if (!entry.isIntersecting) {
738
- continue;
739
- }
740
- const zoneTop = entry.rootBounds?.top ?? 0;
741
- const distance = entry.boundingClientRect.top - zoneTop;
742
- if (distance >= 0) {
743
- if (distance < bestPositiveDist) {
744
- bestPositive = entry;
745
- bestPositiveDist = distance;
746
- }
747
- }
748
- else if (distance > bestNegativeDist) {
749
- bestNegative = entry;
750
- bestNegativeDist = distance;
751
- }
752
- }
753
- return bestPositive ?? bestNegative;
336
+ let bestPositive = null;
337
+ let bestPositiveDist = Number.POSITIVE_INFINITY;
338
+ let bestNegative = null;
339
+ let bestNegativeDist = Number.NEGATIVE_INFINITY;
340
+ for (const entry of entries) {
341
+ if (!entry.isIntersecting) continue;
342
+ const zoneTop = entry.rootBounds?.top ?? 0;
343
+ const distance = entry.boundingClientRect.top - zoneTop;
344
+ if (distance >= 0) {
345
+ if (distance < bestPositiveDist) {
346
+ bestPositive = entry;
347
+ bestPositiveDist = distance;
348
+ }
349
+ } else if (distance > bestNegativeDist) {
350
+ bestNegative = entry;
351
+ bestNegativeDist = distance;
352
+ }
353
+ }
354
+ return bestPositive ?? bestNegative;
754
355
  };
755
356
  const createUrlPluginDetector = (router, onMissing) => {
756
- let detectionUnsub = null;
757
- const verify = (state) => {
758
- const context = state.context;
759
- if (context && context.url === undefined) {
760
- console.warn("[real-router] scroll-spy: state.context.url is not claimed. " +
761
- "Spy requires browser-plugin or navigation-plugin. Disabling.");
762
- onMissing();
763
- }
764
- };
765
- const peekState = router.getState();
766
- if (peekState) {
767
- verify(peekState);
768
- }
769
- else {
770
- // Re-entry guard: `router.subscribe` MAY invoke the callback synchronously
771
- // from inside `.subscribe(...)` before the function returns. In that case
772
- // `detectionUnsub` is still `null` when the callback fires. Without this
773
- // boolean, a hypothetical multi-fire would double-warn.
774
- let detectionConsumed = false;
775
- detectionUnsub = router.subscribe(({ route }) => {
776
- /* 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 */
777
- if (detectionConsumed) {
778
- return;
779
- }
780
- detectionConsumed = true;
781
- verify(route);
782
- detectionUnsub?.();
783
- detectionUnsub = null;
784
- });
785
- }
786
- return {
787
- destroy() {
788
- detectionUnsub?.();
789
- detectionUnsub = null;
790
- },
791
- };
357
+ let detectionUnsub = null;
358
+ const verify = (state) => {
359
+ const context = state.context;
360
+ if (context && context.url === void 0) {
361
+ console.warn("[real-router] scroll-spy: state.context.url is not claimed. Spy requires browser-plugin or navigation-plugin. Disabling.");
362
+ onMissing();
363
+ }
364
+ };
365
+ const peekState = router.getState();
366
+ if (peekState) verify(peekState);
367
+ else {
368
+ let detectionConsumed = false;
369
+ detectionUnsub = router.subscribe(({ route }) => {
370
+ /* 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 */
371
+ if (detectionConsumed) return;
372
+ detectionConsumed = true;
373
+ verify(route);
374
+ detectionUnsub?.();
375
+ detectionUnsub = null;
376
+ });
377
+ }
378
+ return { destroy() {
379
+ detectionUnsub?.();
380
+ detectionUnsub = null;
381
+ } };
792
382
  };
793
383
  const createCooldown = (getContainer) => {
794
- let active = false;
795
- let timeout = null;
796
- let listenerContainer = null;
797
- let listener = null;
798
- const clear = () => {
799
- if (timeout !== null) {
800
- clearTimeout(timeout);
801
- timeout = null;
802
- }
803
- if (listener) {
804
- const target = listenerContainer ?? globalThis;
805
- target.removeEventListener("scrollend", listener);
806
- }
807
- listener = null;
808
- listenerContainer = null;
809
- active = false;
810
- };
811
- return {
812
- get active() {
813
- return active;
814
- },
815
- start() {
816
- // Reset rather than stack timers if cooldown is already active.
817
- clear();
818
- active = true;
819
- const lift = () => {
820
- clear();
821
- };
822
- listener = lift;
823
- listenerContainer = getContainer();
824
- const target = listenerContainer ?? globalThis;
825
- target.addEventListener("scrollend", lift, { once: true });
826
- timeout = setTimeout(lift, COOLDOWN_TIMEOUT_MS);
827
- },
828
- destroy() {
829
- clear();
830
- },
831
- };
384
+ let active = false;
385
+ let timeout = null;
386
+ let listenerContainer = null;
387
+ let listener = null;
388
+ const clear = () => {
389
+ if (timeout !== null) {
390
+ clearTimeout(timeout);
391
+ timeout = null;
392
+ }
393
+ if (listener) (listenerContainer ?? globalThis).removeEventListener("scrollend", listener);
394
+ listener = null;
395
+ listenerContainer = null;
396
+ active = false;
397
+ };
398
+ return {
399
+ get active() {
400
+ return active;
401
+ },
402
+ start() {
403
+ clear();
404
+ active = true;
405
+ const lift = () => {
406
+ clear();
407
+ };
408
+ listener = lift;
409
+ listenerContainer = getContainer();
410
+ (listenerContainer ?? globalThis).addEventListener("scrollend", lift, { once: true });
411
+ timeout = setTimeout(lift, COOLDOWN_TIMEOUT_MS);
412
+ },
413
+ destroy() {
414
+ clear();
415
+ }
416
+ };
832
417
  };
833
418
  const createDebouncer = (callback, trailingMs) => {
834
- let raf = null;
835
- let timeout = null;
836
- return {
837
- schedule() {
838
- if (raf !== null) {
839
- return;
840
- }
841
- raf = requestAnimationFrame(() => {
842
- raf = null;
843
- if (timeout !== null) {
844
- clearTimeout(timeout);
845
- }
846
- timeout = setTimeout(() => {
847
- timeout = null;
848
- callback();
849
- }, trailingMs);
850
- });
851
- },
852
- destroy() {
853
- if (raf !== null) {
854
- cancelAnimationFrame(raf);
855
- raf = null;
856
- }
857
- if (timeout !== null) {
858
- clearTimeout(timeout);
859
- timeout = null;
860
- }
861
- },
862
- };
419
+ let raf = null;
420
+ let timeout = null;
421
+ return {
422
+ schedule() {
423
+ if (raf !== null) return;
424
+ raf = requestAnimationFrame(() => {
425
+ raf = null;
426
+ if (timeout !== null) clearTimeout(timeout);
427
+ timeout = setTimeout(() => {
428
+ timeout = null;
429
+ callback();
430
+ }, trailingMs);
431
+ });
432
+ },
433
+ destroy() {
434
+ if (raf !== null) {
435
+ cancelAnimationFrame(raf);
436
+ raf = null;
437
+ }
438
+ if (timeout !== null) {
439
+ clearTimeout(timeout);
440
+ timeout = null;
441
+ }
442
+ }
443
+ };
863
444
  };
864
445
  const createObserverPair = (selector, rootMargin, getContainer, onIntersection, onInvalidSelector, isStopped) => {
865
- const observed = new Set();
866
- // Latest IO entry per target — accumulated across batches. IO delivers
867
- // entries only for targets whose intersection state CHANGED (W3C IO
868
- // §3.2.1), so a fast scroll that lands two callbacks inside the same
869
- // debounce window must merge by target, not overwrite. Entries are
870
- // dropped from the map when their target leaves the DOM (see `reconcile`)
871
- // and on `destroy()`.
872
- const pending = new Map();
873
- let duplicateIdWarned = false;
874
- let mutationTimer = null;
875
- const handleIntersection = (entries) => {
876
- // Defensive: IO callback may fire AFTER `destroy()` if a queued event
877
- // was already scheduled by the browser before `disconnect()`. Cheap
878
- // belt-and-suspenders.
879
- if (isStopped()) {
880
- return;
881
- }
882
- for (const entry of entries) {
883
- pending.set(entry.target, entry);
884
- }
885
- onIntersection();
886
- };
887
- // Build (and rebuild) the IntersectionObserver for a given root. A root is
888
- // immutable once its IO is constructed, so `reconcile` recreates the IO via
889
- // this same factory when the resolved container changes (#780) — one
890
- // definition, two call sites.
891
- const makeIo = (container) => new IntersectionObserver(handleIntersection, {
892
- root: container,
893
- rootMargin,
894
- threshold: 0,
895
- });
896
- // Container the IntersectionObserver root + MutationObserver target are
897
- // built with. Both are immutable once the observer is constructed (W3C), so
898
- // a `scrollContainer` that resolves to a different element after creation —
899
- // most importantly one that MOUNTS after the spy starts (Angular wires the
900
- // spy at bootstrap, before any component renders; a docs route's container
901
- // mounts on navigation) — is only honoured by rebuilding the pair in
902
- // `reconcile`. Tracked here so `reconcile` can compare on every run (#780).
903
- let observerContainer = getContainer();
904
- let io = makeIo(observerContainer);
905
- const observeMatches = () => {
906
- const scope = getContainer() ?? document;
907
- let candidates;
908
- try {
909
- candidates = scope.querySelectorAll(selector);
910
- }
911
- catch {
912
- onInvalidSelector();
913
- return;
914
- }
915
- const seenIds = new Set();
916
- for (const element of candidates) {
917
- // Detect duplicate ids once (RFC §7.7). The DOM permits duplicate ids
918
- // even though it is a markup bug; the spy keeps working but picks the
919
- // first one deterministically via the topmost-visible rule.
920
- const id = element.id;
921
- if (id && !duplicateIdWarned) {
922
- if (seenIds.has(id)) {
923
- duplicateIdWarned = true;
924
- console.warn(`[real-router] scroll-spy: duplicate id "${id}" observed. ` +
925
- "Selection picks the topmost visible match deterministically.");
926
- }
927
- seenIds.add(id);
928
- }
929
- if (observed.has(element)) {
930
- continue;
931
- }
932
- io.observe(element);
933
- observed.add(element);
934
- }
935
- };
936
- // MutationObserver init — reused when the observer is re-pointed at a new
937
- // container in `reconcile`. `childList: true, subtree: true` catches
938
- // structural changes; `attributes: true, attributeFilter: ["id"]` catches
939
- // anchor id renames (typical for client-rendered docs). The MO targets the
940
- // scroll container (or document.body for the window viewport).
941
- const MUTATION_OBSERVE_INIT = {
942
- childList: true,
943
- subtree: true,
944
- attributes: true,
945
- attributeFilter: ["id"],
946
- };
947
- // Null-then-assigned — the same forward-reference idiom as `flush` in the
948
- // main scope. `reconcile` re-points it on a container change, so it must be
949
- // in scope above its assignment; it is non-null by the time any async
950
- // mutation callback (or `reconcile`) runs.
951
- let mo = null;
952
- const reconcile = () => {
953
- // Drop observed elements that left the DOM. Avoids observer holding
954
- // strong refs to detached nodes. Also drop their accumulated entry so
955
- // stale "was intersecting" state for a removed node cannot be picked
956
- // by `pickTopmost` after the node is gone.
957
- for (const element of observed) {
958
- if (element.isConnected) {
959
- continue;
960
- }
961
- io.unobserve(element);
962
- observed.delete(element);
963
- pending.delete(element);
964
- }
965
- // Honour a container that mounted (or changed) after construction (#780).
966
- // The IntersectionObserver root and MutationObserver target cannot be
967
- // mutated in place, so rebuild the pair under the new container. Clearing
968
- // `observed` + `pending` makes the rebuild equivalent to constructing the
969
- // spy with this container from the start: `observeMatches` below
970
- // re-populates the tracked set from the new container's scope, and the
971
- // stale merged snapshot (computed against the old root's geometry) is
972
- // dropped — one empty debounce window, acceptable for a rare event.
973
- const nextContainer = getContainer();
974
- if (nextContainer !== observerContainer) {
975
- observerContainer = nextContainer;
976
- io.disconnect();
977
- io = makeIo(nextContainer);
978
- observed.clear();
979
- pending.clear();
980
- mo?.disconnect();
981
- mo?.observe(nextContainer ?? document.body, MUTATION_OBSERVE_INIT);
982
- }
983
- observeMatches();
984
- };
985
- observeMatches();
986
- mo = new MutationObserver(() => {
987
- if (mutationTimer !== null) {
988
- clearTimeout(mutationTimer);
989
- }
990
- mutationTimer = setTimeout(() => {
991
- mutationTimer = null;
992
- reconcile();
993
- }, MUTATION_DEBOUNCE_MS);
994
- });
995
- mo.observe(observerContainer ?? document.body, MUTATION_OBSERVE_INIT);
996
- return {
997
- pending,
998
- // #1216: the MutationObserver is pointed at the container's OWN subtree, so
999
- // the container's removal (a mutation of its PARENT) is invisible — reconcile
1000
- // never fires on it and a remounted container is never re-observed. Expose a
1001
- // detach check + reconcile so the router.subscribe callback can re-resolve on
1002
- // navigation (exactly when route-tied containers mount/die). When
1003
- // `observerContainer` is null the MO already watches `document.body`, which
1004
- // sees container mounts directly — so only a resolved-then-detached container
1005
- // needs this nav-time nudge.
1006
- isContainerDetached: () => observerContainer !== null && !observerContainer.isConnected,
1007
- reconcile,
1008
- destroy() {
1009
- io.disconnect();
1010
- mo.disconnect();
1011
- if (mutationTimer !== null) {
1012
- clearTimeout(mutationTimer);
1013
- mutationTimer = null;
1014
- }
1015
- observed.clear();
1016
- pending.clear();
1017
- },
1018
- };
446
+ const observed = /* @__PURE__ */ new Set();
447
+ const pending = /* @__PURE__ */ new Map();
448
+ let duplicateIdWarned = false;
449
+ let mutationTimer = null;
450
+ const handleIntersection = (entries) => {
451
+ if (isStopped()) return;
452
+ for (const entry of entries) pending.set(entry.target, entry);
453
+ onIntersection();
454
+ };
455
+ const makeIo = (container) => new IntersectionObserver(handleIntersection, {
456
+ root: container,
457
+ rootMargin,
458
+ threshold: 0
459
+ });
460
+ let observerContainer = getContainer();
461
+ let io = makeIo(observerContainer);
462
+ const observeMatches = () => {
463
+ const scope = getContainer() ?? document;
464
+ let candidates;
465
+ try {
466
+ candidates = scope.querySelectorAll(selector);
467
+ } catch {
468
+ onInvalidSelector();
469
+ return;
470
+ }
471
+ const seenIds = /* @__PURE__ */ new Set();
472
+ for (const element of candidates) {
473
+ const id = element.id;
474
+ if (id && !duplicateIdWarned) {
475
+ if (seenIds.has(id)) {
476
+ duplicateIdWarned = true;
477
+ console.warn(`[real-router] scroll-spy: duplicate id "${id}" observed. Selection picks the topmost visible match deterministically.`);
478
+ }
479
+ seenIds.add(id);
480
+ }
481
+ if (observed.has(element)) continue;
482
+ io.observe(element);
483
+ observed.add(element);
484
+ }
485
+ };
486
+ const MUTATION_OBSERVE_INIT = {
487
+ childList: true,
488
+ subtree: true,
489
+ attributes: true,
490
+ attributeFilter: ["id"]
491
+ };
492
+ let mo = null;
493
+ const reconcile = () => {
494
+ for (const element of observed) {
495
+ if (element.isConnected) continue;
496
+ io.unobserve(element);
497
+ observed.delete(element);
498
+ pending.delete(element);
499
+ }
500
+ const nextContainer = getContainer();
501
+ if (nextContainer !== observerContainer) {
502
+ observerContainer = nextContainer;
503
+ io.disconnect();
504
+ io = makeIo(nextContainer);
505
+ observed.clear();
506
+ pending.clear();
507
+ mo?.disconnect();
508
+ mo?.observe(nextContainer ?? document.body, MUTATION_OBSERVE_INIT);
509
+ }
510
+ observeMatches();
511
+ };
512
+ observeMatches();
513
+ mo = new MutationObserver(() => {
514
+ if (mutationTimer !== null) clearTimeout(mutationTimer);
515
+ mutationTimer = setTimeout(() => {
516
+ mutationTimer = null;
517
+ reconcile();
518
+ }, MUTATION_DEBOUNCE_MS);
519
+ });
520
+ mo.observe(observerContainer ?? document.body, MUTATION_OBSERVE_INIT);
521
+ return {
522
+ pending,
523
+ isContainerDetached: () => observerContainer !== null && !observerContainer.isConnected,
524
+ reconcile,
525
+ destroy() {
526
+ io.disconnect();
527
+ mo.disconnect();
528
+ if (mutationTimer !== null) {
529
+ clearTimeout(mutationTimer);
530
+ mutationTimer = null;
531
+ }
532
+ observed.clear();
533
+ pending.clear();
534
+ }
535
+ };
1019
536
  };
1020
- // =============================================================================
1021
- // Main: compositional wiring
1022
- // =============================================================================
1023
537
  function createScrollSpy(router, options) {
1024
- // SSR guard (RFC §7.5) — return early without warnings.
1025
- if (typeof document === "undefined") {
1026
- return NOOP_INSTANCE$1;
1027
- }
1028
- // Feature-detect IntersectionObserver — no polyfill ships (RFC §4).
1029
- if (typeof IntersectionObserver === "undefined") {
1030
- return NOOP_INSTANCE$1;
1031
- }
1032
- const { selector } = options;
1033
- // Empty selector → disabled. Documented opt-out for conditional enabling
1034
- // (RFC §5.4 `scrollSpy={{ selector: enable ? "[id]" : "" }}`).
1035
- if (!selector) {
1036
- return NOOP_INSTANCE$1;
1037
- }
1038
- const rootMargin = options.rootMargin ?? DEFAULT_ROOT_MARGIN;
1039
- const getContainer = options.scrollContainer;
1040
- const resolveContainer = () => getContainer?.() ?? null;
1041
- // Shared lifecycle flags (Oracle Q1 — `silenced` has multiple unrelated
1042
- // triggers; Oracle Q3 — `selfEmitting` synchronously bracketed around
1043
- // `router.navigate()` cannot cleanly extract). Kept in main scope.
1044
- let destroyed = false;
1045
- let silenced = false;
1046
- let selfEmitting = false;
1047
- const isStopped = () => silenced || destroyed;
1048
- // Symmetric late-binding (Oracle Q2): declare `flush` as nullable, wire
1049
- // debouncer + observers, then assign the real implementation. Reads as
1050
- // intentional wiring rather than accidental closure capture ordering.
1051
- // The `flush?.()` call below safely no-ops if a callback somehow fires
1052
- // before assignment (impossible in practice — IO/debounce are async).
1053
- let flush = null;
1054
- const transitionSource = getTransitionSource(router);
1055
- const detector = createUrlPluginDetector(router, () => {
1056
- silenced = true;
1057
- });
1058
- const cooldown = createCooldown(resolveContainer);
1059
- const debouncer = createDebouncer(() => {
1060
- flush?.();
1061
- }, RAF_DEBOUNCE_MS);
1062
- const observers = createObserverPair(selector, rootMargin, resolveContainer, () => {
1063
- debouncer.schedule();
1064
- }, () => {
1065
- if (silenced) {
1066
- return;
1067
- }
1068
- silenced = true;
1069
- console.warn(`[real-router] scroll-spy: invalid selector "${selector}". Disabling.`);
1070
- }, isStopped);
1071
- flush = () => {
1072
- if (destroyed || silenced) {
1073
- observers.pending.clear();
1074
- return;
1075
- }
1076
- // Gate-skipped flushes keep `pendingEntries` populated — the merged
1077
- // state is still the best-known snapshot, and the next non-gated flush
1078
- // consumes it. Clearing under a gate would re-introduce the overwrite
1079
- // bug for any anchor whose intersection state did not change during
1080
- // the gate window.
1081
- if (transitionSource.getSnapshot().isTransitioning) {
1082
- return;
1083
- }
1084
- if (cooldown.active) {
1085
- return;
1086
- }
1087
- // No `if (pending.size === 0) return` fast-path: `pending` is never empty
1088
- // here via any real path (a real IntersectionObserver always delivers ≥1
1089
- // entry, so `handleIntersection` populates `pending` before scheduling; the
1090
- // mutation reconcile that could drop entries runs at MUTATION_DEBOUNCE_MS
1091
- // 250 > RAF_DEBOUNCE_MS 150, i.e. always AFTER the flush). And an empty map
1092
- // is already handled identically below — `pickTopmost(∅)` is `null` → the
1093
- // `if (!picked) return` guard — so the fast-path was both unreachable and
1094
- // redundant.
1095
- // Successful flush consumes the merged snapshot. We clear so that the
1096
- // next debounce window starts fresh; an anchor that is still
1097
- // intersecting will only stay observable if IO emits another event for
1098
- // it (which it does whenever the anchor's intersection state actually
1099
- // changes). Skipping the clear here would leak state from one user-
1100
- // perceived "scroll stop" into the next.
1101
- const picked = pickTopmost(observers.pending.values());
1102
- observers.pending.clear();
1103
- if (!picked) {
1104
- // No anchor visible / above zone — preserve last hash (RFC §10 #5).
1105
- return;
1106
- }
1107
- const newHash = picked.target.id;
1108
- if (!newHash) {
1109
- return;
1110
- }
1111
- const state = router.getState();
1112
- if (!state) {
1113
- return;
1114
- }
1115
- // `getUrlContext` is guaranteed present here (the URL-plugin detector
1116
- // silences the spy otherwise), so `?.` only satisfies the `| undefined`
1117
- // slice type. `newHash` is a non-empty id (guarded above), so it can never
1118
- // equal an absent hash — no `?? ""` normalization needed for the compare.
1119
- const currentHash = getUrlContext(state)?.hash;
1120
- if (newHash === currentHash) {
1121
- return;
1122
- }
1123
- // Emit the same-route same-params hash-only transition. URL plugin
1124
- // writes `state.context.url.hash = newHash` + `hashChanged = true` in
1125
- // its `onTransitionSuccess` claim.
1126
- const opts = {
1127
- hash: newHash,
1128
- replace: true,
1129
- force: true,
1130
- hashChange: true,
1131
- };
1132
- // Self-emit guard (RFC §5.2): set synchronously around our own
1133
- // `router.navigate()` so the `router.subscribe` callback skips the
1134
- // cooldown setup for spy-emitted transitions — otherwise spy would
1135
- // rate-limit itself to ≤ 2 emits/s, contradicting the ≤ 10/s benchmark
1136
- // target. Test coupling (Q8): preserve exact `.catch(noop).finally(reset)`
1137
- // chain — migrating to `try/finally` over `await router.navigate(...)`
1138
- // changes microtask schedule and breaks "spy continues after rejection".
1139
- selfEmitting = true;
1140
- router
1141
- // Both channels of the CURRENT state, not just the path bag (RFC-4 M2 /
1142
- // #1548): this is a same-route re-navigation to move the hash, so
1143
- // whatever query the user is already looking at has to survive it.
1144
- // Passing `undefined` in slot 3 dropped it — scrolling a page at
1145
- // `/docs?tab=api` silently rewrote the URL to `/docs`. Options stay at
1146
- // slot 4.
1147
- .navigate(state.name, state.params, state.search, opts)
1148
- .catch(() => {
1149
- // Fire-and-forget — suppress expected rejections (concurrent
1150
- // navigate, router stopped, etc.) consistent with `<Link>` adapter
1151
- // patterns.
1152
- })
1153
- .finally(() => {
1154
- selfEmitting = false;
1155
- });
1156
- };
1157
- // Cooldown setup on user-driven hash transitions. Spy's own emits are
1158
- // distinguished via the synchronous `selfEmitting` flag (see `flush`).
1159
- const unsubscribeRouter = router.subscribe(({ route }) => {
1160
- if (selfEmitting) {
1161
- return;
1162
- }
1163
- // #1216: a route-tied scroll container may have unmounted since the last
1164
- // navigation. The container-scoped MutationObserver can't observe its own
1165
- // removal (a mutation of its parent), so re-resolve + re-observe here —
1166
- // navigation is exactly when such containers mount / die.
1167
- if (observers.isContainerDetached()) {
1168
- observers.reconcile();
1169
- }
1170
- if (getUrlContext(route)?.hashChanged) {
1171
- cooldown.start();
1172
- }
1173
- });
1174
- return {
1175
- destroy() {
1176
- // No `if (destroyed) return` idempotency guard: every subsystem teardown
1177
- // below is itself idempotent (null-guarded timers, `set.delete` on the
1178
- // router unsubscribe, spec-idempotent `IntersectionObserver.disconnect`),
1179
- // and `destroy()` is not a hot path — so a redundant guard would only add
1180
- // an unreachable branch. `destroyed = true` is still set to gate any
1181
- // late-arriving IO/router callback via `isStopped()`.
1182
- destroyed = true;
1183
- // Unsubscribe FIRST to prevent late-arriving router transition
1184
- // callback from calling `cooldown.start()` on a half-destroyed
1185
- // instance. Without this ordering, a transition with `hashChanged:
1186
- // true` firing between subsystem teardown and `unsubscribeRouter()`
1187
- // would re-install a 500ms timer that survives `destroy()`. Verified
1188
- // via Oracle review (Q5/Q7).
1189
- unsubscribeRouter();
1190
- observers.destroy();
1191
- debouncer.destroy();
1192
- cooldown.destroy();
1193
- detector.destroy();
1194
- },
1195
- };
538
+ if (typeof document === "undefined") return NOOP_INSTANCE$1;
539
+ if (typeof IntersectionObserver === "undefined") return NOOP_INSTANCE$1;
540
+ const { selector } = options;
541
+ if (!selector) return NOOP_INSTANCE$1;
542
+ const rootMargin = options.rootMargin ?? DEFAULT_ROOT_MARGIN;
543
+ const getContainer = options.scrollContainer;
544
+ const resolveContainer = () => getContainer?.() ?? null;
545
+ let destroyed = false;
546
+ let silenced = false;
547
+ let selfEmitting = false;
548
+ const isStopped = () => silenced || destroyed;
549
+ let flush = null;
550
+ const transitionSource = getTransitionSource(router);
551
+ const detector = createUrlPluginDetector(router, () => {
552
+ silenced = true;
553
+ });
554
+ const cooldown = createCooldown(resolveContainer);
555
+ const debouncer = createDebouncer(() => {
556
+ flush?.();
557
+ }, RAF_DEBOUNCE_MS);
558
+ const observers = createObserverPair(selector, rootMargin, resolveContainer, () => {
559
+ debouncer.schedule();
560
+ }, () => {
561
+ if (silenced) return;
562
+ silenced = true;
563
+ console.warn(`[real-router] scroll-spy: invalid selector "${selector}". Disabling.`);
564
+ }, isStopped);
565
+ flush = () => {
566
+ if (destroyed || silenced) {
567
+ observers.pending.clear();
568
+ return;
569
+ }
570
+ if (transitionSource.getSnapshot().isTransitioning) return;
571
+ if (cooldown.active) return;
572
+ const picked = pickTopmost(observers.pending.values());
573
+ observers.pending.clear();
574
+ if (!picked) return;
575
+ const newHash = picked.target.id;
576
+ if (!newHash) return;
577
+ const state = router.getState();
578
+ if (!state) return;
579
+ if (newHash === getUrlContext(state)?.hash) return;
580
+ const opts = {
581
+ hash: newHash,
582
+ replace: true,
583
+ force: true,
584
+ hashChange: true
585
+ };
586
+ selfEmitting = true;
587
+ router.navigate(state.name, state.params, state.search, opts).catch(() => {}).finally(() => {
588
+ selfEmitting = false;
589
+ });
590
+ };
591
+ const unsubscribeRouter = router.subscribe(({ route }) => {
592
+ if (selfEmitting) return;
593
+ if (observers.isContainerDetached()) observers.reconcile();
594
+ if (getUrlContext(route)?.hashChanged) cooldown.start();
595
+ });
596
+ return { destroy() {
597
+ destroyed = true;
598
+ unsubscribeRouter();
599
+ observers.destroy();
600
+ debouncer.destroy();
601
+ cooldown.destroy();
602
+ detector.destroy();
603
+ } };
1196
604
  }
1197
-
1198
- const NOOP_INSTANCE = Object.freeze({
1199
- destroy: () => {
1200
- /* no-op */
1201
- },
1202
- });
605
+ const NOOP_INSTANCE = Object.freeze({ destroy: () => {} });
1203
606
  function createViewTransitions(router) {
1204
- if (typeof document === "undefined" ||
1205
- typeof document.startViewTransition !== "function") {
1206
- return NOOP_INSTANCE;
1207
- }
1208
- let closeVT = null;
1209
- let currentVT = null;
1210
- // Tracks whether TRANSITION_SUCCESS fired for the current leave. Used to
1211
- // distinguish "benign cleanup abort" (router's async path aborts its own
1212
- // controller in a finally block after successful navigation) from "real
1213
- // cancellation" (concurrent navigate, guard rejection, dispose).
1214
- let successFired = false;
1215
- const resolveAndClear = () => {
1216
- closeVT?.();
1217
- closeVT = null;
1218
- };
1219
- const offLeave = router.subscribeLeave(({ signal }) => {
1220
- // Reentrant abort: signal already aborted when we're called. Open no VT
1221
- // — router will fall through to TRANSITION_CANCELLED via isCurrentNav()
1222
- // after leave resolves. addEventListener("abort", ...) does not re-fire
1223
- // for past events, so skipping startViewTransition is the safe path.
1224
- if (signal.aborted) {
1225
- return;
1226
- }
1227
- successFired = false;
1228
- resolveAndClear();
1229
- // Return a Promise so the router awaits until the browser invokes
1230
- // updateCallback. This ensures old DOM snapshot is captured BEFORE the
1231
- // router commits the new state — giving correct exit→state→entry
1232
- // ordering (vs fire-and-forget, where URL changes before VT captures).
1233
- return new Promise((resolveLeave) => {
1234
- // Capture the resolver synchronously BEFORE startViewTransition() is
1235
- // called. The browser invokes updateCallback in a later task, but
1236
- // router.subscribe (TRANSITION_SUCCESS) can fire before that. If we
1237
- // captured `resolve` inside the callback, subscribe would see closeVT
1238
- // still null and skip resolving — the deferred would hang for 4s
1239
- // until the VT API aborts with TimeoutError.
1240
- // eslint-disable-next-line unicorn/prefer-promise-with-resolvers -- frozen shared primitive; resolver captured synchronously before startViewTransition() by design (see comment above)
1241
- const deferred = new Promise((resolve) => {
1242
- closeVT = resolve;
1243
- });
1244
- signal.addEventListener("abort", () => {
1245
- if (successFired) {
1246
- // Router's async path (#finishAsyncNavigation) aborts its own
1247
- // controller in a finally block AFTER completeTransition (and
1248
- // thus AFTER subscribe fired). This is cleanup, not
1249
- // cancellation — VT is progressing normally, do nothing.
1250
- return;
1251
- }
1252
- // Real cancellation (concurrent navigate, dispose). Resolve the
1253
- // deferred so updateCallback can complete, skip the VT so no
1254
- // stale animation leaks, and unblock the router if the abort
1255
- // fires before updateCallback was invoked.
1256
- resolveAndClear();
1257
- currentVT?.skipTransition?.();
1258
- resolveLeave();
1259
- }, { once: true });
1260
- try {
1261
- currentVT = document.startViewTransition(() => {
1262
- // Resolving here unblocks the router at the moment the browser
1263
- // enters updateCallback — by spec, old DOM snapshot is captured
1264
- // before this callback runs. Router now proceeds through
1265
- // activation guards and setState; the VT animation waits on
1266
- // `deferred`, which is resolved from router.subscribe after a
1267
- // task-queue tick (see NOTE on setTimeout below).
1268
- resolveLeave();
1269
- return deferred;
1270
- });
1271
- }
1272
- catch {
1273
- // Defensive: spec says startViewTransition doesn't throw under
1274
- // normal conditions, but Chromium has had edge cases (detached
1275
- // document, extension interference). Clean up and unblock router.
1276
- resolveAndClear();
1277
- resolveLeave();
1278
- }
1279
- });
1280
- });
1281
- const offSuccess = router.subscribe(() => {
1282
- const resolver = closeVT;
1283
- successFired = true;
1284
- closeVT = null;
1285
- if (resolver === null) {
1286
- currentVT = null;
1287
- }
1288
- else {
1289
- // The VT this resolver belongs to. If the next navigation opens a new VT
1290
- // in the task-queue window before this setTimeout runs, the stale
1291
- // resolver must NOT null the new `currentVT` — otherwise a later
1292
- // cancellation reads `null` and skips nothing, leaking a stale animation
1293
- // (#781). Same identity-guard technique the navigation-plugin uses to
1294
- // heal its seams.
1295
- const scheduledVT = currentVT;
1296
- // CRITICAL: CANNOT use requestAnimationFrame here. When the router
1297
- // takes the async path (leave returned a Promise), subscribe fires
1298
- // AFTER the browser has already transitioned VT into the
1299
- // "update-callback-called" phase. In that phase Chromium sets
1300
- // rendering suppression to true, which ALSO blocks rAF callbacks.
1301
- // rAF would never fire → deferred never resolves → browser aborts
1302
- // vt.ready with TimeoutError after 4s (observed in Chromium).
1303
- //
1304
- // setTimeout runs on the task queue independent of the rendering
1305
- // pipeline, so it fires regardless of suppression. React's scheduler
1306
- // uses MessageChannel tasks, which are queued before our setTimeout,
1307
- // so the new DOM is committed by the time our callback runs.
1308
- setTimeout(() => {
1309
- resolver();
1310
- if (currentVT === scheduledVT) {
1311
- currentVT = null;
1312
- }
1313
- }, 0);
1314
- }
1315
- });
1316
- return {
1317
- destroy: () => {
1318
- offLeave();
1319
- offSuccess();
1320
- currentVT?.skipTransition?.();
1321
- currentVT = null;
1322
- resolveAndClear();
1323
- },
1324
- };
607
+ if (typeof document === "undefined" || typeof document.startViewTransition !== "function") return NOOP_INSTANCE;
608
+ let closeVT = null;
609
+ let currentVT = null;
610
+ let successFired = false;
611
+ const resolveAndClear = () => {
612
+ closeVT?.();
613
+ closeVT = null;
614
+ };
615
+ const offLeave = router.subscribeLeave(({ signal }) => {
616
+ if (signal.aborted) return;
617
+ successFired = false;
618
+ resolveAndClear();
619
+ return new Promise((resolveLeave) => {
620
+ const deferred = new Promise((resolve) => {
621
+ closeVT = resolve;
622
+ });
623
+ signal.addEventListener("abort", () => {
624
+ if (successFired) return;
625
+ resolveAndClear();
626
+ currentVT?.skipTransition?.();
627
+ resolveLeave();
628
+ }, { once: true });
629
+ try {
630
+ currentVT = document.startViewTransition(() => {
631
+ resolveLeave();
632
+ return deferred;
633
+ });
634
+ } catch {
635
+ resolveAndClear();
636
+ resolveLeave();
637
+ }
638
+ });
639
+ });
640
+ const offSuccess = router.subscribe(() => {
641
+ const resolver = closeVT;
642
+ successFired = true;
643
+ closeVT = null;
644
+ if (resolver === null) currentVT = null;
645
+ else {
646
+ const scheduledVT = currentVT;
647
+ setTimeout(() => {
648
+ resolver();
649
+ if (currentVT === scheduledVT) currentVT = null;
650
+ }, 0);
651
+ }
652
+ });
653
+ return { destroy: () => {
654
+ offLeave();
655
+ offSuccess();
656
+ currentVT?.skipTransition?.();
657
+ currentVT = null;
658
+ resolveAndClear();
659
+ } };
1325
660
  }
1326
-
1327
- /**
1328
- * Intrinsics captured at module load (#1971).
1329
- *
1330
- * ⚑ These DECIDE — they answer "what is on this object" for a value this module
1331
- * did not build. Read off the live global they can be re-pointed after boot, and
1332
- * `shared/` is the half where that fails OPEN: measured in `browser-env`, a
1333
- * re-pointed `getPrototypeOf` admits a `Date` into `state.params` and a
1334
- * re-pointed `keys` skips option validation entirely.
1335
- *
1336
- * ⚠ Capture narrows the window from "any time after boot" to "before this module
1337
- * loads". It does not close it — a shim evaluated ahead of core still wins
1338
- * (#1798), which is the doctrine's own caveat and travels with it.
1339
- */
1340
661
  const objectKeys = Object.keys;
1341
- /**
1342
- * The brand `packages/core/src/internals.ts` puts on every router it registers,
1343
- * RE-DECLARED rather than imported (#2294).
1344
- *
1345
- * ⚑ `Symbol.for` makes the two the same symbol, so **the STRING is the
1346
- * contract** — change it in one place and this warning silently stops firing.
1347
- * The same shape core already uses for `CONFIG_FAULT`, declared twice across a
1348
- * boundary it cannot import over, and pinned the same way: the guard is
1349
- * `foreign-router-href-2294.test.ts`, whose cells fail on exactly that drift.
1350
- */
1351
662
  const ROUTER_BRAND = Symbol.for("real-router.router");
1352
- /**
1353
- * Is this a real router that core cannot read — as opposed to the `Router`-SHAPED
1354
- * double this helper accepts by contract?
1355
- *
1356
- * ⚠ Read defensively: the argument is the caller's object and may be a `Proxy`
1357
- * whose `get` trap throws. A diagnostic that throws would change where the error
1358
- * comes FROM, which is the #1572 class, so a throwing read means "cannot tell".
1359
- */
1360
663
  function isUnreadableRouter(candidate) {
1361
- try {
1362
- return (candidate?.[ROUTER_BRAND] === true);
1363
- }
1364
- catch {
1365
- return false;
1366
- }
664
+ try {
665
+ return candidate?.[ROUTER_BRAND] === true;
666
+ } catch {
667
+ return false;
668
+ }
1367
669
  }
1368
- /**
1369
- * The registry lookup, ALONE — and standing alone is what makes the warning
1370
- * correct (#2294).
1371
- *
1372
- * ⚑ Inside the resolve-and-print `try` this could not be told apart from a
1373
- * `forwardState` that threw for a reason the arm handles deliberately. The
1374
- * channel guard (#1572) is exactly that, and it fires on a router that IS
1375
- * registered and IS branded — so a check made there would report duplicated core
1376
- * on a perfectly healthy one.
1377
- */
1378
670
  function readPluginApi(router, routeName) {
1379
- try {
1380
- return getPluginApi(router);
1381
- }
1382
- catch {
1383
- if (isUnreadableRouter(router)) {
1384
- console.error(`[real-router] Route "${routeName}" rendered its LITERAL path: this IS a router, ` +
1385
- "but not one this copy of @real-router/core built, so `forwardTo` was not resolved. " +
1386
- "It is either wrapped in a Proxy (Vue `reactive()` / Pinia — store it with `markRaw`), " +
1387
- "or your dependency tree holds two copies of @real-router/core — dedupe it to one.");
1388
- }
1389
- return undefined;
1390
- }
671
+ try {
672
+ return getPluginApi(router);
673
+ } catch {
674
+ if (isUnreadableRouter(router)) console.error(`[real-router] Route "${routeName}" rendered its LITERAL path: this IS a router, but not one this copy of @real-router/core built, so \`forwardTo\` was not resolved. It is either wrapped in a Proxy (Vue \`reactive()\` / Pinia — store it with \`markRaw\`), or your dependency tree holds two copies of @real-router/core — dedupe it to one.`);
675
+ return;
676
+ }
1391
677
  }
1392
- /**
1393
- * Collapses a `<Link>`'s two prop forms (RFC-4 M2 B2, #1548) into one channel
1394
- * triple:
1395
- *
1396
- * - **Descriptor** — `to={{ name, params?, search? }}` (a `NavigationTarget`).
1397
- * - **Channel props** — `routeName` + `routeParams?` + `routeSearch?`.
1398
- *
1399
- * The forms are mutually exclusive: the TS union on each adapter's `LinkProps`
1400
- * rejects mixing them at compile time, and this helper is the runtime backstop —
1401
- * when `to` is present it **wins**, and a `dev`-visible `console.warn` fires if
1402
- * channel props were also supplied (a JS consumer, an object spread, or an
1403
- * adapter without a strict union can still slip both through). `routeOptions` /
1404
- * `hash` are separate props under BOTH forms (hash is not part of
1405
- * `NavigationTarget` — #532), so they are resolved by the caller, not here.
1406
- */
1407
678
  function resolveLinkTarget(to, routeName, routeParams, routeSearch) {
1408
- if (to !== undefined) {
1409
- if (routeName !== "" ||
1410
- routeParams !== undefined ||
1411
- routeSearch !== undefined) {
1412
- console.warn("[real-router] <Link> received both `to` and channel props " +
1413
- "(routeName / routeParams / routeSearch). `to` wins; the channel " +
1414
- "props are ignored. Use one form or the other.");
1415
- }
1416
- return { name: to.name, params: to.params, search: to.search };
1417
- }
1418
- return { name: routeName, params: routeParams, search: routeSearch };
679
+ if (to !== void 0) {
680
+ if (routeName !== "" || routeParams !== void 0 || routeSearch !== void 0) console.warn("[real-router] <Link> received both `to` and channel props (routeName / routeParams / routeSearch). `to` wins; the channel props are ignored. Use one form or the other.");
681
+ return {
682
+ name: to.name,
683
+ params: to.params,
684
+ search: to.search
685
+ };
686
+ }
687
+ return {
688
+ name: routeName,
689
+ params: routeParams,
690
+ search: routeSearch
691
+ };
1419
692
  }
1420
693
  function shouldNavigate(evt) {
1421
- return (evt.button === 0 &&
1422
- !evt.metaKey &&
1423
- !evt.altKey &&
1424
- !evt.ctrlKey &&
1425
- !evt.shiftKey);
694
+ return evt.button === 0 && !evt.metaKey && !evt.altKey && !evt.ctrlKey && !evt.shiftKey;
1426
695
  }
1427
- /**
1428
- * Does an anchor's `target` send this navigation somewhere the router cannot
1429
- * follow? (#1834)
1430
- *
1431
- * `target` names the browsing context the author wants the URL loaded into.
1432
- * Three values are the router's — absent, empty, `_self` — and every other one
1433
- * goes to the browser, the only thing that can resolve a context name.
1434
- * Intercepting instead is how a `<Link target="_blank">` ends up reloading the
1435
- * same tab rather than opening a new one. React Router's
1436
- * `shouldProcessLinkClick` and TanStack Router's `handleClick` split the same
1437
- * way; neither reproduces browsing contexts inside the router, and neither does
1438
- * this.
1439
- *
1440
- * ⚠ The split is by SPELLING, not by where the value resolves to, and three
1441
- * spellings resolve back to this context anyway: `_parent` and `_top` fall back
1442
- * to `_self` in a document with no ancestor, and `_SELF` matches `_self`
1443
- * ASCII-case-insensitively (MDN, `<a>` § target). All three are handed to the
1444
- * browser, which reaches the right destination by a full page load instead of a
1445
- * transition. Resolving them properly means reproducing frame ancestry and
1446
- * keyword folding here; both reference routers decline, and the cost is a page
1447
- * load rather than a wrong destination.
1448
- *
1449
- * ⚠ Ask this only about an `<a>`. On a `<button v-link>` or a `<div use:link>`
1450
- * the attribute is inert markup the browser will not act on, so deferring there
1451
- * would leave the activation unhandled by anyone. Callers that cannot assume an
1452
- * anchor ask {@link anchorTargetsAnotherContext} instead, which narrows first;
1453
- * `target-predicate-authority-1834` owns which call site is in which set.
1454
- */
1455
696
  function targetsAnotherContext(target) {
1456
- return Boolean(target) && target !== "_self";
1457
- }
1458
- /**
1459
- * The same question, asked about an ELEMENT — for the `use:link` / `v-link`
1460
- * forms, which attach to whatever element the consumer wrote and so cannot
1461
- * assume an anchor (#1834). The `<Link>` components pass a value instead
1462
- * (they render the anchor), and so does Angular's directive (its selector is
1463
- * `a[realLink]`).
1464
- *
1465
- * ⚠ `tagName`, never `instanceof HTMLAnchorElement`, for the reason
1466
- * `applyLinkA11y` sets out below: the constructor belongs to the realm this
1467
- * module loaded in, so a real anchor from an iframe `contentDocument` or a
1468
- * micro-frontend fails the check. Failing it HERE re-intercepts the very
1469
- * `target="_blank"` click this predicate exists to leave alone.
1470
- *
1471
- * Anything that is not an HTML anchor answers `false`: `target` is
1472
- * anchor-specific markup the browser will not act on, so a `<button use:link>`
1473
- * or a `<div v-link>` carrying one must still navigate in-app.
1474
- */
1475
- function anchorTargetsAnotherContext(element) {
1476
- if (element?.tagName !== "A") {
1477
- return false;
1478
- }
1479
- return targetsAnotherContext(element.getAttribute("target"));
697
+ return Boolean(target) && target !== "_self";
1480
698
  }
1481
- /**
1482
- * RFC 3986 fragment encoding: preserve sub-delims (`&`, `=`, `?`, `:`),
1483
- * encode space, `%`, control chars, non-ASCII via encodeURI; defensively
1484
- * escape `#` (encodeURI does not). Kept BYTE-FOR-BYTE identical to
1485
- * `encodeHashFragment` in `shared/browser-env/url-context.ts` — duplicated
1486
- * because the shared/dom-utils symlink graph does not reach shared/browser-env;
1487
- * a sync test (`link-utils` functional suite) asserts the two stay identical.
1488
- *
1489
- * **STRICTLY-DECODED contract (#1211 / D1=A).** The `<Link hash>` value is a
1490
- * DECODED fragment (no leading `#`) and is encoded verbatim. This OVERTURNS
1491
- * audit-2026-05-17 §5 E.1 — the earlier percent-escape probe (decode + re-encode
1492
- * for copy-from-`location.hash` tolerance) is REMOVED, so both the adapter and
1493
- * the plugin layer obey one contract: `<Link hash="a%20b">` renders `#a%2520b`
1494
- * (the literal fragment `a%20b`) under every runtime. Consumers who want the
1495
- * fragment `a b` pass `hash="a b"`; passing raw `location.hash` (percent-encoded)
1496
- * is no longer supported — it was the source of the plugin↔adapter divergence.
1497
- */
1498
699
  function encodeFragmentInline(decoded) {
1499
- return encodeURI(decoded).replaceAll("#", "%23");
700
+ return encodeURI(decoded).replaceAll("#", "%23");
1500
701
  }
1501
- /**
1502
- * Builds an href for a `<Link>` element.
1503
- *
1504
- * - Prefers the URL plugin's `buildUrl` (browser-plugin, navigation-plugin,
1505
- * hash-plugin) when present.
1506
- * - Falls back to the core's resolving door for runtimes without a URL plugin
1507
- * (memory-plugin, console UIs, NativeScript). In that fallback the hash
1508
- * is appended manually so the rendered href is still correct.
1509
- * - The optional 4th argument is the decoded hash fragment (no leading "#";
1510
- * `<Link hash="#section">` is accepted defensively — leading "#" stripped),
1511
- * passed positionally to mirror `navigateWithHash(router, name, params, hash)`
1512
- * (#1442). Previous 3-arg call sites continue to work unchanged.
1513
- */
1514
702
  function buildHref(router, routeName, routeParams, routeSearch, hash) {
1515
- try {
1516
- let normHash;
1517
- if (hash !== undefined) {
1518
- normHash = hash.startsWith("#") ? hash.slice(1) : hash;
1519
- }
1520
- const buildUrl = router.buildUrl;
1521
- if (buildUrl) {
1522
- const url = buildUrl(routeName, routeParams,
1523
- // Query channel at position 3 (RFC-4 M2 / #1548) — from the `routeSearch`
1524
- // prop; hash options at position 4. `undefined` when the link has no
1525
- // `routeSearch` (its query, if any, still rides in routeParams).
1526
- routeSearch, normHash === undefined ? undefined : { hash: normHash });
1527
- // Accept only non-empty strings. The BuildUrlFn type contract is
1528
- // `string | undefined`, but defensive against:
1529
- // - `""` (empty string) → would render `<a href="">`, which resolves
1530
- // to the current page URL → silent self-navigation on click.
1531
- // - `null` (type-contract violation) → would render `<a href={null}>`,
1532
- // stringified to `"null"` in some renderers.
1533
- // Either case falls through to the `router.buildPath` fallback below.
1534
- if (typeof url === "string" && url.length > 0) {
1535
- return url;
1536
- }
1537
- }
1538
- // ⚑ RESOLVE, then print (#2250). An href is a promise about where the click
1539
- // lands, and the click resolves `forwardTo`. `router.buildPath` alone is
1540
- // class LITERAL by record and answers about the route it was NAMED —
1541
- // INVARIANTS #8 keeps that so a plugin can build a state for an alias
1542
- // without being teleported off it — so the chain is resolved FIRST and the
1543
- // printer prints the target. The door choice belongs here rather than one
1544
- // layer down.
1545
- //
1546
- // ⚠ **The `??` is not reached by a name the table does not hold, and the
1547
- // claim that it was described a door this arm stopped calling.** That read
1548
- // `buildNavigationState`, which answers `undefined` for an unknown route;
1549
- // since #2265 the resolving door is `forwardState`, which ANSWERS for one
1550
- // (measured — it does not validate the name), leaving the printer to throw.
1551
- // `packages/react/INVARIANTS.md` row 3 still holds — `Both throw →
1552
- // undefined + console.error` — but it is reached by both printers throwing,
1553
- // not by a `undefined` the `??` absorbs. What the `??` IS load-bearing for
1554
- // is the two cases below.
1555
- //
1556
- // ⚠ **The fallback is also where the channel guard lands (#1572).** A route's
1557
- // declared query name handed in the PATH bag makes the class-① door throw
1558
- // where `buildPath` answers, so the `??` prints the literal path — the same
1559
- // href this arm has always rendered. Under a URL plugin the guard is not
1560
- // swallowed: `router.buildUrl` throws and the outer `catch` drops the href.
1561
- //
1562
- // ⚠ **The inner `try` keeps this helper's STRUCTURAL contract.** `buildHref`
1563
- // is handed a `Router`-shaped object, not necessarily a registered one, and
1564
- // `getPluginApi` resolves it through `getInternals` — a WeakMap keyed on
1565
- // identity, which REFUSES a test double or a `Proxy` wrapper. Such a router
1566
- // keeps the literal path; the stub-router CONTROL in
1567
- // `packages/react/tests/functional/dom-utils/forwarding-link-href-2250.test.ts`
1568
- // owns that.
1569
- let resolved;
1570
- const api = readPluginApi(router, routeName);
1571
- try {
1572
- // ⚠ **`forwardState`, not `buildNavigationState`.** Both resolve the whole
1573
- // chain, and the href is identical — but the committing door opts into
1574
- // `reportUndeclaredParamKey`, and an href COMMITS NOTHING. That diagnostic
1575
- // is for a state you are about to persist, which is why `canNavigateTo`
1576
- // is silent despite sharing `navigate`'s form (#2248 / #1581).
1577
- // ⚑ **`buildPathResolved`, not `router.buildPath` — ONE href is ONE pass
1578
- // of the chain (#2260).** The facade's printer runs the `forwardState`
1579
- // seam a door lower (#2087), which is right for a caller holding a raw
1580
- // intent and a SECOND pass for this one, which just resolved. Counted,
1581
- // because nothing in either door's source says "twice": the second pass
1582
- // is what two individually-correct doors compose to.
1583
- //
1584
- // ⚠ A plugin author registers one interceptor and has no reason to expect
1585
- // two invocations per href — a stateful one double-counts. Cost is the
1586
- // lesser half: +1333 ns per href with `search-schema` +
1587
- // `persistent-params` installed, per `<Link>` per render.
1588
- //
1589
- // ⚠ `api?.` is a TYPE gate, not a runtime guard, and naming it so keeps it
1590
- // from being read as one: calling `forwardState` on `undefined` throws
1591
- // into the same `catch` for the same outcome, so a mutant dropping the
1592
- // check is EQUIVALENT. What it buys is that TypeScript can see the call is
1593
- // safe below a lookup that may have failed (#2294).
1594
- const forwarded = api?.forwardState(routeName, routeParams, routeSearch);
1595
- resolved =
1596
- forwarded &&
1597
- api?.buildPathResolved(forwarded.name, forwarded.params, forwarded.search);
1598
- }
1599
- catch {
1600
- resolved = undefined;
1601
- }
1602
- const path = resolved ?? router.buildPath(routeName, routeParams, routeSearch);
1603
- // Symmetric to the buildUrl guard above (#S1 audit, Invariant 12).
1604
- // `router.buildPath` is typed `string`, but defends against:
1605
- // - `""` (empty string) — would render `<a href="">`, which resolves
1606
- // to the current page URL → silent self-navigation on click.
1607
- // - non-string type-contract violations from custom path-matchers.
1608
- // Both yield `undefined` (renderer drops the attribute) with a warning.
1609
- if (typeof path !== "string" || path.length === 0) {
1610
- console.error(`[real-router] Route "${routeName}" yielded an empty path. The element will render without an href attribute.`);
1611
- return undefined;
1612
- }
1613
- return normHash ? `${path}#${encodeFragmentInline(normHash)}` : path;
1614
- }
1615
- catch {
1616
- console.error(`[real-router] Route "${routeName}" is not defined. The element will render without an href attribute.`);
1617
- return undefined;
1618
- }
703
+ try {
704
+ let normHash;
705
+ if (hash !== void 0) normHash = hash.startsWith("#") ? hash.slice(1) : hash;
706
+ const buildUrl = router.buildUrl;
707
+ if (buildUrl) {
708
+ const url = buildUrl(routeName, routeParams, routeSearch, normHash === void 0 ? void 0 : { hash: normHash });
709
+ if (typeof url === "string" && url.length > 0) return url;
710
+ }
711
+ let resolved;
712
+ const api = readPluginApi(router, routeName);
713
+ try {
714
+ const forwarded = api?.forwardState(routeName, routeParams, routeSearch);
715
+ resolved = forwarded && api?.buildPathResolved(forwarded.name, forwarded.params, forwarded.search);
716
+ } catch {
717
+ resolved = void 0;
718
+ }
719
+ const path = resolved ?? router.buildPath(routeName, routeParams, routeSearch);
720
+ if (typeof path !== "string" || path.length === 0) {
721
+ console.error(`[real-router] Route "${routeName}" yielded an empty path. The element will render without an href attribute.`);
722
+ return;
723
+ }
724
+ return normHash ? `${path}#${encodeFragmentInline(normHash)}` : path;
725
+ } catch {
726
+ console.error(`[real-router] Route "${routeName}" is not defined. The element will render without an href attribute.`);
727
+ return;
728
+ }
1619
729
  }
1620
- /**
1621
- * `<Link>` click-handler navigation helper (#532).
1622
- *
1623
- * Wraps `router.navigate(name, params, search, opts)` — the query channel took
1624
- * slot 3 in RFC-4 M2 (#1548) — with same-route different-hash
1625
- * detection: when the consumer clicks a hash-bearing Link that targets the
1626
- * current route with the same params but a different fragment, core's
1627
- * SAME_STATES check would otherwise reject the navigation. The helper adds
1628
- * `force: true` and `hashChange: true` automatically — subscribers can then
1629
- * disambiguate via `state.context.url.hashChanged`.
1630
- *
1631
- * For pure programmatic same-route hash-only navigation, callers are
1632
- * documented to pass `{ force: true }` themselves; the auto-bypass here is
1633
- * a UX convenience for `<Link hash>` that all 6 framework adapters share.
1634
- */
1635
730
  function navigateWithHash(router, routeName, routeParams, routeSearch, hash, extraOptions) {
1636
- const opts = { ...extraOptions };
1637
- if (hash !== undefined) {
1638
- // ⚑ `putField`, not `opts.hash = …` (#2141 / #1852). The spread above produces
1639
- // no own key for this slot unless the caller's extra options carried one, so
1640
- // a plain assignment walks the prototype: an ambient accessor an application
1641
- // or a polyfill put on `Object.prototype` takes the value and the navigation
1642
- // runs without the fragment it was asked for, or — getter-only — throws.
1643
- //
1644
- // ⚠ This dir is shared, so one unguarded write here multiplies by its whole
1645
- // consumer set — `packages/react` is the coverage and authority owner
1646
- // (#1838) and owns that count. Its scan classifies COMPUTED-key writes only,
1647
- // which is why a literal slot like this one sat outside it.
1648
- putField(opts, "hash", hash);
1649
- }
1650
- const current = router.getState();
1651
- // What the navigation gets — the caller's `routeSearch` unless the bypass
1652
- // below substitutes it (#1925).
1653
- let navigatedSearch = routeSearch;
1654
- if (current !== undefined) {
1655
- // ONE expression, asked ONCE and navigated with under the bypass (#1925).
1656
- // The predicate's answer is only as good as the value it answered ABOUT, so
1657
- // the two must be the same value — a second copy of this expression would
1658
- // let them drift apart with nothing to catch it. The name is what keeps
1659
- // them in agreement structurally rather than by convention.
1660
- const sameLocationSearch = routeSearch ?? current.search;
1661
- // "Does this link point at where we already are?" is a question the router
1662
- // owns, and asking it here by hand got two things wrong at once (#1555).
1663
- //
1664
- // The hand-rolled version compared with `Object.is` per key, so a link
1665
- // writing `routeSearch={{ page: "2" }}` never matched a state parsed from
1666
- // `?page=2`, where the value is the NUMBER 2 — the bypass silently did not
1667
- // fire, core rejected the navigation as SAME_STATES, and `<Link hash>`
1668
- // looked dead. The predicate carries the provenance-tolerant comparison
1669
- // (#1554) that makes the two forms equal because they print the same URL.
1670
- //
1671
- // It also compared the caller's whole `routeParams` bag against
1672
- // `state.params`, which stopped meaning anything once the channels split
1673
- // (#1548) — the predicate applies the channel rule instead of re-deriving
1674
- // it.
1675
- //
1676
- // `strictEquality: true` — a link to a PARENT route is a different
1677
- // location, so the hierarchical arm must not match. `ignoreQueryParams:
1678
- // false` — the query is part of the location here; ignoring it would fire
1679
- // the bypass across a real query change and let `force: true` smuggle it
1680
- // through as a hash change.
1681
- if (router.isActiveRoute(routeName, routeParams, sameLocationSearch, true, false)) {
1682
- const currentHash = current.context?.url
1683
- ?.hash ?? "";
1684
- const newHash = hash ?? currentHash;
1685
- if (currentHash !== newHash) {
1686
- opts.force = true;
1687
- opts.hashChange = true;
1688
- // Reaching here means the predicate answered "this is where we already
1689
- // are, only the fragment differs", and `force` + `hashChange` announce
1690
- // exactly that. The bare `routeSearch` would say "no query" rather than
1691
- // "unchanged" — on `/docs?tab=api` a fragment link would land on
1692
- // `/docs`, moving the location it just announced as unmoved. Same slot,
1693
- // same conclusion as `scroll-spy.ts`, which re-navigates with both
1694
- // channels of the CURRENT state.
1695
- //
1696
- // ⚠ Only under the bypass. Without it the helper claims no sameness, so
1697
- // `<Link routeName="docs">` means `/docs` — substituting there would
1698
- // turn a real navigation into a no-op. An explicit `routeSearch={{}}`
1699
- // still clears the query, because `{}` is not nullish. Both pinned by
1700
- // the #1925 suite.
1701
- navigatedSearch = sameLocationSearch;
1702
- }
1703
- }
1704
- }
1705
- // Query channel at position 3 (RFC-4 M2 / #1548); opts at position 4.
1706
- return router.navigate(routeName, routeParams, navigatedSearch, opts);
1707
- }
1708
- // Match-any-whitespace regex shared across calls. RegExp literals at
1709
- // call-site recompile in some engines; lifting it avoids that microcost
1710
- // for the slow-path branch.
1711
- const WHITESPACE_PROBE = /\s/;
1712
- const WHITESPACE_SPLIT = /\S+/g;
1713
- // `value` is always a truthy class string: both call sites narrow it first
1714
- // (`if (isActive && activeClassName)` / `if (!baseClassName) return …`), so an
1715
- // `if (!value) return []` guard here would be unreachable (#809).
1716
- function parseTokens(value) {
1717
- // Hot-path fast-path (audit-2026-05-17 §8b #1): >99% of active-class
1718
- // inputs at `<Link>` emit are single-token strings like `"active"` or
1719
- // `"is-current"` — no whitespace, no leading/trailing pad. Skip the
1720
- // regex match and Array result allocation: a literal `[value]` works
1721
- // because the slow-path `match(/\S+/g)` would return exactly `[value]`
1722
- // for the same input. PBT lock: linkUtils.properties.ts Invariant 13.
1723
- if (!WHITESPACE_PROBE.test(value)) {
1724
- return [value];
1725
- }
1726
- return value.match(WHITESPACE_SPLIT) ?? [];
1727
- }
1728
- function buildActiveClassName(isActive, activeClassName, baseClassName) {
1729
- if (isActive && activeClassName) {
1730
- const activeTokens = parseTokens(activeClassName);
1731
- if (activeTokens.length === 0) {
1732
- return baseClassName ?? undefined;
1733
- }
1734
- if (!baseClassName) {
1735
- return activeTokens.join(" ");
1736
- }
1737
- const baseTokens = parseTokens(baseClassName);
1738
- const seen = new Set(baseTokens);
1739
- for (const token of activeTokens) {
1740
- if (seen.has(token)) {
1741
- continue;
1742
- }
1743
- seen.add(token);
1744
- baseTokens.push(token);
1745
- }
1746
- return baseTokens.join(" ");
1747
- }
1748
- return baseClassName ?? undefined;
731
+ const opts = { ...extraOptions };
732
+ if (hash !== void 0) putField(opts, "hash", hash);
733
+ const current = router.getState();
734
+ let navigatedSearch = routeSearch;
735
+ if (current !== void 0) {
736
+ const sameLocationSearch = routeSearch ?? current.search;
737
+ if (router.isActiveRoute(routeName, routeParams, sameLocationSearch, true, false)) {
738
+ const currentHash = current.context?.url?.hash ?? "";
739
+ if (currentHash !== (hash ?? currentHash)) {
740
+ opts.force = true;
741
+ opts.hashChange = true;
742
+ navigatedSearch = sameLocationSearch;
743
+ }
744
+ }
745
+ }
746
+ return router.navigate(routeName, routeParams, navigatedSearch, opts);
1749
747
  }
1750
- /**
1751
- * One-level structural equality using `Object.is` per key.
1752
- *
1753
- * **String-keyed properties only (Mini-sprint E.3 — audit-5 §4.2 #3).**
1754
- * Implementation walks `Object.keys()` which by spec returns only
1755
- * enumerable own STRING keys. Symbol-keyed properties — created via
1756
- * `obj[Symbol("brand")] = value` or `{ [Symbol(...)]: value }` — are
1757
- * NOT compared. Two records that differ only in a Symbol-keyed value
1758
- * will compare as equal.
1759
- *
1760
- * This is intentional: route params and Link options are documented as
1761
- * string-keyed primitives (string | number | boolean) — Symbol-keyed
1762
- * metadata (e.g. brand markers, private state) doesn't belong in a
1763
- * cache-key comparison. Switching to `Reflect.ownKeys()` would extend
1764
- * the contract to symbols at the cost of one extra allocation per call
1765
- * (Reflect.ownKeys composes string-keys + symbol-keys arrays). If a
1766
- * consumer relies on symbol-keyed metadata for navigation
1767
- * disambiguation, they should encode it into a string key instead.
1768
- *
1769
- * Mirrors React's `shallowEqual` (packages/shared/shallowEqual.js) in
1770
- * both the string-keys-only semantics and the `hasOwnProperty` guard
1771
- * below.
1772
- */
1773
748
  function shallowEqual(prev, next) {
1774
- if (Object.is(prev, next)) {
1775
- return true;
1776
- }
1777
- if (!prev || !next) {
1778
- return false;
1779
- }
1780
- const prevKeys = objectKeys(prev);
1781
- const nextKeys = objectKeys(next);
1782
- if (prevKeys.length !== nextKeys.length) {
1783
- return false;
1784
- }
1785
- const prevRecord = prev;
1786
- const nextRecord = next;
1787
- for (const key of prevKeys) {
1788
- // ⚑ Membership is decided from the LIST the count produced, never from a
1789
- // second question put to the record (#2064; #1815 settled the same question
1790
- // for `recordsShallowEqual` in core). `Object.keys` is own AND enumerable
1791
- // while `hasOwnProperty` is own only — and on a Proxy it is whatever the
1792
- // `getOwnPropertyDescriptor` trap answers.
1793
- //
1794
- // ⚠ `key in next`, `Object.hasOwn` and `propertyIsEnumerable` are the same
1795
- // family, and none of them is the fix: each leaves a cell of this file's
1796
- // own suites red. `lint:membership` is the ratchet over the class.
1797
- //
1798
- // The second array is free: the count already built it and threw it away.
1799
- if (!nextKeys.includes(key) ||
1800
- !Object.is(prevRecord[key], nextRecord[key])) {
1801
- return false;
1802
- }
1803
- }
1804
- return true;
749
+ if (Object.is(prev, next)) return true;
750
+ if (!prev || !next) return false;
751
+ const prevKeys = objectKeys(prev);
752
+ const nextKeys = objectKeys(next);
753
+ if (prevKeys.length !== nextKeys.length) return false;
754
+ const prevRecord = prev;
755
+ const nextRecord = next;
756
+ for (const key of prevKeys) if (!nextKeys.includes(key) || !Object.is(prevRecord[key], nextRecord[key])) return false;
757
+ return true;
1805
758
  }
1806
759
  function applyLinkA11y(element) {
1807
- if (!element) {
1808
- return;
1809
- }
1810
- // Cross-realm safety (audit-2026-05-17 §5 HIGH #4):
1811
- // `instanceof HTMLAnchorElement` compares against the constructor from
1812
- // the CURRENT realm. An element created in a different window (iframe
1813
- // contentDocument, micro-frontend, embedded widget) fails the check
1814
- // even when it IS a real anchor — the helper would then inject
1815
- // role="link" + tabindex="0" on top of native anchor semantics,
1816
- // breaking screen reader output ("link link") and focus order.
1817
- //
1818
- // tagName is realm-agnostic and is uppercase for HTML-namespaced
1819
- // elements in any document. SVG `<a>` has lowercase tagName plus a
1820
- // different prototype (SVGAElement) — skipping it here is wrong by
1821
- // accident: SVG anchors don't have keyboard activation semantics the
1822
- // helper would add. But they also don't reach this helper in
1823
- // practice (router Link components emit HTML anchors). Lock the
1824
- // uppercase compare to keep the contract narrow.
1825
- const tag = element.tagName;
1826
- if (tag === "A" || tag === "BUTTON") {
1827
- return;
1828
- }
1829
- if (!element.hasAttribute("role")) {
1830
- element.setAttribute("role", "link");
1831
- }
1832
- if (!element.hasAttribute("tabindex")) {
1833
- element.setAttribute("tabindex", "0");
1834
- }
760
+ if (!element) return;
761
+ const tag = element.tagName;
762
+ if (tag === "A" || tag === "BUTTON") return;
763
+ if (!element.hasAttribute("role")) element.setAttribute("role", "link");
764
+ if (!element.hasAttribute("tabindex")) element.setAttribute("tabindex", "0");
1835
765
  }
1836
-
1837
- /**
1838
- * The three DI tokens live in their own leaf module (#1525). Declaring them in
1839
- * `providers.ts` forms a real value-level dependency cycle: that file also
1840
- * imports the install helpers, and `internal/install.ts` injects `ROUTER` back
1841
- * (`providers → install → providers`). It runs at all only because the helpers
1842
- * are lazy inside environment initializers, and `import-x/no-cycle` flags it. A
1843
- * leaf module breaks the cycle structurally. `providers.ts` re-exports them, so the public surface
1844
- * (`@real-router/angular` barrel, `providersFactory`, `injectRouter`) is
1845
- * unchanged.
1846
- */
1847
766
  const ROUTER = new InjectionToken("ROUTER");
1848
767
  const NAVIGATOR = new InjectionToken("NAVIGATOR");
1849
768
  const ROUTE = new InjectionToken("ROUTE");
1850
-
1851
- /**
1852
- * Shared installation helpers for `provideRealRouter` and
1853
- * `provideRealRouterFactory`. Must be called inside the body of a
1854
- * `provideEnvironmentInitializer(() => { ... })` callback so the active
1855
- * injection context resolves `ROUTER`, `ApplicationRef`, and `DestroyRef`.
1856
- *
1857
- * Closes review-2026-05-10 §8.1 MED — eliminates duplicate wiring between
1858
- * `providers.ts` and `providersFactory.ts` (high drift risk noted in the
1859
- * audit: the comment blocks were identical down to the punctuation).
1860
- */
1861
769
  function installScrollRestoration(options) {
1862
- const router = inject(ROUTER);
1863
- const sr = createScrollRestoration(router, options);
1864
- inject(DestroyRef).onDestroy(() => {
1865
- sr.destroy();
1866
- });
770
+ const sr = createScrollRestoration(inject(ROUTER), options);
771
+ inject(DestroyRef).onDestroy(() => {
772
+ sr.destroy();
773
+ });
1867
774
  }
1868
775
  function installScrollSpy(options) {
1869
- const router = inject(ROUTER);
1870
- const spy = createScrollSpy(router, options);
1871
- inject(DestroyRef).onDestroy(() => {
1872
- spy.destroy();
1873
- });
776
+ const spy = createScrollSpy(inject(ROUTER), options);
777
+ inject(DestroyRef).onDestroy(() => {
778
+ spy.destroy();
779
+ });
1874
780
  }
1875
781
  function installViewTransitions() {
1876
- const router = inject(ROUTER);
1877
- // Feature-detect `document.startViewTransition` once at install time. The
1878
- // `appRef.tick()` listener exists ONLY to feed Angular's zoneless CD into
1879
- // the VT utility's `setTimeout(0)`-driven snapshot capture (see comment
1880
- // below). When `startViewTransition` is unavailable (Firefox as of 2026-04,
1881
- // SSR, older browsers), `createViewTransitions` short-circuits to its
1882
- // frozen NOOP_INSTANCE — no leave subscriber registered, no
1883
- // `setTimeout(0)` invariant to satisfy. Installing the per-navigation
1884
- // tick listener anyway would force a synchronous CD pass on every
1885
- // navigation with zero benefit, doubling CD work in zoneless apps.
1886
- // Closes review-2026-05-10 §8.2 MED (view-transitions hot path).
1887
- const vtAvailable = typeof document !== "undefined" &&
1888
- typeof document.startViewTransition === "function";
1889
- let offTick;
1890
- if (vtAvailable) {
1891
- // Force synchronous change detection on every transition success BEFORE
1892
- // the VT utility resolves its deferred. The utility uses `setTimeout(0)`
1893
- // to release the new-snapshot capture, which is load-bearing because
1894
- // Chromium blocks rAF callbacks while VT sits in the
1895
- // `update-callback-called` phase. Angular's zoneless CD is rAF-driven by
1896
- // default — without this synchronous tick the new DOM is not committed
1897
- // when the browser captures the new snapshot, so old and new snapshots
1898
- // end up identical and animations finish in ~0 ms with no visible work
1899
- // (the inner-route `products.list ↔ products.detail` morph in the
1900
- // example app was the canary).
1901
- //
1902
- // Subscribers fire in registration order; this one runs BEFORE
1903
- // `createViewTransitions` registers its own subscriber, guaranteeing CD
1904
- // completes first.
1905
- const appRef = inject(ApplicationRef);
1906
- offTick = router.subscribe(() => {
1907
- appRef.tick();
1908
- });
1909
- }
1910
- const vt = createViewTransitions(router);
1911
- inject(DestroyRef).onDestroy(() => {
1912
- offTick?.();
1913
- vt.destroy();
1914
- });
782
+ const router = inject(ROUTER);
783
+ const vtAvailable = typeof document !== "undefined" && typeof document.startViewTransition === "function";
784
+ let offTick;
785
+ if (vtAvailable) {
786
+ const appRef = inject(ApplicationRef);
787
+ offTick = router.subscribe(() => {
788
+ appRef.tick();
789
+ });
790
+ }
791
+ const vt = createViewTransitions(router);
792
+ inject(DestroyRef).onDestroy(() => {
793
+ offTick?.();
794
+ vt.destroy();
795
+ });
1915
796
  }
1916
-
1917
- /** Must be called within an injection context (constructor, field initializer, runInInjectionContext). */
1918
797
  function sourceToSignal(source) {
1919
- const sig = signal(source.getSnapshot(), /* @ts-ignore */
1920
- ...(ngDevMode ? [{ debugName: "sig" }] : /* istanbul ignore next */ []));
1921
- const destroyRef = inject(DestroyRef);
1922
- const unsubscribe = source.subscribe(() => {
1923
- sig.set(source.getSnapshot());
1924
- });
1925
- destroyRef.onDestroy(() => {
1926
- // `try/finally` guarantees `source.destroy()` runs even if `unsubscribe`
1927
- // throws. Cached sources from `@real-router/sources` keep `destroy()` as
1928
- // a no-op (so they survive multi-consumer teardown), but non-cached
1929
- // sources rely on this call to release their router subscription —
1930
- // skipping it on an unsubscribe throw would leak the listener.
1931
- try {
1932
- unsubscribe();
1933
- }
1934
- finally {
1935
- source.destroy();
1936
- }
1937
- });
1938
- return sig.asReadonly();
798
+ const sig = signal(source.getSnapshot(), ...ngDevMode ? [{ debugName: "sig" }] : /* istanbul ignore next */ []);
799
+ const destroyRef = inject(DestroyRef);
800
+ const unsubscribe = source.subscribe(() => {
801
+ sig.set(source.getSnapshot());
802
+ });
803
+ destroyRef.onDestroy(() => {
804
+ try {
805
+ unsubscribe();
806
+ } finally {
807
+ source.destroy();
808
+ }
809
+ });
810
+ return sig.asReadonly();
1939
811
  }
1940
-
1941
812
  function provideRealRouter(router, options) {
1942
- const navigator = getNavigator(router);
1943
- // `Parameters<typeof makeEnvironmentProviders>[0]` is the actual union
1944
- // `(Provider | EnvironmentProviders | EnvironmentProviders[])[]` —
1945
- // `provideEnvironmentInitializer()` returns `EnvironmentProviders`, so the
1946
- // narrower `Provider[]` would force a cast at every push (review §8a — the
1947
- // proposed Provider[] swap was retracted after discovering this).
1948
- const providers = [
1949
- { provide: ROUTER, useValue: router },
1950
- { provide: NAVIGATOR, useValue: navigator },
1951
- {
1952
- provide: ROUTE,
1953
- useFactory: () => ({
1954
- routeState: sourceToSignal(createRouteSource(router)),
1955
- navigator,
1956
- }),
1957
- },
1958
- // #778 P2: eagerly create the per-router error source at bootstrap so a
1959
- // navigation error that fires BEFORE a RouterErrorBoundary is instantiated
1960
- // (a lazily-rendered shell, a failed boot navigation) is still captured. The
1961
- // boundary's createDismissableError reuses this cached source and catches up
1962
- // (#765); without it the error source is created lazily on boundary init —
1963
- // after the error — and never sees it.
1964
- provideEnvironmentInitializer(() => {
1965
- primeErrorSource(router);
1966
- }),
1967
- ];
1968
- if (options?.scrollRestoration) {
1969
- const scrollOpts = options.scrollRestoration;
1970
- providers.push(provideEnvironmentInitializer(() => {
1971
- installScrollRestoration(scrollOpts);
1972
- }));
1973
- }
1974
- if (options?.scrollSpy && options.scrollSpy.selector !== "") {
1975
- const spyOpts = options.scrollSpy;
1976
- providers.push(provideEnvironmentInitializer(() => {
1977
- installScrollSpy(spyOpts);
1978
- }));
1979
- }
1980
- if (options?.viewTransitions === true) {
1981
- providers.push(provideEnvironmentInitializer(installViewTransitions));
1982
- }
1983
- return makeEnvironmentProviders(providers);
813
+ const navigator = getNavigator(router);
814
+ const providers = [
815
+ {
816
+ provide: ROUTER,
817
+ useValue: router
818
+ },
819
+ {
820
+ provide: NAVIGATOR,
821
+ useValue: navigator
822
+ },
823
+ {
824
+ provide: ROUTE,
825
+ useFactory: () => ({
826
+ routeState: sourceToSignal(createRouteSource(router)),
827
+ navigator
828
+ })
829
+ },
830
+ provideEnvironmentInitializer(() => {
831
+ primeErrorSource(router);
832
+ })
833
+ ];
834
+ if (options?.scrollRestoration) {
835
+ const scrollOpts = options.scrollRestoration;
836
+ providers.push(provideEnvironmentInitializer(() => {
837
+ installScrollRestoration(scrollOpts);
838
+ }));
839
+ }
840
+ if (options?.scrollSpy && options.scrollSpy.selector !== "") {
841
+ const spyOpts = options.scrollSpy;
842
+ providers.push(provideEnvironmentInitializer(() => {
843
+ installScrollSpy(spyOpts);
844
+ }));
845
+ }
846
+ if (options?.viewTransitions === true) providers.push(provideEnvironmentInitializer(installViewTransitions));
847
+ return makeEnvironmentProviders(providers);
1984
848
  }
1985
-
1986
- /**
1987
- * `TransferState` key carrying the SSR-resolved router state from server to
1988
- * client as an XSS-safe JSON string (produced by `serializeRouterState`).
1989
- * Populated server-side by the `provideAppInitializer` callback after
1990
- * `router.start()` resolves; consumed client-side after hydration. Mirrors the
1991
- * `<script>window.__SSR_STATE__ = …</script>` pattern used by every other
1992
- * adapter — Angular's idiomatic transport is `TransferState` (#599).
1993
- *
1994
- * Stored as `string`: `serializeRouterState(state)` already produces JSON;
1995
- * `hydrateRouter(router, json)` accepts a JSON string and parses it once
1996
- * internally. Storing the parsed object would force a double round-trip
1997
- * (TransferState wraps every value in JSON for transport).
1998
- *
1999
- * Internal implementation detail. Not re-exported.
2000
- */
2001
849
  const ROUTER_STATE_KEY = makeStateKey("@real-router/angular:ssrState");
2002
- /**
2003
- * `provideRealRouterFactory` — environment providers for SSR / SSG scenarios.
2004
- *
2005
- * Unlike `provideRealRouter(router)` (single instance via `useValue`), this
2006
- * factory uses `useFactory` to produce a per-request router clone:
2007
- *
2008
- * 1. Reads Angular's `REQUEST` token (`{ optional: true }`).
2009
- * 2. Calls `cloneRouter(baseRouter, deps?.(request))` to create a request-scoped clone.
2010
- * 3. Applies plugins (`plugins` array or `plugins(request)` factory).
2011
- * 4. Registers `provideAppInitializer` that calls `await router.start(url)`.
2012
- * 5. Schedules `router.dispose()` via `DestroyRef.onDestroy` — the request
2013
- * Injector is destroyed after the response is sent, releasing all
2014
- * subscriptions and plugins.
2015
- *
2016
- * Use cases:
2017
- * - Angular SSR with `@angular/ssr` (`outputMode: "server"`).
2018
- * - SSG build-time render via `renderApplication` + `platformProviders` `REQUEST` mock.
2019
- * - Multi-tenant request-scoped routing.
2020
- *
2021
- * Existing single-instance scenarios (SPA, SSG client after hydration) continue
2022
- * to use `provideRealRouter(router)` — both APIs ship in parallel.
2023
- *
2024
- * @param options - Factory configuration — see `RealRouterFactoryOptions`.
2025
- * @returns `EnvironmentProviders` to spread into `ApplicationConfig.providers`.
2026
- */
2027
850
  function provideRealRouterFactory(options) {
2028
- const { baseRouter, plugins, deps, scrollRestoration, scrollSpy, viewTransitions, } = options;
2029
- const providers = [
2030
- {
2031
- provide: ROUTER,
2032
- useFactory: () => {
2033
- const request = inject(REQUEST, { optional: true });
2034
- const requestDeps = deps?.(request);
2035
- const router = cloneRouter(baseRouter, requestDeps);
2036
- const pluginList = typeof plugins === "function" ? plugins(request) : plugins;
2037
- if (pluginList && pluginList.length > 0) {
2038
- // Variadic — `usePlugin` accepts `(PluginFactory<D> | false | null | undefined)[]`.
2039
- router.usePlugin(...pluginList);
2040
- }
2041
- // Per-request cleanup. The application Injector is destroyed:
2042
- // - On server: after `writeResponseToNodeResponse` finishes the response
2043
- // (request scope ends).
2044
- // - On client: at `ApplicationRef.destroy` (rare in SPA, common in TestBed).
2045
- // - In SSG build: after each `renderApplication` resolves.
2046
- inject(DestroyRef).onDestroy(() => {
2047
- router.dispose();
2048
- });
2049
- return router;
2050
- },
2051
- },
2052
- {
2053
- provide: NAVIGATOR,
2054
- useFactory: () => getNavigator(inject(ROUTER)),
2055
- },
2056
- {
2057
- provide: ROUTE,
2058
- useFactory: () => {
2059
- const router = inject(ROUTER);
2060
- return {
2061
- routeState: sourceToSignal(createRouteSource(router)),
2062
- navigator: inject(NAVIGATOR),
2063
- };
2064
- },
2065
- },
2066
- // Async bootstrap — runs before the first component renders. Three
2067
- // branches based on TransferState population:
2068
- //
2069
- // 1. **Client after hydration** — server populated TransferState with
2070
- // the SSR-resolved router state. Consume it via `hydrateRouter`,
2071
- // which deposits the parsed state into `@real-router/ssr-utils`'
2072
- // one-shot scratchpad before invoking
2073
- // `router.start(state.path)`. SSR loader plugins
2074
- // (`@real-router/ssr-data-plugin`, `@real-router/rsc-server-plugin`)
2075
- // read the scratchpad and skip the loader on first paint — parity
2076
- // with the other 5 adapters that consume `<script>__SSR_STATE__</script>` (#596, #599).
2077
- //
2078
- // 2. **Server / SSG** — TransferState empty; run the regular
2079
- // `router.start(path)`. After it resolves, write the serialized
2080
- // state back into TransferState so the matching client run lands
2081
- // in branch 1. Angular's `TransferState` infrastructure
2082
- // (provided by `provideClientHydration()`) carries this blob to
2083
- // the client as a `<script id="ng-state">` payload.
2084
- //
2085
- // 3. **Pure CSR** — TransferState empty (never populated by a server
2086
- // pass), and `inject(REQUEST, { optional: true })` returns null.
2087
- // Falls into the same `router.start(path)` branch as server-side
2088
- // but skips the TransferState write (no client to hand off to).
2089
- //
2090
- // Errors propagate (Option A from RFC §10): the bootstrap fails and the
2091
- // server returns 500. Custom error pages should be wired via
2092
- // `RouterErrorBoundary` on subsequent renders.
2093
- provideAppInitializer(async () => {
2094
- const router = inject(ROUTER);
2095
- // #778 P2 / #1232: eagerly create the per-request error source before the
2096
- // first component renders, so a navigation error that fires AFTER start()
2097
- // but BEFORE a lazily-rendered RouterErrorBoundary mounts is still
2098
- // captured (the boundary's createDismissableError reuses this cached
2099
- // source). Symmetric intent to the SPA `provideRealRouter` prime, but done
2100
- // HERE, not in a `provideEnvironmentInitializer`: the factory's router is
2101
- // lazily cloned via `inject(ROUTER)`, so a clone failure (e.g. a disposed
2102
- // baseRouter) must stay on the async Option-A reject path — an env
2103
- // initializer runs earlier and would surface it as a synchronous bootstrap
2104
- // throw. `primeErrorSource` no-ops on a router with no internals registry,
2105
- // so it is safe on the server clone.
2106
- primeErrorSource(router);
2107
- const request = inject(REQUEST, { optional: true });
2108
- const transferState = inject(TransferState);
2109
- const ssrJson = transferState.get(ROUTER_STATE_KEY, null);
2110
- if (ssrJson !== null) {
2111
- // Branch 1: client after hydration — reuse server-resolved state.
2112
- await hydrateRouter(router, ssrJson);
2113
- // One-shot semantic, parity with `delete window.__SSR_STATE__`.
2114
- transferState.remove(ROUTER_STATE_KEY);
2115
- return;
2116
- }
2117
- // Branches 2 & 3: regular start.
2118
- // Browser-plugin's `start` interceptor (when registered) wraps this call
2119
- // with location-derived path. We always pass an explicit string — the
2120
- // interceptor uses the explicit value because `next(path ?? location)`
2121
- // short-circuits when `path` is non-nullish.
2122
- const path = deriveStartPath(request);
2123
- const state = await router.start(path);
2124
- if (request !== null) {
2125
- // Branch 2: running inside `@angular/ssr`'s request handler — write
2126
- // serialized state to TransferState so the matching client run can
2127
- // skip the loader on first paint.
2128
- transferState.set(ROUTER_STATE_KEY, serializeRouterState(state));
2129
- }
2130
- }),
2131
- ];
2132
- if (scrollRestoration) {
2133
- providers.push(provideEnvironmentInitializer(() => {
2134
- installScrollRestoration(scrollRestoration);
2135
- }));
2136
- }
2137
- if (scrollSpy && scrollSpy.selector !== "") {
2138
- providers.push(provideEnvironmentInitializer(() => {
2139
- installScrollSpy(scrollSpy);
2140
- }));
2141
- }
2142
- if (viewTransitions === true) {
2143
- providers.push(provideEnvironmentInitializer(installViewTransitions));
2144
- }
2145
- return makeEnvironmentProviders(providers);
851
+ const { baseRouter, plugins, deps, scrollRestoration, scrollSpy, viewTransitions } = options;
852
+ const providers = [
853
+ {
854
+ provide: ROUTER,
855
+ useFactory: () => {
856
+ const request = inject(REQUEST, { optional: true });
857
+ const requestDeps = deps?.(request);
858
+ const router = cloneRouter(baseRouter, requestDeps);
859
+ const pluginList = typeof plugins === "function" ? plugins(request) : plugins;
860
+ if (pluginList && pluginList.length > 0) router.usePlugin(...pluginList);
861
+ inject(DestroyRef).onDestroy(() => {
862
+ router.dispose();
863
+ });
864
+ return router;
865
+ }
866
+ },
867
+ {
868
+ provide: NAVIGATOR,
869
+ useFactory: () => getNavigator(inject(ROUTER))
870
+ },
871
+ {
872
+ provide: ROUTE,
873
+ useFactory: () => {
874
+ const router = inject(ROUTER);
875
+ return {
876
+ routeState: sourceToSignal(createRouteSource(router)),
877
+ navigator: inject(NAVIGATOR)
878
+ };
879
+ }
880
+ },
881
+ provideAppInitializer(async () => {
882
+ const router = inject(ROUTER);
883
+ primeErrorSource(router);
884
+ const request = inject(REQUEST, { optional: true });
885
+ const transferState = inject(TransferState);
886
+ const ssrJson = transferState.get(ROUTER_STATE_KEY, null);
887
+ if (ssrJson !== null) {
888
+ await hydrateRouter(router, ssrJson);
889
+ transferState.remove(ROUTER_STATE_KEY);
890
+ return;
891
+ }
892
+ const path = deriveStartPath(request);
893
+ const state = await router.start(path);
894
+ if (request !== null) transferState.set(ROUTER_STATE_KEY, serializeRouterState(state));
895
+ })
896
+ ];
897
+ if (scrollRestoration) providers.push(provideEnvironmentInitializer(() => {
898
+ installScrollRestoration(scrollRestoration);
899
+ }));
900
+ if (scrollSpy && scrollSpy.selector !== "") providers.push(provideEnvironmentInitializer(() => {
901
+ installScrollSpy(scrollSpy);
902
+ }));
903
+ if (viewTransitions === true) providers.push(provideEnvironmentInitializer(installViewTransitions));
904
+ return makeEnvironmentProviders(providers);
2146
905
  }
2147
- /**
2148
- * Derive the path passed to `router.start(path)`:
2149
- * - Server / SSG: `request.url` → pathname + search.
2150
- * - Client: `window.location` if available.
2151
- * - Fallback: `"/"` (only reachable in synthetic non-browser non-SSR setups).
2152
- */
2153
906
  function deriveStartPath(request) {
2154
- if (request) {
2155
- const url = new URL(request.url);
2156
- return url.pathname + url.search;
2157
- }
2158
- if (typeof globalThis.window !== "undefined") {
2159
- return globalThis.location.pathname + globalThis.location.search;
2160
- }
2161
- return "/";
907
+ if (request) {
908
+ const url = new URL(request.url);
909
+ return url.pathname + url.search;
910
+ }
911
+ if (typeof globalThis.window !== "undefined") return globalThis.location.pathname + globalThis.location.search;
912
+ return "/";
2162
913
  }
2163
-
2164
914
  function injectOrThrow(token, fnName) {
2165
- const value = inject(token, { optional: true });
2166
- // Explicit null / undefined check — falsy guard would misfire on
2167
- // legitimately falsy values (`0`, `""`, `false`) if the token were ever
2168
- // typed for primitives. Today all our tokens hold object instances, but
2169
- // pinning the check keeps the function safe for future typing changes.
2170
- if (value === null || value === undefined) {
2171
- throw new Error(`${fnName} must be used within a provideRealRouter context`);
2172
- }
2173
- return value;
915
+ const value = inject(token, { optional: true });
916
+ if (value === null || value === void 0) throw new Error(`${fnName} must be used within a provideRealRouter context`);
917
+ return value;
2174
918
  }
2175
-
2176
919
  function injectRouter() {
2177
- assertInInjectionContext(injectRouter);
2178
- return injectOrThrow(ROUTER, "injectRouter");
920
+ assertInInjectionContext(injectRouter);
921
+ return injectOrThrow(ROUTER, "injectRouter");
2179
922
  }
2180
-
2181
923
  function injectNavigator() {
2182
- assertInInjectionContext(injectNavigator);
2183
- return injectOrThrow(NAVIGATOR, "injectNavigator");
924
+ assertInInjectionContext(injectNavigator);
925
+ return injectOrThrow(NAVIGATOR, "injectNavigator");
2184
926
  }
2185
-
2186
927
  function injectRoute() {
2187
- assertInInjectionContext(injectRoute);
2188
- const signals = injectOrThrow(ROUTE, "injectRoute");
2189
- // Read the snapshot once: the signal is reactive, but the throw-guard
2190
- // and any future use of the snapshot within this call should observe the
2191
- // SAME value to avoid races.
2192
- const snapshot = signals.routeState();
2193
- if (!snapshot.route) {
2194
- throw new Error("injectRoute called with no active route. Did you forget to await router.start() before rendering, or is the router stopped/disposed?");
2195
- }
2196
- // #1466: sync-commit this consumer's route-reactive bindings in the click
2197
- // task. The shared `ROUTE.routeState` signal updates synchronously on every
2198
- // navigation, but a signal read in a template only re-renders on the zoneless
2199
- // scheduler's DEFERRED change-detection flush — a ~0.6-0.9 ms felt-wall gap on
2200
- // route-state displays (`{{ params.id }}`, active-content, route name), the
2201
- // same class the `RouteView` outlet swap hits. The route source notifies
2202
- // synchronously from `router.navigate()` (OUTSIDE Angular CD), so a local
2203
- // `detectChanges()` on the consuming component commits it in-task instead.
2204
- // `createRouteSource` is cached per router (a shared subscription, not a new
2205
- // source); `subscribe` fires on navigations only (not initial), so no
2206
- // in-CD re-entrancy on setup. Optional CDR: `injectRoute` in a non-component
2207
- // (environment) injector keeps its original deferred behaviour. `@angular/router`
2208
- // cannot match this — its route bindings flow through `@Input`/CD.
2209
- const cdr = inject(ChangeDetectorRef, { optional: true });
2210
- if (cdr) {
2211
- const source = createRouteSource(injectRouter());
2212
- const unsub = source.subscribe(() => {
2213
- cdr.detectChanges();
2214
- });
2215
- inject(DestroyRef).onDestroy(() => {
2216
- try {
2217
- unsub();
2218
- }
2219
- finally {
2220
- source.destroy();
2221
- }
2222
- });
2223
- }
2224
- return signals;
928
+ assertInInjectionContext(injectRoute);
929
+ const signals = injectOrThrow(ROUTE, "injectRoute");
930
+ if (!signals.routeState().route) throw new Error("injectRoute called with no active route. Did you forget to await router.start() before rendering, or is the router stopped/disposed?");
931
+ const cdr = inject(ChangeDetectorRef, { optional: true });
932
+ if (cdr) {
933
+ const source = createRouteSource(injectRouter());
934
+ const unsub = source.subscribe(() => {
935
+ cdr.detectChanges();
936
+ });
937
+ inject(DestroyRef).onDestroy(() => {
938
+ try {
939
+ unsub();
940
+ } finally {
941
+ source.destroy();
942
+ }
943
+ });
944
+ }
945
+ return signals;
2225
946
  }
2226
-
2227
947
  function injectRouteNode(nodeName) {
2228
- assertInInjectionContext(injectRouteNode);
2229
- const router = injectRouter();
2230
- const navigator = getNavigator(router);
2231
- const source = createRouteNodeSource(router, nodeName);
2232
- const routeState = sourceToSignal(source);
2233
- // #1466: sync-commit node-state displays in the click task — the node source
2234
- // notifies synchronously (outside Angular CD), so a local `detectChanges()`
2235
- // commits the consumer in-task instead of on the deferred zoneless flush.
2236
- // Mirrors `injectRoute`; the `source` teardown is owned by `sourceToSignal`
2237
- // (cached-source `destroy()` is a no-op), so only the extra listener is
2238
- // unsubscribed here. Optional CDR keeps environment-context usage deferred.
2239
- const cdr = inject(ChangeDetectorRef, { optional: true });
2240
- if (cdr) {
2241
- inject(DestroyRef).onDestroy(source.subscribe(() => {
2242
- cdr.detectChanges();
2243
- }));
2244
- }
2245
- return { routeState, navigator };
948
+ assertInInjectionContext(injectRouteNode);
949
+ const router = injectRouter();
950
+ const navigator = getNavigator(router);
951
+ const source = createRouteNodeSource(router, nodeName);
952
+ const routeState = sourceToSignal(source);
953
+ const cdr = inject(ChangeDetectorRef, { optional: true });
954
+ if (cdr) inject(DestroyRef).onDestroy(source.subscribe(() => {
955
+ cdr.detectChanges();
956
+ }));
957
+ return {
958
+ routeState,
959
+ navigator
960
+ };
2246
961
  }
2247
-
2248
962
  function injectRouteUtils() {
2249
- assertInInjectionContext(injectRouteUtils);
2250
- const router = injectRouter();
2251
- return getRouteUtils(getPluginApi(router).getTree());
963
+ assertInInjectionContext(injectRouteUtils);
964
+ const router = injectRouter();
965
+ return getRouteUtils(getPluginApi(router).getTree());
2252
966
  }
2253
-
2254
967
  function injectRouterTransition() {
2255
- assertInInjectionContext(injectRouterTransition);
2256
- const router = injectRouter();
2257
- const source = getTransitionSource(router);
2258
- return sourceToSignal(source);
968
+ assertInInjectionContext(injectRouterTransition);
969
+ const router = injectRouter();
970
+ return sourceToSignal(getTransitionSource(router));
2259
971
  }
2260
-
2261
972
  function injectIsActiveRoute(routeName, params, search, options) {
2262
- assertInInjectionContext(injectIsActiveRoute);
2263
- const router = injectRouter();
2264
- // Route through the shared fast/slow builder (mirrors RealLink / RealLinkActive):
2265
- // a default-options call (non-empty name, no params, non-strict, query-ignoring, no
2266
- // hash) shares the per-router createActiveNameSelector fast path instead of a
2267
- // dedicated createActiveRouteSource + subscription (#1437). Behavior-identical —
2268
- // createActiveRouteSource normalizes the options internally either way.
2269
- const source = createActiveSource(router, routeName, params, search, options?.strict ?? false, options?.ignoreQueryParams ?? true, options?.hash);
2270
- return sourceToSignal(source);
973
+ assertInInjectionContext(injectIsActiveRoute);
974
+ const router = injectRouter();
975
+ return sourceToSignal(createActiveSource(router, routeName, params, search, options?.strict ?? false, options?.ignoreQueryParams ?? true, options?.hash));
2271
976
  }
2272
-
2273
- /**
2274
- * Subscribe to the router's leave-window with the universal guards baked
2275
- * in. Wraps `router.subscribeLeave` so consumers don't repeat the same
2276
- * boilerplate every time:
2277
- *
2278
- * - **Reentrant abort pre-check**: if `signal.aborted` is already `true`
2279
- * when the handler would run (rapid navigation superseded a slower
2280
- * one), the handler is skipped entirely.
2281
- * - **Same-route skip**: by default, `route.name === nextRoute.name`
2282
- * short-circuits the handler — query-only navigations skip the work.
2283
- * Opt out with `skipSameRoute: false`.
2284
- *
2285
- * Cleanup is bound to the injection context's `DestroyRef`. Must be
2286
- * called within an injection context (constructor, field initializer,
2287
- * or `runInInjectionContext`).
2288
- *
2289
- * If the handler returns a Promise, the router blocks on it. If the
2290
- * Promise resolves, navigation proceeds. If it **rejects**, the router
2291
- * rejects `navigate()` with the handler's **original error** and emits
2292
- * `TRANSITION_ERROR` — it is NOT re-coded to `TRANSITION_CANCELLED` (that
2293
- * arises only when the navigation's `signal` aborts).
2294
- *
2295
- * **Handler reactivity (Angular):** `inject*` functions run **once**
2296
- * during component construction; `handler` is captured in closure at the
2297
- * call site. The common Angular pattern is to pass a class method
2298
- * (`this.onExit.bind(this)` or an arrow-property) — its identity is
2299
- * stable across change detection. To vary behavior over time, read
2300
- * signals **inside** the handler body — do not rely on swapping the
2301
- * handler reference.
2302
- *
2303
- * @example Animation
2304
- * ```ts
2305
- * \@Component({ ... })
2306
- * class FadeOutComponent {
2307
- * private el = inject(ElementRef<HTMLElement>);
2308
- *
2309
- * constructor() {
2310
- * injectRouteExit(async ({ signal }) => {
2311
- * const el = this.el.nativeElement;
2312
- * el.classList.add("fade-out");
2313
- * const cleanup = () => el.classList.remove("fade-out");
2314
- * signal.addEventListener("abort", cleanup, { once: true });
2315
- * try {
2316
- * el.getBoundingClientRect();
2317
- * await Promise.allSettled(el.getAnimations().map((a) => a.finished));
2318
- * } finally {
2319
- * cleanup();
2320
- * }
2321
- * });
2322
- * }
2323
- * }
2324
- * ```
2325
- *
2326
- * @example Auto-save form draft
2327
- * ```ts
2328
- * injectRouteExit(async ({ signal }) => {
2329
- * if (this.formState.dirty) {
2330
- * await this.api.saveDraft(this.formState, { signal });
2331
- * }
2332
- * });
2333
- * ```
2334
- */
2335
977
  function injectRouteExit(handler, options) {
2336
- assertInInjectionContext(injectRouteExit);
2337
- const router = injectRouter();
2338
- const destroyRef = inject(DestroyRef);
2339
- const skipSameRoute = options?.skipSameRoute ?? true;
2340
- // The same-route + reentrant-abort guards and the Promise passthrough live in
2341
- // the shared listener (@real-router/sources, #1435); the handler is captured
2342
- // at injection time (Angular `inject*` runs once at construction).
2343
- const off = router.subscribeLeave(guardLeaveListener(handler, { skipSameRoute }));
2344
- destroyRef.onDestroy(off);
978
+ assertInInjectionContext(injectRouteExit);
979
+ const router = injectRouter();
980
+ const destroyRef = inject(DestroyRef);
981
+ const skipSameRoute = options?.skipSameRoute ?? true;
982
+ const off = router.subscribeLeave(guardLeaveListener(handler, { skipSameRoute }));
983
+ destroyRef.onDestroy(off);
2345
984
  }
2346
-
2347
- /**
2348
- * Fire `handler` once when the component is created as a result of a
2349
- * navigation. Mirror of `injectRouteExit` for the entry side.
2350
- *
2351
- * What this function covers that an ad-hoc `effect()` + `injectRoute()`
2352
- * doesn't:
2353
- *
2354
- * - **Skip-initial**: handler is skipped when there is no
2355
- * `route.transition.from` (i.e. first-load mount). Most consumers
2356
- * want to fire side effects only on real navigations, not on
2357
- * hydration.
2358
- * - **Same-route skip** (default): handler is skipped when
2359
- * `route.transition.from === route.name`. Sort/filter/query-only
2360
- * navigations re-run the effect (because the `route` reference
2361
- * changes), but they are not "entries" in the animation / analytics
2362
- * sense. Opt out with `skipSameRoute: false`.
2363
- * - **Mount-time `route` / `previousRoute` snapshot**: handler receives
2364
- * the values that were live at the moment of effect activation.
2365
- *
2366
- * Effect cleanup is wired through the injection context's `DestroyRef`
2367
- * (Angular's `effect()` ties into the active context automatically).
2368
- * Must be called within an injection context (constructor, field
2369
- * initializer, or `runInInjectionContext`).
2370
- *
2371
- * **Handler reactivity (Angular):** `inject*` functions run **once**
2372
- * during component construction; `handler` is captured in closure at the
2373
- * call site. The common Angular pattern is to pass a class method —
2374
- * its identity is stable across change detection. To vary behavior
2375
- * over time, read signals **inside** the handler body.
2376
- *
2377
- * @example Direction-aware entry animation
2378
- * ```ts
2379
- * \@Component({ ... })
2380
- * class PageComponent {
2381
- * private el = inject(ElementRef<HTMLElement>);
2382
- *
2383
- * constructor() {
2384
- * injectRouteEnter(({ route }) => {
2385
- * const direction = route.context.browser?.direction;
2386
- * this.el.nativeElement.classList.add(
2387
- * direction === "back" ? "slide-from-left" : "slide-from-right",
2388
- * );
2389
- * });
2390
- * }
2391
- * }
2392
- * ```
2393
- *
2394
- * @example Analytics page-enter event (skip-initial built-in)
2395
- * ```ts
2396
- * injectRouteEnter(({ route, previousRoute }) => {
2397
- * analytics.track("page_enter", {
2398
- * route: route.name,
2399
- * from: previousRoute.name,
2400
- * });
2401
- * });
2402
- * ```
2403
- */
2404
985
  function injectRouteEnter(handler, options) {
2405
- assertInInjectionContext(injectRouteEnter);
2406
- const { routeState } = injectRoute();
2407
- const skipSameRoute = options?.skipSameRoute ?? true;
2408
- // The canonical enter-guard set lives in the shared gate (@real-router/
2409
- // sources, #1435). Angular `inject*` runs once at construction, so a plain
2410
- // const holds the gate. The gate owns skip-initial / same-route / the
2411
- // `!previousRoute` guard (the sole defense of the non-nullable
2412
- // `RouteEnterContext.previousRoute` contract) plus a StrictMode dedupe arm —
2413
- // a defensive no-op in Angular (the effect below only re-runs on a fresh
2414
- // `route` reference; see the `untracked` note), kept for parity with React and
2415
- // tested once in sources, so no per-adapter v8-ignore is needed.
2416
- const gate = createRouteEnterGate();
2417
- effect(() => {
2418
- const { route, previousRoute } = routeState();
2419
- const context = gate(route, previousRoute, skipSameRoute);
2420
- if (context) {
2421
- // `untracked`: scope this effect's dependencies to `routeState()` alone.
2422
- // Angular's `effect()` tracks signals read inside a synchronously-called
2423
- // function, so WITHOUT this a handler-read signal changing (no navigation)
2424
- // would re-run the effect and — pre-#1435 — re-fire the enter handler (a
2425
- // spurious re-fire vs the "fire once per nav-driven mount" contract). With
2426
- // the dispatch untracked the effect re-runs only on real navigations (a
2427
- // fresh `route` reference each time), so the handler fires once per mount —
2428
- // Angular parity with the other five adapters (empirically confirmed
2429
- // 2026-07-17). A small beneficial BEHAVIOR change, not behavior-neutral
2430
- // (hence the `minor` bump).
2431
- untracked(() => {
2432
- handler(context);
2433
- });
2434
- }
2435
- });
986
+ assertInInjectionContext(injectRouteEnter);
987
+ const { routeState } = injectRoute();
988
+ const skipSameRoute = options?.skipSameRoute ?? true;
989
+ const gate = createRouteEnterGate();
990
+ effect(() => {
991
+ const { route, previousRoute } = routeState();
992
+ const context = gate(route, previousRoute, skipSameRoute);
993
+ if (context) untracked(() => {
994
+ handler(context);
995
+ });
996
+ });
2436
997
  }
2437
-
2438
- class RouteMatch {
2439
- routeMatch = input.required(/* @ts-ignore */
2440
- ...(ngDevMode ? [{ debugName: "routeMatch" }] : /* istanbul ignore next */ []));
2441
- templateRef = inject(TemplateRef);
2442
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: RouteMatch, deps: [], target: i0.ɵɵFactoryTarget.Directive });
2443
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.1.6", type: RouteMatch, isStandalone: true, selector: "ng-template[routeMatch]", inputs: { routeMatch: { classPropertyName: "routeMatch", publicName: "routeMatch", isSignal: true, isRequired: true, transformFunction: null } }, ngImport: i0 });
2444
- }
2445
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: RouteMatch, decorators: [{
2446
- type: Directive,
2447
- args: [{ selector: "ng-template[routeMatch]" }]
2448
- }], propDecorators: { routeMatch: [{ type: i0.Input, args: [{ isSignal: true, alias: "routeMatch", required: true }] }] } });
2449
-
2450
- class RouteNotFound {
2451
- templateRef = inject(TemplateRef);
2452
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: RouteNotFound, deps: [], target: i0.ɵɵFactoryTarget.Directive });
2453
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "22.1.6", type: RouteNotFound, isStandalone: true, selector: "ng-template[routeNotFound]", ngImport: i0 });
2454
- }
2455
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: RouteNotFound, decorators: [{
2456
- type: Directive,
2457
- args: [{ selector: "ng-template[routeNotFound]" }]
2458
- }] });
2459
-
2460
- class RouteSelf {
2461
- templateRef = inject(TemplateRef);
2462
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: RouteSelf, deps: [], target: i0.ɵɵFactoryTarget.Directive });
2463
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "22.1.6", type: RouteSelf, isStandalone: true, selector: "ng-template[routeSelf]", ngImport: i0 });
2464
- }
2465
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: RouteSelf, decorators: [{
2466
- type: Directive,
2467
- args: [{ selector: "ng-template[routeSelf]" }]
2468
- }] });
2469
-
998
+ var RouteMatch = class RouteMatch {
999
+ routeMatch = input.required(...ngDevMode ? [{ debugName: "routeMatch" }] : /* istanbul ignore next */ []);
1000
+ templateRef = inject(TemplateRef);
1001
+ static ɵfac = i0.ɵɵngDeclareFactory({
1002
+ minVersion: "12.0.0",
1003
+ version: "22.2.0",
1004
+ ngImport: i0,
1005
+ type: RouteMatch,
1006
+ deps: [],
1007
+ target: i0.ɵɵFactoryTarget.Directive
1008
+ });
1009
+ static ɵdir = i0.ɵɵngDeclareDirective({
1010
+ minVersion: "17.1.0",
1011
+ version: "22.2.0",
1012
+ type: RouteMatch,
1013
+ isStandalone: true,
1014
+ selector: "ng-template[routeMatch]",
1015
+ inputs: { routeMatch: {
1016
+ classPropertyName: "routeMatch",
1017
+ publicName: "routeMatch",
1018
+ isSignal: true,
1019
+ isRequired: true,
1020
+ transformFunction: null
1021
+ } },
1022
+ ngImport: i0
1023
+ });
1024
+ };
1025
+ i0.ɵɵngDeclareClassMetadata({
1026
+ minVersion: "12.0.0",
1027
+ version: "22.2.0",
1028
+ ngImport: i0,
1029
+ type: RouteMatch,
1030
+ decorators: [{
1031
+ type: Directive,
1032
+ args: [{ selector: "ng-template[routeMatch]" }]
1033
+ }],
1034
+ propDecorators: { routeMatch: [{
1035
+ type: i0.Input,
1036
+ args: [{
1037
+ isSignal: true,
1038
+ alias: "routeMatch",
1039
+ required: true
1040
+ }]
1041
+ }] }
1042
+ });
1043
+ var RouteNotFound = class RouteNotFound {
1044
+ templateRef = inject(TemplateRef);
1045
+ static ɵfac = i0.ɵɵngDeclareFactory({
1046
+ minVersion: "12.0.0",
1047
+ version: "22.2.0",
1048
+ ngImport: i0,
1049
+ type: RouteNotFound,
1050
+ deps: [],
1051
+ target: i0.ɵɵFactoryTarget.Directive
1052
+ });
1053
+ static ɵdir = i0.ɵɵngDeclareDirective({
1054
+ minVersion: "14.0.0",
1055
+ version: "22.2.0",
1056
+ type: RouteNotFound,
1057
+ isStandalone: true,
1058
+ selector: "ng-template[routeNotFound]",
1059
+ ngImport: i0
1060
+ });
1061
+ };
1062
+ i0.ɵɵngDeclareClassMetadata({
1063
+ minVersion: "12.0.0",
1064
+ version: "22.2.0",
1065
+ ngImport: i0,
1066
+ type: RouteNotFound,
1067
+ decorators: [{
1068
+ type: Directive,
1069
+ args: [{ selector: "ng-template[routeNotFound]" }]
1070
+ }]
1071
+ });
1072
+ var RouteSelf = class RouteSelf {
1073
+ templateRef = inject(TemplateRef);
1074
+ static ɵfac = i0.ɵɵngDeclareFactory({
1075
+ minVersion: "12.0.0",
1076
+ version: "22.2.0",
1077
+ ngImport: i0,
1078
+ type: RouteSelf,
1079
+ deps: [],
1080
+ target: i0.ɵɵFactoryTarget.Directive
1081
+ });
1082
+ static ɵdir = i0.ɵɵngDeclareDirective({
1083
+ minVersion: "14.0.0",
1084
+ version: "22.2.0",
1085
+ type: RouteSelf,
1086
+ isStandalone: true,
1087
+ selector: "ng-template[routeSelf]",
1088
+ ngImport: i0
1089
+ });
1090
+ };
1091
+ i0.ɵɵngDeclareClassMetadata({
1092
+ minVersion: "12.0.0",
1093
+ version: "22.2.0",
1094
+ ngImport: i0,
1095
+ type: RouteSelf,
1096
+ decorators: [{
1097
+ type: Directive,
1098
+ args: [{ selector: "ng-template[routeSelf]" }]
1099
+ }]
1100
+ });
2470
1101
  const EMPTY_SNAPSHOT = {
2471
- route: undefined,
2472
- previousRoute: undefined,
1102
+ route: void 0,
1103
+ previousRoute: void 0
2473
1104
  };
2474
- class RouteView {
2475
- nodeName = input("", { ...(ngDevMode ? { debugName: "nodeName" } : /* istanbul ignore next */ {}), alias: "routeNode" });
2476
- matches = contentChildren(RouteMatch, { ...(ngDevMode ? { debugName: "matches" } : /* istanbul ignore next */ {}), descendants: true });
2477
- selfs = contentChildren(RouteSelf, { ...(ngDevMode ? { debugName: "selfs" } : /* istanbul ignore next */ {}), descendants: true });
2478
- notFounds = contentChildren(RouteNotFound, { ...(ngDevMode ? { debugName: "notFounds" } : /* istanbul ignore next */ {}), descendants: true });
2479
- activeTemplate = computed(() => this.matchedTemplate() ?? this.fallbackTemplate(), /* @ts-ignore */
2480
- ...(ngDevMode ? [{ debugName: "activeTemplate" }] : /* istanbul ignore next */ []));
2481
- router = injectRouter();
2482
- cdr = inject(ChangeDetectorRef);
2483
- routeState = signal(EMPTY_SNAPSHOT, /* @ts-ignore */
2484
- ...(ngDevMode ? [{ debugName: "routeState" }] : /* istanbul ignore next */ []));
2485
- matchEntries = computed(() => {
2486
- const nodeName = this.nodeName();
2487
- return this.matches().map((match) => {
2488
- const segment = match.routeMatch();
2489
- return {
2490
- match,
2491
- fullSegmentName: nodeName ? `${nodeName}.${segment}` : segment,
2492
- };
2493
- });
2494
- }, /* @ts-ignore */
2495
- ...(ngDevMode ? [{ debugName: "matchEntries" }] : /* istanbul ignore next */ []));
2496
- // The matched template (Match priority) is independent of the Self /
2497
- // NotFound fallback chain. Splitting the two paths into separate computeds
2498
- // localises re-runs: a change to `selfs()` / `notFounds()` no longer
2499
- // re-evaluates the Match loop (review §8a LOW — RouteView activeTemplate
2500
- // split).
2501
- matchedTemplate = computed(() => {
2502
- const route = this.routeState().route;
2503
- if (!route) {
2504
- return null;
2505
- }
2506
- const routeName = route.name;
2507
- for (const { match, fullSegmentName } of this.matchEntries()) {
2508
- if (startsWithSegment(routeName, fullSegmentName)) {
2509
- return match.templateRef;
2510
- }
2511
- }
2512
- return null;
2513
- }, /* @ts-ignore */
2514
- ...(ngDevMode ? [{ debugName: "matchedTemplate" }] : /* istanbul ignore next */ []));
2515
- // Fallback chain — only consulted when `matchedTemplate()` returned `null`.
2516
- // Template priority: Self → NotFound. Both use **first-wins** (`.at(0)`) for
2517
- // parity with React / Preact / Solid / Vue (#1439): the first matching
2518
- // `<ng-template routeSelf>` / `<ng-template routeNotFound>` token in
2519
- // declaration order wins; later duplicates are ignored. `contentChildren`
2520
- // resolves matched directives in DOM/source order, so `.at(0)` is the
2521
- // first-declared marker.
2522
- fallbackTemplate = computed(() => {
2523
- const route = this.routeState().route;
2524
- if (!route) {
2525
- return null;
2526
- }
2527
- const routeName = route.name;
2528
- // The Self/NotFound fallback resolution reads contentChildren(RouteSelf /
2529
- // RouteNotFound) — signal queries that only register under a compiler
2530
- // transform, so the jit test project leaves them empty and these guarded
2531
- // `.at(0)` returns are unreachable there (CLAUDE.md "Coverage Ceiling").
2532
- // They ARE executed and asserted by the AOT test project
2533
- // (`tests/aot/routeview-fallback.aot.test.ts`, #1512), including the
2534
- // #1439 first-wins order (`.at(0)` = first-declared, parity with Match).
2535
- if (routeName === this.nodeName()) {
2536
- const first = this.selfs().at(0);
2537
- if (first) {
2538
- return first.templateRef;
2539
- }
2540
- }
2541
- if (routeName === UNKNOWN_ROUTE) {
2542
- const first = this.notFounds().at(0);
2543
- if (first) {
2544
- return first.templateRef;
2545
- }
2546
- }
2547
- return null;
2548
- }, /* @ts-ignore */
2549
- ...(ngDevMode ? [{ debugName: "fallbackTemplate" }] : /* istanbul ignore next */ []));
2550
- constructor() {
2551
- // Reactive source-creation effect (#630 fix) — see
2552
- // `packages/angular/CLAUDE.md` → "Directives use constructor + effect()".
2553
- effect((onCleanup) => {
2554
- const source = createRouteNodeSource(this.router, this.nodeName());
2555
- // Initial snapshot — applied during the effect's first flush (inside
2556
- // Angular's change detection), so set the signal ONLY. A re-entrant
2557
- // detectChanges() here would throw.
2558
- this.routeState.set(source.getSnapshot());
2559
- const unsub = source.subscribe(() => {
2560
- this.routeState.set(source.getSnapshot());
2561
- // #1466: commit the `ngTemplateOutlet` swap SYNCHRONOUSLY. The route
2562
- // source notifies in the click task, but the template
2563
- // `@if (activeTemplate())` only re-renders on a change-detection pass,
2564
- // which zoneless Angular schedules asynchronously — a ~0.85 ms idle
2565
- // felt-wall gap where `@angular/router` activates its outlet in-task.
2566
- // The source callback fires from `router.navigate()` (OUTSIDE Angular
2567
- // CD), so a local `detectChanges()` is safe here and materialises the
2568
- // route DOM now, collapsing the gap. Mirrors `RealLink`'s direct-DOM
2569
- // write — both bypass the deferred scheduler flush for a same-task commit.
2570
- this.cdr.detectChanges();
2571
- });
2572
- onCleanup(() => {
2573
- unsub();
2574
- source.destroy();
2575
- });
2576
- });
2577
- }
2578
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: RouteView, deps: [], target: i0.ɵɵFactoryTarget.Component });
2579
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.6", type: RouteView, isStandalone: true, selector: "route-view", inputs: { nodeName: { classPropertyName: "nodeName", publicName: "routeNode", isSignal: true, isRequired: false, transformFunction: null } }, queries: [{ propertyName: "matches", predicate: RouteMatch, descendants: true, isSignal: true }, { propertyName: "selfs", predicate: RouteSelf, descendants: true, isSignal: true }, { propertyName: "notFounds", predicate: RouteNotFound, descendants: true, isSignal: true }], ngImport: i0, template: `
1105
+ var RouteView = class RouteView {
1106
+ nodeName = input("", {
1107
+ ...ngDevMode ? { debugName: "nodeName" } : /* istanbul ignore next */ {},
1108
+ alias: "routeNode"
1109
+ });
1110
+ matches = contentChildren(RouteMatch, {
1111
+ ...ngDevMode ? { debugName: "matches" } : /* istanbul ignore next */ {},
1112
+ descendants: true
1113
+ });
1114
+ selfs = contentChildren(RouteSelf, {
1115
+ ...ngDevMode ? { debugName: "selfs" } : /* istanbul ignore next */ {},
1116
+ descendants: true
1117
+ });
1118
+ notFounds = contentChildren(RouteNotFound, {
1119
+ ...ngDevMode ? { debugName: "notFounds" } : /* istanbul ignore next */ {},
1120
+ descendants: true
1121
+ });
1122
+ activeTemplate = computed(() => this.matchedTemplate() ?? this.fallbackTemplate(), ...ngDevMode ? [{ debugName: "activeTemplate" }] : /* istanbul ignore next */ []);
1123
+ router = injectRouter();
1124
+ cdr = inject(ChangeDetectorRef);
1125
+ routeState = signal(EMPTY_SNAPSHOT, ...ngDevMode ? [{ debugName: "routeState" }] : /* istanbul ignore next */ []);
1126
+ matchEntries = computed(() => {
1127
+ const nodeName = this.nodeName();
1128
+ return this.matches().map((match) => {
1129
+ const segment = match.routeMatch();
1130
+ return {
1131
+ match,
1132
+ fullSegmentName: nodeName ? `${nodeName}.${segment}` : segment
1133
+ };
1134
+ });
1135
+ }, ...ngDevMode ? [{ debugName: "matchEntries" }] : /* istanbul ignore next */ []);
1136
+ matchedTemplate = computed(() => {
1137
+ const route = this.routeState().route;
1138
+ if (!route) return null;
1139
+ const routeName = route.name;
1140
+ for (const { match, fullSegmentName } of this.matchEntries()) if (startsWithSegment(routeName, fullSegmentName)) return match.templateRef;
1141
+ return null;
1142
+ }, ...ngDevMode ? [{ debugName: "matchedTemplate" }] : /* istanbul ignore next */ []);
1143
+ fallbackTemplate = computed(() => {
1144
+ const route = this.routeState().route;
1145
+ if (!route) return null;
1146
+ const routeName = route.name;
1147
+ if (routeName === this.nodeName()) {
1148
+ const first = this.selfs().at(0);
1149
+ if (first) return first.templateRef;
1150
+ }
1151
+ if (routeName === UNKNOWN_ROUTE) {
1152
+ const first = this.notFounds().at(0);
1153
+ if (first) return first.templateRef;
1154
+ }
1155
+ return null;
1156
+ }, ...ngDevMode ? [{ debugName: "fallbackTemplate" }] : /* istanbul ignore next */ []);
1157
+ constructor() {
1158
+ effect((onCleanup) => {
1159
+ const source = createRouteNodeSource(this.router, this.nodeName());
1160
+ this.routeState.set(source.getSnapshot());
1161
+ const unsub = source.subscribe(() => {
1162
+ this.routeState.set(source.getSnapshot());
1163
+ this.cdr.detectChanges();
1164
+ });
1165
+ onCleanup(() => {
1166
+ unsub();
1167
+ source.destroy();
1168
+ });
1169
+ });
1170
+ }
1171
+ static ɵfac = i0.ɵɵngDeclareFactory({
1172
+ minVersion: "12.0.0",
1173
+ version: "22.2.0",
1174
+ ngImport: i0,
1175
+ type: RouteView,
1176
+ deps: [],
1177
+ target: i0.ɵɵFactoryTarget.Component
1178
+ });
1179
+ static ɵcmp = i0.ɵɵngDeclareComponent({
1180
+ minVersion: "17.0.0",
1181
+ version: "22.2.0",
1182
+ type: RouteView,
1183
+ isStandalone: true,
1184
+ selector: "route-view",
1185
+ inputs: { nodeName: {
1186
+ classPropertyName: "nodeName",
1187
+ publicName: "routeNode",
1188
+ isSignal: true,
1189
+ isRequired: false,
1190
+ transformFunction: null
1191
+ } },
1192
+ queries: [
1193
+ {
1194
+ propertyName: "matches",
1195
+ predicate: RouteMatch,
1196
+ descendants: true,
1197
+ isSignal: true
1198
+ },
1199
+ {
1200
+ propertyName: "selfs",
1201
+ predicate: RouteSelf,
1202
+ descendants: true,
1203
+ isSignal: true
1204
+ },
1205
+ {
1206
+ propertyName: "notFounds",
1207
+ predicate: RouteNotFound,
1208
+ descendants: true,
1209
+ isSignal: true
1210
+ }
1211
+ ],
1212
+ ngImport: i0,
1213
+ template: `
2580
1214
  @if (activeTemplate()) {
2581
1215
  <ng-container [ngTemplateOutlet]="activeTemplate()!" />
2582
1216
  }
2583
- `, isInline: true, dependencies: [{ kind: "directive", type: NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }] });
2584
- }
2585
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: RouteView, decorators: [{
2586
- type: Component,
2587
- args: [{
2588
- selector: "route-view",
2589
- template: `
1217
+ `,
1218
+ isInline: true,
1219
+ dependencies: [{
1220
+ kind: "directive",
1221
+ type: NgTemplateOutlet,
1222
+ selector: "[ngTemplateOutlet]",
1223
+ inputs: [
1224
+ "ngTemplateOutletContext",
1225
+ "ngTemplateOutlet",
1226
+ "ngTemplateOutletInjector"
1227
+ ]
1228
+ }]
1229
+ });
1230
+ };
1231
+ i0.ɵɵngDeclareClassMetadata({
1232
+ minVersion: "12.0.0",
1233
+ version: "22.2.0",
1234
+ ngImport: i0,
1235
+ type: RouteView,
1236
+ decorators: [{
1237
+ type: Component,
1238
+ args: [{
1239
+ selector: "route-view",
1240
+ template: `
2590
1241
  @if (activeTemplate()) {
2591
1242
  <ng-container [ngTemplateOutlet]="activeTemplate()!" />
2592
1243
  }
2593
1244
  `,
2594
- imports: [NgTemplateOutlet],
2595
- }]
2596
- }], ctorParameters: () => [], propDecorators: { nodeName: [{ type: i0.Input, args: [{ isSignal: true, alias: "routeNode", required: false }] }], matches: [{ type: i0.ContentChildren, args: [i0.forwardRef(() => RouteMatch), { ...{ descendants: true }, isSignal: true }] }], selfs: [{ type: i0.ContentChildren, args: [i0.forwardRef(() => RouteSelf), { ...{ descendants: true }, isSignal: true }] }], notFounds: [{ type: i0.ContentChildren, args: [i0.forwardRef(() => RouteNotFound), { ...{ descendants: true }, isSignal: true }] }] } });
2597
-
2598
- class RouterErrorBoundary {
2599
- errorTemplate = input(/* @ts-ignore */
2600
- ...(ngDevMode ? [undefined, { debugName: "errorTemplate" }] : /* istanbul ignore next */ []));
2601
- onError = output();
2602
- errorContext = computed(() => {
2603
- const snap = this.snapshot();
2604
- if (!snap.error) {
2605
- return null;
2606
- }
2607
- return {
2608
- $implicit: snap.error,
2609
- resetError: snap.resetError,
2610
- };
2611
- }, /* @ts-ignore */
2612
- ...(ngDevMode ? [{ debugName: "errorContext" }] : /* istanbul ignore next */ []));
2613
- router = injectRouter();
2614
- snapshot = sourceToSignal(createDismissableError(this.router));
2615
- constructor() {
2616
- // `effect()` registers itself with the current injection context's
2617
- // `DestroyRef` and tears down automatically when the component is
2618
- // destroyed. The earlier manual `effectRef.destroy()` wired through
2619
- // `inject(DestroyRef).onDestroy(...)` duplicated that built-in cleanup
2620
- // (audit §8.1 LOW — confirmed: no behavior change without the manual
2621
- // path).
2622
- effect(() => {
2623
- const snap = this.snapshot();
2624
- if (snap.error) {
2625
- this.onError.emit({
2626
- error: snap.error,
2627
- toRoute: snap.toRoute,
2628
- fromRoute: snap.fromRoute,
2629
- });
2630
- }
2631
- });
2632
- }
2633
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: RouterErrorBoundary, deps: [], target: i0.ɵɵFactoryTarget.Component });
2634
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "22.1.6", type: RouterErrorBoundary, isStandalone: true, selector: "router-error-boundary", inputs: { errorTemplate: { classPropertyName: "errorTemplate", publicName: "errorTemplate", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { onError: "onError" }, ngImport: i0, template: `
1245
+ imports: [NgTemplateOutlet]
1246
+ }]
1247
+ }],
1248
+ ctorParameters: () => [],
1249
+ propDecorators: {
1250
+ nodeName: [{
1251
+ type: i0.Input,
1252
+ args: [{
1253
+ isSignal: true,
1254
+ alias: "routeNode",
1255
+ required: false
1256
+ }]
1257
+ }],
1258
+ matches: [{
1259
+ type: i0.ContentChildren,
1260
+ args: [i0.forwardRef(() => RouteMatch), {
1261
+ descendants: true,
1262
+ isSignal: true
1263
+ }]
1264
+ }],
1265
+ selfs: [{
1266
+ type: i0.ContentChildren,
1267
+ args: [i0.forwardRef(() => RouteSelf), {
1268
+ descendants: true,
1269
+ isSignal: true
1270
+ }]
1271
+ }],
1272
+ notFounds: [{
1273
+ type: i0.ContentChildren,
1274
+ args: [i0.forwardRef(() => RouteNotFound), {
1275
+ descendants: true,
1276
+ isSignal: true
1277
+ }]
1278
+ }]
1279
+ }
1280
+ });
1281
+ var RouterErrorBoundary = class RouterErrorBoundary {
1282
+ errorTemplate = input(...ngDevMode ? [void 0, { debugName: "errorTemplate" }] : /* istanbul ignore next */ []);
1283
+ onError = output();
1284
+ errorContext = computed(() => {
1285
+ const snap = this.snapshot();
1286
+ if (!snap.error) return null;
1287
+ return {
1288
+ $implicit: snap.error,
1289
+ resetError: snap.resetError
1290
+ };
1291
+ }, ...ngDevMode ? [{ debugName: "errorContext" }] : /* istanbul ignore next */ []);
1292
+ router = injectRouter();
1293
+ snapshot = sourceToSignal(createDismissableError(this.router));
1294
+ constructor() {
1295
+ effect(() => {
1296
+ const snap = this.snapshot();
1297
+ if (snap.error) this.onError.emit({
1298
+ error: snap.error,
1299
+ toRoute: snap.toRoute,
1300
+ fromRoute: snap.fromRoute
1301
+ });
1302
+ });
1303
+ }
1304
+ static ɵfac = i0.ɵɵngDeclareFactory({
1305
+ minVersion: "12.0.0",
1306
+ version: "22.2.0",
1307
+ ngImport: i0,
1308
+ type: RouterErrorBoundary,
1309
+ deps: [],
1310
+ target: i0.ɵɵFactoryTarget.Component
1311
+ });
1312
+ static ɵcmp = i0.ɵɵngDeclareComponent({
1313
+ minVersion: "17.0.0",
1314
+ version: "22.2.0",
1315
+ type: RouterErrorBoundary,
1316
+ isStandalone: true,
1317
+ selector: "router-error-boundary",
1318
+ inputs: { errorTemplate: {
1319
+ classPropertyName: "errorTemplate",
1320
+ publicName: "errorTemplate",
1321
+ isSignal: true,
1322
+ isRequired: false,
1323
+ transformFunction: null
1324
+ } },
1325
+ outputs: { onError: "onError" },
1326
+ ngImport: i0,
1327
+ template: `
2635
1328
  <ng-content />
2636
1329
  @if (errorContext() && errorTemplate()) {
2637
1330
  <ng-container
@@ -2639,13 +1332,30 @@ class RouterErrorBoundary {
2639
1332
  [ngTemplateOutletContext]="errorContext()!"
2640
1333
  />
2641
1334
  }
2642
- `, isInline: true, dependencies: [{ kind: "directive", type: NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }] });
2643
- }
2644
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: RouterErrorBoundary, decorators: [{
2645
- type: Component,
2646
- args: [{
2647
- selector: "router-error-boundary",
2648
- template: `
1335
+ `,
1336
+ isInline: true,
1337
+ dependencies: [{
1338
+ kind: "directive",
1339
+ type: NgTemplateOutlet,
1340
+ selector: "[ngTemplateOutlet]",
1341
+ inputs: [
1342
+ "ngTemplateOutletContext",
1343
+ "ngTemplateOutlet",
1344
+ "ngTemplateOutletInjector"
1345
+ ]
1346
+ }]
1347
+ });
1348
+ };
1349
+ i0.ɵɵngDeclareClassMetadata({
1350
+ minVersion: "12.0.0",
1351
+ version: "22.2.0",
1352
+ ngImport: i0,
1353
+ type: RouterErrorBoundary,
1354
+ decorators: [{
1355
+ type: Component,
1356
+ args: [{
1357
+ selector: "router-error-boundary",
1358
+ template: `
2649
1359
  <ng-content />
2650
1360
  @if (errorContext() && errorTemplate()) {
2651
1361
  <ng-container
@@ -2654,354 +1364,491 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.6", ngImpor
2654
1364
  />
2655
1365
  }
2656
1366
  `,
2657
- imports: [NgTemplateOutlet],
2658
- }]
2659
- }], ctorParameters: () => [], propDecorators: { errorTemplate: [{ type: i0.Input, args: [{ isSignal: true, alias: "errorTemplate", required: false }] }], onError: [{ type: i0.Output, args: ["onError"] }] } });
2660
-
2661
- class NavigationAnnouncer {
2662
- /**
2663
- * Optional announcer customization — mirrors the `announceNavigation`
2664
- * options exposed by the react/preact/vue/solid/svelte adapters.
2665
- * `prefix` overrides the default `"Navigated to "`; `getAnnouncementText`
2666
- * computes the full announcement from the resolved route (falling back to
2667
- * the default `h1 → title → route-name` chain on empty/throw). Read once in
2668
- * `ngOnInit` — after the input bindings have fired — because signal inputs
2669
- * are not yet bound at field-initialization time (same pattern as the SSR
2670
- * `<http-status-code>` component).
2671
- */
2672
- prefix = input(/* @ts-ignore */
2673
- ...(ngDevMode ? [undefined, { debugName: "prefix" }] : /* istanbul ignore next */ []));
2674
- getAnnouncementText = input(/* @ts-ignore */
2675
- ...(ngDevMode ? [undefined, { debugName: "getAnnouncementText" }] : /* istanbul ignore next */ []));
2676
- router = injectRouter();
2677
- announcer;
2678
- constructor() {
2679
- inject(DestroyRef).onDestroy(() => {
2680
- this.announcer?.destroy();
2681
- });
2682
- }
2683
- ngOnInit() {
2684
- const prefix = this.prefix();
2685
- const getAnnouncementText = this.getAnnouncementText();
2686
- // Build the options object omitting unset fields so it stays assignable to
2687
- // `RouteAnnouncerOptions` under exactOptionalPropertyTypes (`{ prefix:
2688
- // undefined }` is rejected). An empty object is equivalent to no options.
2689
- const options = {
2690
- ...(prefix !== undefined && { prefix }),
2691
- ...(getAnnouncementText !== undefined && { getAnnouncementText }),
2692
- };
2693
- this.announcer = createRouteAnnouncer(this.router, options);
2694
- }
2695
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: NavigationAnnouncer, deps: [], target: i0.ɵɵFactoryTarget.Component });
2696
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "22.1.6", type: NavigationAnnouncer, isStandalone: true, selector: "navigation-announcer", inputs: { prefix: { classPropertyName: "prefix", publicName: "prefix", isSignal: true, isRequired: false, transformFunction: null }, getAnnouncementText: { classPropertyName: "getAnnouncementText", publicName: "getAnnouncementText", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0, template: "", isInline: true });
2697
- }
2698
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: NavigationAnnouncer, decorators: [{
2699
- type: Component,
2700
- args: [{
2701
- selector: "navigation-announcer",
2702
- template: "",
2703
- }]
2704
- }], ctorParameters: () => [], propDecorators: { prefix: [{ type: i0.Input, args: [{ isSignal: true, alias: "prefix", required: false }] }], getAnnouncementText: [{ type: i0.Input, args: [{ isSignal: true, alias: "getAnnouncementText", required: false }] }] } });
2705
-
2706
- /**
2707
- * Content-stable `routeParams` signal. Angular re-allocates an inline
2708
- * `[routeParams]="{ id: 1 }"` literal on every change detection, so a signal
2709
- * input changes identity each navigation even when the param CONTENT is
2710
- * unchanged (`Object.is` equality). Reading that raw input inside `RealLink` /
2711
- * `RealLinkActive`'s constructor `effect()` (added by the #630 fix) would tear
2712
- * down and re-create the cached active-route source — re-running `canonicalJson`
2713
- * for the cache key plus sub/unsub churn — and re-run `buildHref`, once per
2714
- * navigation per directive (#988).
2715
- *
2716
- * `shallowEqual` (`Object.is` per key, key-order-insensitive — the same
2717
- * contract as the React adapter's Link `memo` comparator and the Vue Link fix)
2718
- * collapses structurally-equal params to a reference-stable value. Because the
2719
- * returned `computed` re-emits the cached reference, Angular's `Object.is`
2720
- * output equality keeps the effect / `href` computed from re-running until the
2721
- * param content actually changes.
2722
- *
2723
- * Hot path on Link-heavy pages: replaces a per-navigation `canonicalJson`
2724
- * (JSON.stringify + key sort) with a per-navigation `shallowEqual` (no
2725
- * allocation), and lets same-shape navigations skip the source re-creation and
2726
- * `buildHref` entirely. Nested-object param VALUES fall back to per-render
2727
- * recompute (`shallowEqual` compares them by reference) — bind a stable
2728
- * `signal`/`computed` if it matters, exactly as documented for the Vue/React
2729
- * Link.
2730
- *
2731
- * Accepts (and preserves) `undefined`: an omitted `routeParams` input must reach
2732
- * `createActiveRouteSource` as `undefined` so it keys the active source as "" and
2733
- * shares one cached source with a manual `injectIsActiveRoute(name)`, rather than
2734
- * EMPTY_PARAMS ({}) which keys "{}" and opens a second eager subscription (#776).
2735
- * `undefined` is its own reference-stable value (`Object.is(undefined, undefined)`),
2736
- * so a stable no-params input never re-runs the effect.
2737
- *
2738
- * @param read - reads the raw params (the directive's `routeParams` input).
2739
- * @returns a `Signal<Params | undefined>` that only changes identity on real content change.
2740
- */
1367
+ imports: [NgTemplateOutlet]
1368
+ }]
1369
+ }],
1370
+ ctorParameters: () => [],
1371
+ propDecorators: {
1372
+ errorTemplate: [{
1373
+ type: i0.Input,
1374
+ args: [{
1375
+ isSignal: true,
1376
+ alias: "errorTemplate",
1377
+ required: false
1378
+ }]
1379
+ }],
1380
+ onError: [{
1381
+ type: i0.Output,
1382
+ args: ["onError"]
1383
+ }]
1384
+ }
1385
+ });
1386
+ var NavigationAnnouncer = class NavigationAnnouncer {
1387
+ prefix = input(...ngDevMode ? [void 0, { debugName: "prefix" }] : /* istanbul ignore next */ []);
1388
+ getAnnouncementText = input(...ngDevMode ? [void 0, { debugName: "getAnnouncementText" }] : /* istanbul ignore next */ []);
1389
+ router = injectRouter();
1390
+ announcer;
1391
+ constructor() {
1392
+ inject(DestroyRef).onDestroy(() => {
1393
+ this.announcer?.destroy();
1394
+ });
1395
+ }
1396
+ ngOnInit() {
1397
+ const prefix = this.prefix();
1398
+ const getAnnouncementText = this.getAnnouncementText();
1399
+ const options = {
1400
+ ...prefix !== void 0 && { prefix },
1401
+ ...getAnnouncementText !== void 0 && { getAnnouncementText }
1402
+ };
1403
+ this.announcer = createRouteAnnouncer(this.router, options);
1404
+ }
1405
+ static ɵfac = i0.ɵɵngDeclareFactory({
1406
+ minVersion: "12.0.0",
1407
+ version: "22.2.0",
1408
+ ngImport: i0,
1409
+ type: NavigationAnnouncer,
1410
+ deps: [],
1411
+ target: i0.ɵɵFactoryTarget.Component
1412
+ });
1413
+ static ɵcmp = i0.ɵɵngDeclareComponent({
1414
+ minVersion: "17.1.0",
1415
+ version: "22.2.0",
1416
+ type: NavigationAnnouncer,
1417
+ isStandalone: true,
1418
+ selector: "navigation-announcer",
1419
+ inputs: {
1420
+ prefix: {
1421
+ classPropertyName: "prefix",
1422
+ publicName: "prefix",
1423
+ isSignal: true,
1424
+ isRequired: false,
1425
+ transformFunction: null
1426
+ },
1427
+ getAnnouncementText: {
1428
+ classPropertyName: "getAnnouncementText",
1429
+ publicName: "getAnnouncementText",
1430
+ isSignal: true,
1431
+ isRequired: false,
1432
+ transformFunction: null
1433
+ }
1434
+ },
1435
+ ngImport: i0,
1436
+ template: "",
1437
+ isInline: true
1438
+ });
1439
+ };
1440
+ i0.ɵɵngDeclareClassMetadata({
1441
+ minVersion: "12.0.0",
1442
+ version: "22.2.0",
1443
+ ngImport: i0,
1444
+ type: NavigationAnnouncer,
1445
+ decorators: [{
1446
+ type: Component,
1447
+ args: [{
1448
+ selector: "navigation-announcer",
1449
+ template: ""
1450
+ }]
1451
+ }],
1452
+ ctorParameters: () => [],
1453
+ propDecorators: {
1454
+ prefix: [{
1455
+ type: i0.Input,
1456
+ args: [{
1457
+ isSignal: true,
1458
+ alias: "prefix",
1459
+ required: false
1460
+ }]
1461
+ }],
1462
+ getAnnouncementText: [{
1463
+ type: i0.Input,
1464
+ args: [{
1465
+ isSignal: true,
1466
+ alias: "getAnnouncementText",
1467
+ required: false
1468
+ }]
1469
+ }]
1470
+ }
1471
+ });
2741
1472
  function createStableParams(read) {
2742
- let cached;
2743
- return computed(() => {
2744
- const next = read();
2745
- if (cached !== undefined && shallowEqual(cached, next)) {
2746
- return cached;
2747
- }
2748
- cached = next;
2749
- return next;
2750
- });
1473
+ let cached;
1474
+ return computed(() => {
1475
+ const next = read();
1476
+ if (cached !== void 0 && shallowEqual(cached, next)) return cached;
1477
+ cached = next;
1478
+ return next;
1479
+ });
2751
1480
  }
2752
-
2753
- /**
2754
- * Subscribe a `RouterSource<T>` to a write-callback and return a cleanup
2755
- * function. The shape is the per-effect-run pattern that `RealLink`,
2756
- * `RealLinkActive`, and `RouteView` all share inside their constructor
2757
- * `effect(...)` (review-2026-05-16 §8a MEDIUM — identical 8-line block
2758
- * repeated in 3 directives):
2759
- *
2760
- * 1. Read initial snapshot and apply it via `onSnapshot(snap)`.
2761
- * 2. Subscribe — every subsequent emission calls `onSnapshot(snap)` again.
2762
- * 3. Return a cleanup that unsubscribes and destroys the source. For
2763
- * cached factories from `@real-router/sources` (`createActiveRouteSource`,
2764
- * `createRouteNodeSource`, `getTransitionSource`, `getErrorSource`,
2765
- * `createDismissableError`) `destroy()` is a no-op on the shared
2766
- * wrapper, so this helper is safe to invoke from rapid effect re-runs
2767
- * under signal-input changes.
2768
- *
2769
- * Callers pass the result to `onCleanup(...)` from Angular's `effect()`.
2770
- *
2771
- * @example
2772
- * ```ts
2773
- * effect((onCleanup) => {
2774
- * const source = createActiveRouteSource(router, routeName(), params());
2775
- * onCleanup(
2776
- * subscribeSourceToSignal(source, (snap) => {
2777
- * this.isActive.set(snap);
2778
- * this.updateDom();
2779
- * }),
2780
- * );
2781
- * });
2782
- * ```
2783
- */
2784
1481
  function subscribeSourceToSignal(source, onSnapshot) {
2785
- onSnapshot(source.getSnapshot());
2786
- const unsub = source.subscribe(() => {
2787
- onSnapshot(source.getSnapshot());
2788
- });
2789
- return () => {
2790
- unsub();
2791
- source.destroy();
2792
- };
1482
+ onSnapshot(source.getSnapshot());
1483
+ const unsub = source.subscribe(() => {
1484
+ onSnapshot(source.getSnapshot());
1485
+ });
1486
+ return () => {
1487
+ unsub();
1488
+ source.destroy();
1489
+ };
2793
1490
  }
2794
-
2795
- const NOOP_CATCH = () => { };
2796
- // Frozen no-params singleton — used where navigation/href building need a
2797
- // concrete object. The `routeParams` input itself defaults to `undefined` (NOT
2798
- // this), so the active-route source keys "" and dedups with a manual
2799
- // `injectIsActiveRoute(name)` instead of keying "{}" (#776).
1491
+ const NOOP_CATCH = () => {};
2800
1492
  const EMPTY_PARAMS = Object.freeze({});
2801
- class RealLink {
2802
- routeName = input("", /* @ts-ignore */
2803
- ...(ngDevMode ? [{ debugName: "routeName" }] : /* istanbul ignore next */ []));
2804
- // Default `undefined` (NOT {}): an omitted `routeParams` must reach
2805
- // `createActiveRouteSource` (via `stableParams`) as `undefined` so the active
2806
- // source keys "" and shares ONE cached source / router subscription with a
2807
- // manual `injectIsActiveRoute(name)`. Defaulting to {} keys "{}" and splits
2808
- // the same logical question into a second eager subscription (#776).
2809
- routeParams = input(undefined, /* @ts-ignore */
2810
- ...(ngDevMode ? [{ debugName: "routeParams" }] : /* istanbul ignore next */ []));
2811
- /**
2812
- * Query (search) params for the link's target (RFC-4 M2, #1548) — parallel to
2813
- * `routeParams`, the path/query split's view-layer channel.
2814
- */
2815
- routeSearch = input(undefined, /* @ts-ignore */
2816
- ...(ngDevMode ? [{ debugName: "routeSearch" }] : /* istanbul ignore next */ []));
2817
- /**
2818
- * Descriptor form (RFC-4 M2 B2, #1548): `[to]="{ name, params?, search? }"` —
2819
- * mutually exclusive with the routeName/routeParams/routeSearch channels
2820
- * (runtime dev-warn on conflict via `resolveLinkTarget`, `to` wins).
2821
- */
2822
- to = input(undefined, /* @ts-ignore */
2823
- ...(ngDevMode ? [{ debugName: "to" }] : /* istanbul ignore next */ []));
2824
- routeOptions = input({}, /* @ts-ignore */
2825
- ...(ngDevMode ? [{ debugName: "routeOptions" }] : /* istanbul ignore next */ []));
2826
- activeClassName = input("active", /* @ts-ignore */
2827
- ...(ngDevMode ? [{ debugName: "activeClassName" }] : /* istanbul ignore next */ []));
2828
- activeStrict = input(false, /* @ts-ignore */
2829
- ...(ngDevMode ? [{ debugName: "activeStrict" }] : /* istanbul ignore next */ []));
2830
- ignoreQueryParams = input(true, /* @ts-ignore */
2831
- ...(ngDevMode ? [{ debugName: "ignoreQueryParams" }] : /* istanbul ignore next */ []));
2832
- /**
2833
- * URL fragment (decoded form, no leading "#") (#532).
2834
- * - omitted/`undefined` → preserve current fragment on same-route navigation
2835
- * - `""` → clear fragment
2836
- * - non-empty → set fragment
2837
- */
2838
- hash = input(undefined, /* @ts-ignore */
2839
- ...(ngDevMode ? [{ debugName: "hash" }] : /* istanbul ignore next */ []));
2840
- router = injectRouter();
2841
- anchor = inject(ElementRef)
2842
- .nativeElement;
2843
- isActive = signal(false, /* @ts-ignore */
2844
- ...(ngDevMode ? [{ debugName: "isActive" }] : /* istanbul ignore next */ []));
2845
- // Content-stable `routeParams` (#988). Angular re-allocates an inline
2846
- // `[routeParams]="{ id: 1 }"` literal on every change detection, so the raw
2847
- // signal input changes identity each navigation even when the param content
2848
- // is unchanged. Feeding the stabilized signal to the `href` computed and the
2849
- // source-creation effect lets both bail (Object.is on the cached reference)
2850
- // until param content actually changes — mirrors the Vue `<Link>` fix.
2851
- stableParams = createStableParams(this.routeParams);
2852
- // `href` is computed from signal inputs only — Angular's default Object.is
2853
- // equality already collapses repeated `string` results, so no custom
2854
- // comparator is required (review §8b note 3 — applies after verifying that
2855
- // `buildHref` returns a primitive).
2856
- href = computed(() => {
2857
- const resolved = resolveLinkTarget(this.to(), this.routeName(), this.stableParams(), this.routeSearch());
2858
- return buildHref(this.router, resolved.name, resolved.params ?? EMPTY_PARAMS, resolved.search, this.hash());
2859
- }, /* @ts-ignore */
2860
- ...(ngDevMode ? [{ debugName: "href" }] : /* istanbul ignore next */ []));
2861
- prevActiveClass = "";
2862
- prevHref = undefined;
2863
- // Skip-same-value: only re-touch the DOM `class` list when the active state
2864
- // actually flipped. Without this, every navigation that re-fires the active
2865
- // source still issues a `classList.toggle` no-op (review §8b MEDIUM).
2866
- prevActive = undefined;
2867
- constructor() {
2868
- // Reactive source-creation effect (#630 fix) — see
2869
- // `packages/angular/CLAUDE.md` → "Directives use constructor + effect()".
2870
- // Reading signal inputs inside `effect()` re-creates the active-route
2871
- // source whenever any input changes; `onCleanup` tears the previous
2872
- // subscription down.
2873
- effect((onCleanup) => {
2874
- // Fast path (#1103) for default-options links — shared name selector
2875
- // instead of a per-link source; see `createActiveSource`.
2876
- // Resolve the two prop forms (RFC-4 M2 B2, #1548): `to` supersedes the
2877
- // channel inputs (dev-warn on conflict).
2878
- const resolved = resolveLinkTarget(this.to(), this.routeName(), this.stableParams(), this.routeSearch());
2879
- const source = createActiveSource(this.router, resolved.name, resolved.params, resolved.search, this.activeStrict(), this.ignoreQueryParams(), this.hash());
2880
- onCleanup(subscribeSourceToSignal(source, (snap) => {
2881
- // Pure-href refresh: when the active flag did not change, only the
2882
- // href may have moved (e.g. param-only update on a parent route).
2883
- // Skip the classList work in that branch (review §8b MEDIUM).
2884
- if (snap === this.prevActive) {
2885
- this.isActive.set(snap);
2886
- this.updateHref();
2887
- return;
2888
- }
2889
- this.prevActive = snap;
2890
- this.isActive.set(snap);
2891
- this.updateHref();
2892
- this.updateActiveClass();
2893
- }));
2894
- });
2895
- }
2896
- onClick(event) {
2897
- if (!shouldNavigate(event) || targetsAnotherContext(this.anchor.target)) {
2898
- return;
2899
- }
2900
- event.preventDefault();
2901
- const resolved = resolveLinkTarget(this.to(), this.routeName(), this.routeParams(), this.routeSearch());
2902
- navigateWithHash(this.router, resolved.name, resolved.params ?? EMPTY_PARAMS, resolved.search, this.hash(), this.routeOptions()).catch(NOOP_CATCH);
2903
- }
2904
- updateHref() {
2905
- const href = this.href();
2906
- if (href !== undefined && href !== this.prevHref) {
2907
- this.anchor.setAttribute("href", href);
2908
- }
2909
- this.prevHref = href;
2910
- }
2911
- updateActiveClass() {
2912
- const activeClass = this.activeClassName();
2913
- if (this.prevActiveClass && this.prevActiveClass !== activeClass) {
2914
- this.anchor.classList.remove(this.prevActiveClass);
2915
- }
2916
- if (activeClass) {
2917
- this.anchor.classList.toggle(activeClass, this.isActive());
2918
- }
2919
- this.prevActiveClass = activeClass;
2920
- }
2921
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: RealLink, deps: [], target: i0.ɵɵFactoryTarget.Directive });
2922
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.1.6", type: RealLink, isStandalone: true, selector: "a[realLink]", inputs: { routeName: { classPropertyName: "routeName", publicName: "routeName", isSignal: true, isRequired: false, transformFunction: null }, routeParams: { classPropertyName: "routeParams", publicName: "routeParams", isSignal: true, isRequired: false, transformFunction: null }, routeSearch: { classPropertyName: "routeSearch", publicName: "routeSearch", isSignal: true, isRequired: false, transformFunction: null }, to: { classPropertyName: "to", publicName: "to", isSignal: true, isRequired: false, transformFunction: null }, routeOptions: { classPropertyName: "routeOptions", publicName: "routeOptions", isSignal: true, isRequired: false, transformFunction: null }, activeClassName: { classPropertyName: "activeClassName", publicName: "activeClassName", isSignal: true, isRequired: false, transformFunction: null }, activeStrict: { classPropertyName: "activeStrict", publicName: "activeStrict", isSignal: true, isRequired: false, transformFunction: null }, ignoreQueryParams: { classPropertyName: "ignoreQueryParams", publicName: "ignoreQueryParams", isSignal: true, isRequired: false, transformFunction: null }, hash: { classPropertyName: "hash", publicName: "hash", isSignal: true, isRequired: false, transformFunction: null } }, host: { listeners: { "click": "onClick($event)" } }, ngImport: i0 });
2923
- }
2924
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: RealLink, decorators: [{
2925
- type: Directive,
2926
- args: [{
2927
- selector: "a[realLink]",
2928
- host: {
2929
- "(click)": "onClick($event)",
2930
- },
2931
- }]
2932
- }], ctorParameters: () => [], propDecorators: { routeName: [{ type: i0.Input, args: [{ isSignal: true, alias: "routeName", required: false }] }], routeParams: [{ type: i0.Input, args: [{ isSignal: true, alias: "routeParams", required: false }] }], routeSearch: [{ type: i0.Input, args: [{ isSignal: true, alias: "routeSearch", required: false }] }], to: [{ type: i0.Input, args: [{ isSignal: true, alias: "to", required: false }] }], routeOptions: [{ type: i0.Input, args: [{ isSignal: true, alias: "routeOptions", required: false }] }], activeClassName: [{ type: i0.Input, args: [{ isSignal: true, alias: "activeClassName", required: false }] }], activeStrict: [{ type: i0.Input, args: [{ isSignal: true, alias: "activeStrict", required: false }] }], ignoreQueryParams: [{ type: i0.Input, args: [{ isSignal: true, alias: "ignoreQueryParams", required: false }] }], hash: [{ type: i0.Input, args: [{ isSignal: true, alias: "hash", required: false }] }] } });
2933
-
2934
- class RealLinkActive {
2935
- realLinkActive = input("", /* @ts-ignore */
2936
- ...(ngDevMode ? [{ debugName: "realLinkActive" }] : /* istanbul ignore next */ []));
2937
- routeName = input("", /* @ts-ignore */
2938
- ...(ngDevMode ? [{ debugName: "routeName" }] : /* istanbul ignore next */ []));
2939
- // Default `undefined` (NOT {}): an omitted `routeParams` must reach
2940
- // `createActiveRouteSource` (via `stableParams`) as `undefined` so the active
2941
- // source keys "" and shares ONE cached source with a manual
2942
- // `injectIsActiveRoute(name)`, instead of keying "{}" and opening a second
2943
- // eager subscription for the same question (#776). Mirrors `RealLink`.
2944
- routeParams = input(undefined, /* @ts-ignore */
2945
- ...(ngDevMode ? [{ debugName: "routeParams" }] : /* istanbul ignore next */ []));
2946
- activeStrict = input(false, /* @ts-ignore */
2947
- ...(ngDevMode ? [{ debugName: "activeStrict" }] : /* istanbul ignore next */ []));
2948
- ignoreQueryParams = input(true, /* @ts-ignore */
2949
- ...(ngDevMode ? [{ debugName: "ignoreQueryParams" }] : /* istanbul ignore next */ []));
2950
- router = injectRouter();
2951
- element = inject(ElementRef).nativeElement;
2952
- isActive = signal(false, /* @ts-ignore */
2953
- ...(ngDevMode ? [{ debugName: "isActive" }] : /* istanbul ignore next */ []));
2954
- // Content-stable `routeParams` (#988) — see the matching field in `RealLink`.
2955
- // Lets the source-creation effect bail until param content actually changes
2956
- // instead of churning on every fresh inline-literal binding.
2957
- stableParams = createStableParams(this.routeParams);
2958
- // Skip-same-value: only touch `classList.toggle` when the active flag
2959
- // actually flipped. Saves one DOM write per RealLinkActive per unrelated
2960
- // navigation (review §8b MEDIUM).
2961
- prevActive = undefined;
2962
- constructor() {
2963
- // One-time a11y setup — doesn't depend on signal inputs, stays in
2964
- // constructor body. `applyLinkA11y` is idempotent so re-running would
2965
- // be safe, but we only need it once per element.
2966
- applyLinkA11y(this.element);
2967
- // Reactive source-creation effect (#630 fix) — see
2968
- // `packages/angular/CLAUDE.md` → "Directives use constructor + effect()".
2969
- effect((onCleanup) => {
2970
- // Fast path (#1103) for default-options links — shared name selector
2971
- // instead of a per-link source; see `createActiveSource`. RealLinkActive
2972
- // has no `hash` input, so it is always passed `undefined`.
2973
- const source = createActiveSource(this.router, this.routeName(), this.stableParams(),
2974
- // Query channel (RFC-4 M2, #1548) — RealLinkActive is styling-only and
2975
- // has no `routeSearch` input (parity with its no-`hash` policy).
2976
- undefined, this.activeStrict(), this.ignoreQueryParams(), undefined);
2977
- onCleanup(subscribeSourceToSignal(source, (snap) => {
2978
- if (snap === this.prevActive) {
2979
- return;
2980
- }
2981
- this.prevActive = snap;
2982
- this.isActive.set(snap);
2983
- this.updateClass();
2984
- }));
2985
- });
2986
- }
2987
- updateClass() {
2988
- const className = this.realLinkActive();
2989
- if (!className) {
2990
- return;
2991
- }
2992
- this.element.classList.toggle(className, this.isActive());
2993
- }
2994
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: RealLinkActive, deps: [], target: i0.ɵɵFactoryTarget.Directive });
2995
- static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.1.6", type: RealLinkActive, isStandalone: true, selector: "[realLinkActive]", inputs: { realLinkActive: { classPropertyName: "realLinkActive", publicName: "realLinkActive", isSignal: true, isRequired: false, transformFunction: null }, routeName: { classPropertyName: "routeName", publicName: "routeName", isSignal: true, isRequired: false, transformFunction: null }, routeParams: { classPropertyName: "routeParams", publicName: "routeParams", isSignal: true, isRequired: false, transformFunction: null }, activeStrict: { classPropertyName: "activeStrict", publicName: "activeStrict", isSignal: true, isRequired: false, transformFunction: null }, ignoreQueryParams: { classPropertyName: "ignoreQueryParams", publicName: "ignoreQueryParams", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0 });
2996
- }
2997
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.6", ngImport: i0, type: RealLinkActive, decorators: [{
2998
- type: Directive,
2999
- args: [{ selector: "[realLinkActive]" }]
3000
- }], ctorParameters: () => [], propDecorators: { realLinkActive: [{ type: i0.Input, args: [{ isSignal: true, alias: "realLinkActive", required: false }] }], routeName: [{ type: i0.Input, args: [{ isSignal: true, alias: "routeName", required: false }] }], routeParams: [{ type: i0.Input, args: [{ isSignal: true, alias: "routeParams", required: false }] }], activeStrict: [{ type: i0.Input, args: [{ isSignal: true, alias: "activeStrict", required: false }] }], ignoreQueryParams: [{ type: i0.Input, args: [{ isSignal: true, alias: "ignoreQueryParams", required: false }] }] } });
3001
-
3002
- /**
3003
- * Generated bundle index. Do not edit.
3004
- */
1493
+ var RealLink = class RealLink {
1494
+ routeName = input("", ...ngDevMode ? [{ debugName: "routeName" }] : /* istanbul ignore next */ []);
1495
+ routeParams = input(void 0, ...ngDevMode ? [{ debugName: "routeParams" }] : /* istanbul ignore next */ []);
1496
+ routeSearch = input(void 0, ...ngDevMode ? [{ debugName: "routeSearch" }] : /* istanbul ignore next */ []);
1497
+ to = input(void 0, ...ngDevMode ? [{ debugName: "to" }] : /* istanbul ignore next */ []);
1498
+ routeOptions = input({}, ...ngDevMode ? [{ debugName: "routeOptions" }] : /* istanbul ignore next */ []);
1499
+ activeClassName = input("active", ...ngDevMode ? [{ debugName: "activeClassName" }] : /* istanbul ignore next */ []);
1500
+ activeStrict = input(false, ...ngDevMode ? [{ debugName: "activeStrict" }] : /* istanbul ignore next */ []);
1501
+ ignoreQueryParams = input(true, ...ngDevMode ? [{ debugName: "ignoreQueryParams" }] : /* istanbul ignore next */ []);
1502
+ hash = input(void 0, ...ngDevMode ? [{ debugName: "hash" }] : /* istanbul ignore next */ []);
1503
+ router = injectRouter();
1504
+ anchor = inject(ElementRef).nativeElement;
1505
+ isActive = signal(false, ...ngDevMode ? [{ debugName: "isActive" }] : /* istanbul ignore next */ []);
1506
+ stableParams = createStableParams(this.routeParams);
1507
+ href = computed(() => {
1508
+ const resolved = resolveLinkTarget(this.to(), this.routeName(), this.stableParams(), this.routeSearch());
1509
+ return buildHref(this.router, resolved.name, resolved.params ?? EMPTY_PARAMS, resolved.search, this.hash());
1510
+ }, ...ngDevMode ? [{ debugName: "href" }] : /* istanbul ignore next */ []);
1511
+ prevActiveClass = "";
1512
+ prevHref = void 0;
1513
+ prevActive = void 0;
1514
+ constructor() {
1515
+ effect((onCleanup) => {
1516
+ const resolved = resolveLinkTarget(this.to(), this.routeName(), this.stableParams(), this.routeSearch());
1517
+ onCleanup(subscribeSourceToSignal(createActiveSource(this.router, resolved.name, resolved.params, resolved.search, this.activeStrict(), this.ignoreQueryParams(), this.hash()), (snap) => {
1518
+ if (snap === this.prevActive) {
1519
+ this.isActive.set(snap);
1520
+ this.updateHref();
1521
+ return;
1522
+ }
1523
+ this.prevActive = snap;
1524
+ this.isActive.set(snap);
1525
+ this.updateHref();
1526
+ this.updateActiveClass();
1527
+ }));
1528
+ });
1529
+ }
1530
+ onClick(event) {
1531
+ if (!shouldNavigate(event) || targetsAnotherContext(this.anchor.target)) return;
1532
+ event.preventDefault();
1533
+ const resolved = resolveLinkTarget(this.to(), this.routeName(), this.routeParams(), this.routeSearch());
1534
+ navigateWithHash(this.router, resolved.name, resolved.params ?? EMPTY_PARAMS, resolved.search, this.hash(), this.routeOptions()).catch(NOOP_CATCH);
1535
+ }
1536
+ updateHref() {
1537
+ const href = this.href();
1538
+ if (href !== void 0 && href !== this.prevHref) this.anchor.setAttribute("href", href);
1539
+ this.prevHref = href;
1540
+ }
1541
+ updateActiveClass() {
1542
+ const activeClass = this.activeClassName();
1543
+ if (this.prevActiveClass && this.prevActiveClass !== activeClass) this.anchor.classList.remove(this.prevActiveClass);
1544
+ if (activeClass) this.anchor.classList.toggle(activeClass, this.isActive());
1545
+ this.prevActiveClass = activeClass;
1546
+ }
1547
+ static ɵfac = i0.ɵɵngDeclareFactory({
1548
+ minVersion: "12.0.0",
1549
+ version: "22.2.0",
1550
+ ngImport: i0,
1551
+ type: RealLink,
1552
+ deps: [],
1553
+ target: i0.ɵɵFactoryTarget.Directive
1554
+ });
1555
+ static ɵdir = i0.ɵɵngDeclareDirective({
1556
+ minVersion: "17.1.0",
1557
+ version: "22.2.0",
1558
+ type: RealLink,
1559
+ isStandalone: true,
1560
+ selector: "a[realLink]",
1561
+ inputs: {
1562
+ routeName: {
1563
+ classPropertyName: "routeName",
1564
+ publicName: "routeName",
1565
+ isSignal: true,
1566
+ isRequired: false,
1567
+ transformFunction: null
1568
+ },
1569
+ routeParams: {
1570
+ classPropertyName: "routeParams",
1571
+ publicName: "routeParams",
1572
+ isSignal: true,
1573
+ isRequired: false,
1574
+ transformFunction: null
1575
+ },
1576
+ routeSearch: {
1577
+ classPropertyName: "routeSearch",
1578
+ publicName: "routeSearch",
1579
+ isSignal: true,
1580
+ isRequired: false,
1581
+ transformFunction: null
1582
+ },
1583
+ to: {
1584
+ classPropertyName: "to",
1585
+ publicName: "to",
1586
+ isSignal: true,
1587
+ isRequired: false,
1588
+ transformFunction: null
1589
+ },
1590
+ routeOptions: {
1591
+ classPropertyName: "routeOptions",
1592
+ publicName: "routeOptions",
1593
+ isSignal: true,
1594
+ isRequired: false,
1595
+ transformFunction: null
1596
+ },
1597
+ activeClassName: {
1598
+ classPropertyName: "activeClassName",
1599
+ publicName: "activeClassName",
1600
+ isSignal: true,
1601
+ isRequired: false,
1602
+ transformFunction: null
1603
+ },
1604
+ activeStrict: {
1605
+ classPropertyName: "activeStrict",
1606
+ publicName: "activeStrict",
1607
+ isSignal: true,
1608
+ isRequired: false,
1609
+ transformFunction: null
1610
+ },
1611
+ ignoreQueryParams: {
1612
+ classPropertyName: "ignoreQueryParams",
1613
+ publicName: "ignoreQueryParams",
1614
+ isSignal: true,
1615
+ isRequired: false,
1616
+ transformFunction: null
1617
+ },
1618
+ hash: {
1619
+ classPropertyName: "hash",
1620
+ publicName: "hash",
1621
+ isSignal: true,
1622
+ isRequired: false,
1623
+ transformFunction: null
1624
+ }
1625
+ },
1626
+ host: { listeners: { "click": "onClick($event)" } },
1627
+ ngImport: i0
1628
+ });
1629
+ };
1630
+ i0.ɵɵngDeclareClassMetadata({
1631
+ minVersion: "12.0.0",
1632
+ version: "22.2.0",
1633
+ ngImport: i0,
1634
+ type: RealLink,
1635
+ decorators: [{
1636
+ type: Directive,
1637
+ args: [{
1638
+ selector: "a[realLink]",
1639
+ host: { "(click)": "onClick($event)" }
1640
+ }]
1641
+ }],
1642
+ ctorParameters: () => [],
1643
+ propDecorators: {
1644
+ routeName: [{
1645
+ type: i0.Input,
1646
+ args: [{
1647
+ isSignal: true,
1648
+ alias: "routeName",
1649
+ required: false
1650
+ }]
1651
+ }],
1652
+ routeParams: [{
1653
+ type: i0.Input,
1654
+ args: [{
1655
+ isSignal: true,
1656
+ alias: "routeParams",
1657
+ required: false
1658
+ }]
1659
+ }],
1660
+ routeSearch: [{
1661
+ type: i0.Input,
1662
+ args: [{
1663
+ isSignal: true,
1664
+ alias: "routeSearch",
1665
+ required: false
1666
+ }]
1667
+ }],
1668
+ to: [{
1669
+ type: i0.Input,
1670
+ args: [{
1671
+ isSignal: true,
1672
+ alias: "to",
1673
+ required: false
1674
+ }]
1675
+ }],
1676
+ routeOptions: [{
1677
+ type: i0.Input,
1678
+ args: [{
1679
+ isSignal: true,
1680
+ alias: "routeOptions",
1681
+ required: false
1682
+ }]
1683
+ }],
1684
+ activeClassName: [{
1685
+ type: i0.Input,
1686
+ args: [{
1687
+ isSignal: true,
1688
+ alias: "activeClassName",
1689
+ required: false
1690
+ }]
1691
+ }],
1692
+ activeStrict: [{
1693
+ type: i0.Input,
1694
+ args: [{
1695
+ isSignal: true,
1696
+ alias: "activeStrict",
1697
+ required: false
1698
+ }]
1699
+ }],
1700
+ ignoreQueryParams: [{
1701
+ type: i0.Input,
1702
+ args: [{
1703
+ isSignal: true,
1704
+ alias: "ignoreQueryParams",
1705
+ required: false
1706
+ }]
1707
+ }],
1708
+ hash: [{
1709
+ type: i0.Input,
1710
+ args: [{
1711
+ isSignal: true,
1712
+ alias: "hash",
1713
+ required: false
1714
+ }]
1715
+ }]
1716
+ }
1717
+ });
1718
+ var RealLinkActive = class RealLinkActive {
1719
+ realLinkActive = input("", ...ngDevMode ? [{ debugName: "realLinkActive" }] : /* istanbul ignore next */ []);
1720
+ routeName = input("", ...ngDevMode ? [{ debugName: "routeName" }] : /* istanbul ignore next */ []);
1721
+ routeParams = input(void 0, ...ngDevMode ? [{ debugName: "routeParams" }] : /* istanbul ignore next */ []);
1722
+ activeStrict = input(false, ...ngDevMode ? [{ debugName: "activeStrict" }] : /* istanbul ignore next */ []);
1723
+ ignoreQueryParams = input(true, ...ngDevMode ? [{ debugName: "ignoreQueryParams" }] : /* istanbul ignore next */ []);
1724
+ router = injectRouter();
1725
+ element = inject(ElementRef).nativeElement;
1726
+ isActive = signal(false, ...ngDevMode ? [{ debugName: "isActive" }] : /* istanbul ignore next */ []);
1727
+ stableParams = createStableParams(this.routeParams);
1728
+ prevActive = void 0;
1729
+ constructor() {
1730
+ applyLinkA11y(this.element);
1731
+ effect((onCleanup) => {
1732
+ onCleanup(subscribeSourceToSignal(createActiveSource(this.router, this.routeName(), this.stableParams(), void 0, this.activeStrict(), this.ignoreQueryParams(), void 0), (snap) => {
1733
+ if (snap === this.prevActive) return;
1734
+ this.prevActive = snap;
1735
+ this.isActive.set(snap);
1736
+ this.updateClass();
1737
+ }));
1738
+ });
1739
+ }
1740
+ updateClass() {
1741
+ const className = this.realLinkActive();
1742
+ if (!className) return;
1743
+ this.element.classList.toggle(className, this.isActive());
1744
+ }
1745
+ static ɵfac = i0.ɵɵngDeclareFactory({
1746
+ minVersion: "12.0.0",
1747
+ version: "22.2.0",
1748
+ ngImport: i0,
1749
+ type: RealLinkActive,
1750
+ deps: [],
1751
+ target: i0.ɵɵFactoryTarget.Directive
1752
+ });
1753
+ static ɵdir = i0.ɵɵngDeclareDirective({
1754
+ minVersion: "17.1.0",
1755
+ version: "22.2.0",
1756
+ type: RealLinkActive,
1757
+ isStandalone: true,
1758
+ selector: "[realLinkActive]",
1759
+ inputs: {
1760
+ realLinkActive: {
1761
+ classPropertyName: "realLinkActive",
1762
+ publicName: "realLinkActive",
1763
+ isSignal: true,
1764
+ isRequired: false,
1765
+ transformFunction: null
1766
+ },
1767
+ routeName: {
1768
+ classPropertyName: "routeName",
1769
+ publicName: "routeName",
1770
+ isSignal: true,
1771
+ isRequired: false,
1772
+ transformFunction: null
1773
+ },
1774
+ routeParams: {
1775
+ classPropertyName: "routeParams",
1776
+ publicName: "routeParams",
1777
+ isSignal: true,
1778
+ isRequired: false,
1779
+ transformFunction: null
1780
+ },
1781
+ activeStrict: {
1782
+ classPropertyName: "activeStrict",
1783
+ publicName: "activeStrict",
1784
+ isSignal: true,
1785
+ isRequired: false,
1786
+ transformFunction: null
1787
+ },
1788
+ ignoreQueryParams: {
1789
+ classPropertyName: "ignoreQueryParams",
1790
+ publicName: "ignoreQueryParams",
1791
+ isSignal: true,
1792
+ isRequired: false,
1793
+ transformFunction: null
1794
+ }
1795
+ },
1796
+ ngImport: i0
1797
+ });
1798
+ };
1799
+ i0.ɵɵngDeclareClassMetadata({
1800
+ minVersion: "12.0.0",
1801
+ version: "22.2.0",
1802
+ ngImport: i0,
1803
+ type: RealLinkActive,
1804
+ decorators: [{
1805
+ type: Directive,
1806
+ args: [{ selector: "[realLinkActive]" }]
1807
+ }],
1808
+ ctorParameters: () => [],
1809
+ propDecorators: {
1810
+ realLinkActive: [{
1811
+ type: i0.Input,
1812
+ args: [{
1813
+ isSignal: true,
1814
+ alias: "realLinkActive",
1815
+ required: false
1816
+ }]
1817
+ }],
1818
+ routeName: [{
1819
+ type: i0.Input,
1820
+ args: [{
1821
+ isSignal: true,
1822
+ alias: "routeName",
1823
+ required: false
1824
+ }]
1825
+ }],
1826
+ routeParams: [{
1827
+ type: i0.Input,
1828
+ args: [{
1829
+ isSignal: true,
1830
+ alias: "routeParams",
1831
+ required: false
1832
+ }]
1833
+ }],
1834
+ activeStrict: [{
1835
+ type: i0.Input,
1836
+ args: [{
1837
+ isSignal: true,
1838
+ alias: "activeStrict",
1839
+ required: false
1840
+ }]
1841
+ }],
1842
+ ignoreQueryParams: [{
1843
+ type: i0.Input,
1844
+ args: [{
1845
+ isSignal: true,
1846
+ alias: "ignoreQueryParams",
1847
+ required: false
1848
+ }]
1849
+ }]
1850
+ }
1851
+ });
1852
+ export { NAVIGATOR, NavigationAnnouncer, ROUTE, ROUTER, RealLink, RealLinkActive, RouteMatch, RouteNotFound, RouteSelf, RouteView, RouterErrorBoundary, createDirectionTracker, injectIsActiveRoute, injectNavigator, injectRoute, injectRouteEnter, injectRouteExit, injectRouteNode, injectRouteUtils, injectRouter, injectRouterTransition, provideRealRouter, provideRealRouterFactory };
3005
1853
 
3006
- export { NAVIGATOR, NavigationAnnouncer, ROUTE, ROUTER, RealLink, RealLinkActive, RouteMatch, RouteNotFound, RouteSelf, RouteView, RouterErrorBoundary, createDirectionTracker, injectIsActiveRoute, injectNavigator, injectRoute, injectRouteEnter, injectRouteExit, injectRouteNode, injectRouteUtils, injectRouter, injectRouterTransition, provideRealRouter, provideRealRouterFactory, sourceToSignal };
3007
- //# sourceMappingURL=real-router-angular.mjs.map
1854
+ //# sourceMappingURL=real-router-angular.mjs.map