@vielzeug/wayfinder 26.11.11 → 26.11.13

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.
package/dist/router.js CHANGED
@@ -4,7 +4,7 @@ import { buildMatchBranch as n, createRouteContext as r, createRouteState as i,
4
4
  import { WayfinderDisposedError as s, WayfinderRedirectLoopError as c, WayfinderRouteError as l } from "./errors.js";
5
5
  import { runLeaveBlockers as u } from "./guards.js";
6
6
  import { createBrowserHistory as d } from "./history.js";
7
- import { buildUrl as f, joinPaths as p, matchRouteFor as m, matchesPrefix as h, normalizePath as g, parseQuery as _, readLocation as v, stripBase as y } from "./path.js";
7
+ import { buildUrl as f, joinPaths as p, matchRouteFor as m, matchesPrefix as h, normalizePath as g, parseQuery as _, stripBase as v } from "./path.js";
8
8
  // src/router.ts
9
9
  function getRouteByName(e, t) {
10
10
  let n = t.get(e);
@@ -17,16 +17,16 @@ function resolveTarget(e, t, n = "/") {
17
17
  let r = getRouteByName(e.name, t), i = f(n, r.path, e.params, e.query);
18
18
  return e.hash ? `${i}#${e.hash}` : i;
19
19
  }
20
- var b = Symbol("wayfinder.routerError");
20
+ var y = Symbol("wayfinder.routerError"), b = 5;
21
21
  function carryError(e, t) {
22
22
  return {
23
- [b]: !0,
23
+ [y]: !0,
24
24
  context: t,
25
25
  error: e
26
26
  };
27
27
  }
28
28
  function isRouterErrorCarrier(e) {
29
- return typeof e == "object" && !!e && b in e;
29
+ return typeof e == "object" && !!e && y in e;
30
30
  }
31
31
  function unwrapCarrier(e) {
32
32
  throw isRouterErrorCarrier(e) ? e.error : e;
@@ -82,14 +82,14 @@ var Router = class {
82
82
  };
83
83
  } else this.#v = null;
84
84
  this.#y = this.#x();
85
- let { hash: r, pathname: a, search: o } = this.#r.location;
86
- this.#m = `${a}${o}${r}`;
87
- let s = this.#u.begin(), c = this.#A(s, v(this.#e, this.#r), (e, t) => {
88
- if (!s.isCurrent()) return;
89
- let n = this.#F(e);
85
+ let { hash: r, pathname: a, search: o, state: s } = this.#r.location, c = `${a}${o}${r}`;
86
+ this.#m = c;
87
+ let l = this.#u.begin(), u = this.#j(l, c, s, (e, t) => {
88
+ if (!l.isCurrent()) return;
89
+ let n = this.#I(e);
90
90
  t && this.#r.replace(n, e.historyState), this.#m = n;
91
- }, void 0, 0, !1).then(() => void 0);
92
- this.ready = c.catch(unwrapCarrier), this.ready.catch(() => {}), this.#w(c, { source: "initial-navigation" }), this.beforeLeave = this.beforeLeave.bind(this), this.createViewRegistry = this.createViewRegistry.bind(this), this.dispose = this.dispose.bind(this), this.getSnapshot = this.getSnapshot.bind(this), this.isActive = this.isActive.bind(this), this.load = this.load.bind(this), this.match = this.match.bind(this), this.navigate = this.navigate.bind(this), this.preload = this.preload.bind(this), this.subscribe = this.subscribe.bind(this), this.url = this.url.bind(this), this.waitFor = this.waitFor.bind(this);
91
+ }, void 0, !1).then(() => void 0);
92
+ this.ready = u.catch(unwrapCarrier), this.ready.catch(() => {}), this.#w(u, { source: "initial-navigation" }), this.beforeLeave = this.beforeLeave.bind(this), this.createViewRegistry = this.createViewRegistry.bind(this), this.dispose = this.dispose.bind(this), this.getSnapshot = this.getSnapshot.bind(this), this.isActive = this.isActive.bind(this), this.load = this.load.bind(this), this.match = this.match.bind(this), this.navigate = this.navigate.bind(this), this.preload = this.preload.bind(this), this.subscribe = this.subscribe.bind(this), this.url = this.url.bind(this), this.waitFor = this.waitFor.bind(this);
93
93
  }
94
94
  getSnapshot() {
95
95
  return this.#d;
@@ -106,8 +106,8 @@ var Router = class {
106
106
  };
107
107
  }
108
108
  navigate(e, t) {
109
- let n = resolveTarget(typeof e == "string" ? { path: e } : e, this.#a);
110
- return this.#L(n, t);
109
+ let n = resolveTarget(typeof e == "string" ? { path: e } : e, this.#a, this.#e);
110
+ return this.#R(n, t);
111
111
  }
112
112
  url(e, t, n) {
113
113
  let r = getRouteByName(e, this.#a);
@@ -122,13 +122,13 @@ var Router = class {
122
122
  return t.exact ?? !1 ? m(r, [n]).record != null : h(r, n);
123
123
  }
124
124
  match(e) {
125
- let t = y(g(e), this.#e), { params: r, record: i } = m(t, this.#i);
125
+ let t = v(g(e), this.#e), { params: r, record: i } = m(t, this.#i);
126
126
  if (!i || i.redirect) return null;
127
127
  let a = n(i.branchDefs, r, t, i.branchDefs.map(() => void 0));
128
128
  return a.length ? a : null;
129
129
  }
130
130
  async load(e, t) {
131
- let a = await this.#D(e);
131
+ let { decision: a } = await this.#D(e, null);
132
132
  if (a.type !== "matched") return null;
133
133
  let { location: o, params: s, record: c, resolvedQuery: l } = a, u = c.branchDefs, d = u.some((e) => e.dataFn != null), f = u.map(() => void 0), p, m = "idle";
134
134
  if (d) {
@@ -148,13 +148,13 @@ var Router = class {
148
148
  }
149
149
  async preload(e) {
150
150
  this.#b();
151
- let t = this.#N(resolveTarget(e, this.#a, this.#e)), n = this.#_.get(t);
151
+ let t = this.#P(resolveTarget(e, this.#a, this.#e)), n = this.#_.get(t);
152
152
  if (n) return n;
153
153
  let r = this.load(t, { signal: this.#p.signal }).then((e) => {
154
154
  if (this.#f) throw this.#p.signal.reason;
155
155
  if (e?.status === "error") throw e.error;
156
156
  if (e) {
157
- let t = this.#F(e.location);
157
+ let t = this.#I(e.location);
158
158
  this.#g.size >= 20 && this.#g.delete(this.#g.keys().next().value), this.#g.set(t, e.matches.map((e) => e.data));
159
159
  }
160
160
  return e;
@@ -216,17 +216,17 @@ var Router = class {
216
216
  });
217
217
  }
218
218
  async #S(e, t) {
219
- let n = this.#u.begin(), r = this.#d.matches.map((e) => e.name), i = this.#I(e), a = await u(this.#l, r, i);
219
+ let n = this.#u.begin(), r = this.#d.matches.map((e) => e.name), i = this.#L(e), a = await u(this.#l, r, i);
220
220
  if (!n.isCurrent()) return;
221
221
  if (!a) {
222
222
  this.#r.replace(t, this.#d.location.historyState);
223
223
  return;
224
224
  }
225
- let o = await this.#A(n, v(this.#e, this.#r), (e, t) => {
225
+ let o = await this.#j(n, e, this.#r.location.state, (e, t) => {
226
226
  if (!n.isCurrent()) return;
227
- let r = this.#F(e);
227
+ let r = this.#I(e);
228
228
  t && this.#r.replace(r, e.historyState), this.#m = r;
229
- }, void 0, 0, !1);
229
+ }, void 0, !1);
230
230
  n.isCurrent() && !o && this.#r.replace(t, this.#d.location.historyState);
231
231
  }
232
232
  #C(e, t) {
@@ -264,23 +264,36 @@ var Router = class {
264
264
  }
265
265
  }));
266
266
  }
267
- async #D(e) {
268
- let t = e;
269
- for (let e = 0; e < 5; e += 1) {
270
- let e = new URL(t, "http://localhost"), n = {
271
- hash: e.hash.replace(/^#/, ""),
272
- historyState: null,
273
- pathname: y(e.pathname, this.#e),
274
- query: _(e.search)
275
- }, r = await this.#O(n);
276
- if (r.type !== "redirect") return r;
277
- t = this.#N(r.redirectTo);
267
+ async #D(e, t) {
268
+ let n = e, r = !1;
269
+ for (let e = 0;; e += 1) {
270
+ let i = await this.#k(this.#F(n, t));
271
+ if (i.type !== "redirect") return {
272
+ decision: i,
273
+ hopped: r
274
+ };
275
+ if (e >= b) throw new c();
276
+ n = i.redirectTo, r = !0;
277
+ }
278
+ }
279
+ #O(e, t) {
280
+ if (!t) return e.query;
281
+ try {
282
+ return t(e.query);
283
+ } catch (t) {
284
+ return this.#C(t, { source: "coerce-search" }), e.query;
278
285
  }
279
- throw new c();
280
286
  }
281
- async #O(e) {
287
+ async #k(e) {
282
288
  let { params: t, record: r } = m(e.pathname, this.#i);
283
- if (!r) return {
289
+ if (!r) return this.#v ? {
290
+ branch: n(this.#v.branchDefs, {}, e.pathname, [void 0]),
291
+ location: e,
292
+ params: {},
293
+ record: this.#v,
294
+ resolvedQuery: this.#O(e, this.#n),
295
+ type: "matched"
296
+ } : {
284
297
  location: e,
285
298
  params: t,
286
299
  type: "unmatched"
@@ -291,12 +304,7 @@ var Router = class {
291
304
  redirectTo: resolveTarget(r.redirect, this.#a, this.#e),
292
305
  type: "redirect"
293
306
  };
294
- let i = e.query, a = r.coerceSearch ?? this.#n;
295
- if (a) try {
296
- i = a(e.query);
297
- } catch (t) {
298
- this.#C(t, { source: "coerce-search" }), i = e.query;
299
- }
307
+ let i = this.#O(e, r.coerceSearch ?? this.#n);
300
308
  return {
301
309
  branch: n(r.branchDefs, t, e.pathname, r.branchDefs.map(() => void 0)),
302
310
  location: e,
@@ -306,11 +314,11 @@ var Router = class {
306
314
  type: "matched"
307
315
  };
308
316
  }
309
- async #k(e, t, r, a, o, s, c) {
317
+ async #A(e, t, r, a, o, s, c) {
310
318
  if (!s()) return;
311
319
  let l = e.branchDefs, u = l.some((e) => e.dataFn != null), d = l.map(() => void 0);
312
320
  if (u) {
313
- let e = this.#F(r), u = this.#_.get(e);
321
+ let e = this.#I(r), u = this.#_.get(e);
314
322
  if (u && (await u.catch(() => void 0), !s())) return;
315
323
  let f = this.#g.get(e);
316
324
  if (f) this.#g.delete(e), d = f;
@@ -339,76 +347,39 @@ var Router = class {
339
347
  status: "idle"
340
348
  }));
341
349
  }
342
- async #A(e, t, o, s, l = 0, u = !1) {
343
- let d = this.#d, isCurrent = () => e.isCurrent() && !this.#f, f = await this.#O(t);
350
+ async #j(e, t, n, o, s, c) {
351
+ let l = this.#d, isCurrent = () => e.isCurrent() && !this.#f, { decision: u, hopped: d } = await this.#D(t, n);
344
352
  if (!isCurrent()) return !1;
345
- if (f.type === "redirect") {
346
- if (l >= 5) throw new c();
347
- return this.#A(e, this.#P(f.redirectTo, t.historyState), o, s, l + 1, !0);
348
- }
349
- if (f.type === "unmatched") {
350
- if (this.#v) {
351
- let i = [this.#v.leaf], c = n(i, {}, t.pathname, [void 0]), l = !1, f, p = !1, m = !1, h = t.query, g = !1;
352
- if (this.#n) try {
353
- h = this.#n(t.query);
354
- } catch (e) {
355
- this.#C(e, { source: "coerce-search" });
356
- }
357
- let run = async () => {
358
- if (!isCurrent()) return;
359
- let n = r(t, h, {}, c, (e, t) => this.navigate(e, t));
360
- m = await a(n, [...this.#t, ...this.#v.ownMiddleware], async () => {
361
- isCurrent() && (l = !0, o(t, u), isCurrent() && (await this.#k(this.#v, n, t, {}, e.signal, isCurrent, (e) => {
362
- f = e, p = !0;
363
- }), isCurrent() && (g = !0, this.#T(), this.#M(this.#d, d))));
364
- }, (e) => isRouterErrorCarrier(e) || p && e === f ? e : carryError(e, {
365
- routeName: "__notFound__",
366
- source: "middleware"
367
- }));
368
- };
369
- try {
370
- await this.#j(run, s);
371
- } catch (e) {
372
- throw p && e === f ? carryError(e, {
373
- routeName: "__notFound__",
374
- source: "data-loader"
375
- }) : e;
376
- } finally {
377
- isCurrent() && l && !g && (this.#T(), this.#M(this.#d, d));
378
- }
379
- return m && l;
380
- }
381
- return !isCurrent() || (o(f.location, u), !isCurrent()) ? !1 : (this.#d = i({
382
- location: f.location,
383
- matches: [],
384
- status: "idle"
385
- }), this.#T(), this.#M(this.#d, d), !0);
386
- }
387
- let { branch: p, location: m, params: h, record: g, resolvedQuery: _ } = f, v = !1, y, b = !1, x = !1, S = !1, run = async () => {
353
+ if (u.type === "unmatched") return o(u.location, c || d), isCurrent() ? (this.#d = i({
354
+ location: u.location,
355
+ matches: [],
356
+ status: "idle"
357
+ }), this.#T(), this.#N(this.#d, l), !0) : !1;
358
+ let { branch: f, location: p, params: m, record: h, resolvedQuery: g } = u, _ = c || d, v = !1, y, b = !1, x = !1, S = !1, run = async () => {
388
359
  if (!isCurrent()) return;
389
- let t = r(m, _, h, p, (e, t) => this.navigate(e, t));
390
- x = await a(t, [...this.#t, ...g.ownMiddleware], async () => {
391
- isCurrent() && (v = !0, o(m, u), isCurrent() && (await this.#k(g, t, m, h, e.signal, isCurrent, (e) => {
360
+ let t = r(p, g, m, f, (e, t) => this.navigate(e, t));
361
+ x = await a(t, [...this.#t, ...h.ownMiddleware], async () => {
362
+ isCurrent() && (v = !0, o(p, _), isCurrent() && (await this.#A(h, t, p, m, e.signal, isCurrent, (e) => {
392
363
  y = e, b = !0;
393
- }), isCurrent() && (S = !0, this.#T(), this.#M(this.#d, d))));
364
+ }), isCurrent() && (S = !0, this.#T(), this.#N(this.#d, l))));
394
365
  }, (e) => isRouterErrorCarrier(e) || b && e === y ? e : carryError(e, {
395
- routeName: g.leaf.name,
366
+ routeName: h.leaf.name,
396
367
  source: "middleware"
397
368
  }));
398
369
  };
399
370
  try {
400
- await this.#j(run, s);
371
+ await this.#M(run, s);
401
372
  } catch (e) {
402
373
  throw b && e === y ? carryError(e, {
403
- routeName: g.leaf.name,
374
+ routeName: h.leaf.name,
404
375
  source: "data-loader"
405
376
  }) : e;
406
377
  } finally {
407
- isCurrent() && v && !S && (this.#T(), this.#M(this.#d, d));
378
+ isCurrent() && v && !S && (this.#T(), this.#N(this.#d, l));
408
379
  }
409
380
  return x && v;
410
381
  }
411
- async #j(e, t) {
382
+ async #M(e, t) {
412
383
  if ((t ?? this.#c) && typeof document < "u") {
413
384
  let t = document.startViewTransition;
414
385
  if (t) {
@@ -418,25 +389,25 @@ var Router = class {
418
389
  }
419
390
  await e();
420
391
  }
421
- #M(e, t) {
392
+ #N(e, t) {
422
393
  if (!this.#s || typeof window > "u") return;
423
394
  let n = this.#s(e, t);
424
395
  n !== "preserve" && (n === "top" ? window.scrollTo(0, 0) : window.scrollTo(n.x, n.y));
425
396
  }
426
- #N(e) {
427
- let t = new URL(e, "http://localhost"), n = y(t.pathname, this.#e);
397
+ #P(e) {
398
+ let t = new URL(e, "http://localhost"), n = v(t.pathname, this.#e);
428
399
  return `${p(this.#e, n)}${t.search}${t.hash}`;
429
400
  }
430
- #P(e, t) {
431
- let n = new URL(this.#N(e), "http://localhost");
401
+ #F(e, t) {
402
+ let n = new URL(this.#P(e), "http://localhost");
432
403
  return {
433
404
  hash: n.hash.replace(/^#/, ""),
434
405
  historyState: t,
435
- pathname: y(n.pathname, this.#e),
406
+ pathname: v(n.pathname, this.#e),
436
407
  query: _(n.search)
437
408
  };
438
409
  }
439
- #F(e) {
410
+ #I(e) {
440
411
  let t = new URLSearchParams();
441
412
  for (let [n, r] of Object.entries(e.query)) Array.isArray(r) ? r.forEach((e) => {
442
413
  t.append(n, e);
@@ -444,8 +415,8 @@ var Router = class {
444
415
  let n = t.toString(), r = e.hash ? `#${e.hash}` : "";
445
416
  return `${p(this.#e, e.pathname)}${n ? `?${n}` : ""}${r}`;
446
417
  }
447
- #I(e) {
448
- let t = new URL(e, "http://localhost"), n = y(t.pathname, this.#e), { params: r, record: i } = m(n, this.#i);
418
+ #L(e) {
419
+ let t = new URL(e, "http://localhost"), n = v(t.pathname, this.#e), { params: r, record: i } = m(n, this.#i);
449
420
  return {
450
421
  name: i?.leaf.name,
451
422
  params: r,
@@ -453,17 +424,17 @@ var Router = class {
453
424
  query: _(t.search)
454
425
  };
455
426
  }
456
- async #L(e, t = {}) {
427
+ async #R(e, t = {}) {
457
428
  this.#b();
458
- let n = this.#N(e);
429
+ let n = this.#P(e);
459
430
  if (!t.force && n === this.#m) return;
460
- let r = this.#u.begin(), i = this.#d.matches.map((e) => e.name), a = await u(this.#l, i, this.#I(n));
431
+ let r = this.#u.begin(), i = this.#d.matches.map((e) => e.name), a = await u(this.#l, i, this.#L(n));
461
432
  if (r.isCurrent() && a) try {
462
- await this.#A(r, this.#P(n, t.state), (e, t) => {
433
+ await this.#j(r, n, t.state, (e, t) => {
463
434
  if (!r.isCurrent()) return;
464
- let n = this.#F(e);
435
+ let n = this.#I(e);
465
436
  t ? this.#r.replace(n, e.historyState) : this.#r.push(n, e.historyState), this.#m = n;
466
- }, t.viewTransition, 0, t.replace ?? !1);
437
+ }, t.viewTransition, t.replace ?? !1);
467
438
  } catch (e) {
468
439
  throw isRouterErrorCarrier(e) ? e.error : e;
469
440
  }
@@ -1 +1 @@
1
- {"version":3,"file":"router.js","names":["route","routesByName","name","available","WayfinderRouteError","target","path","buildUrl","base","ROUTER_ERROR","value","createNavigationCoordinator","compiled","compileRoutes","options","#base","normalizePath","#globalMiddleware","#globalCoerceSearch","#history","createBrowserHistory","#onError","#scroll","#useViewTransition","#records","#routesByName","#currentState","createRouteState","nf","leafDef","#notFoundRecord","#unlistenHistory","#registerHistoryListener","#lastHref","pathname","search","hash","attempt","#navigation","navigationPromise","#handleRoute","readLocation","href","#hrefForLocation","location","replace","#runInBackground","state","views","#assertNotDisposed","#listeners","listener","destination","#navigateToPath","params","query","url","matchRouteFor","matchesPrefix","normalizedPathname","stripBase","record","branch","buildMatchBranch","prepared","#resolveUrl","defs","hasData","d","dataResults","error","status","effectiveSignal","context","createRouteContext","resolvedQuery","#loadData","#resolveDestination","existing","#preloads","work","#disposeController","#disposed","key","#preloaded","match","#reportError","m","unsub","resolve","reject","entry","blocker","#beforeLeaveBlockers","WayfinderDisposedError","newHref","previousHref","#handleHistoryNavigation","activeMatchNames","#navigationDestination","allowed","runLeaveBlockers","terminalRan","def","dataFn","err","i","parsed","parseQuery","#prepareRoute","WayfinderRedirectLoopError","coerce","#runTerminal","isCurrent","preloadKey","preloading","cached","#notifyListeners","signal","onDataError","previousState","currentLocation","depth","#locationFromPath","commit","useTransition","nfDefs","nfBranch","committed","dataError","hasDataError","nfResolvedQuery","notified","executeMiddlewarePipeline","#applyScroll","#runWithTransition","startViewTransition","run","decision","to","from","normalizedPath","joinPaths","item"],"sources":["../src/router.ts"],"sourcesContent":["import { createNavigationCoordinator, type NavigationAttempt } from './_navigation';\nimport { compileRoutes } from './compile';\nimport {\n buildMatchBranch,\n createRouteContext,\n createRouteState,\n executeMiddlewarePipeline,\n reportError,\n} from './context';\nimport { WayfinderDisposedError, WayfinderRedirectLoopError, WayfinderRouteError } from './errors';\nimport { type RegisteredBlocker, runLeaveBlockers } from './guards';\nimport { createBrowserHistory } from './history';\nimport {\n buildUrl,\n joinPaths,\n matchesPrefix,\n matchRouteFor,\n normalizePath,\n parseQuery,\n readLocation,\n stripBase,\n} from './path';\nimport type {\n BeforeLeaveBlocker,\n BeforeLeaveOptions,\n CoerceSearchFn,\n DataContext,\n DataFn,\n HistoryDriver,\n IsActiveOptions,\n Middleware,\n NamedNavigationTarget,\n NavigateOptions,\n NavigationDestination,\n PathParams,\n RawNavigationTarget,\n ResolvedQueryParams,\n RouteBranchDef,\n RouteContext,\n RouteLocation,\n RouteMatchBranch,\n RouteName,\n RouteParams,\n RoutePathByName,\n RouteRecord,\n RouterErrorContext,\n RouterOptions,\n RouteState,\n RouteTable,\n RouteViewMap,\n RouteViewName,\n RouteViewRegistry,\n Unsubscribe,\n} from './types';\n\n// ─── Module-level helpers ────────────────────────────────────────────────────\n\nfunction getRouteByName(name: string, routesByName: ReadonlyMap<string, RouteRecord>): RouteRecord {\n const route = routesByName.get(name);\n\n if (route) return route;\n\n const available = [...routesByName.keys()].join(', ');\n\n throw new WayfinderRouteError(\n available ? `Unknown route name: ${name}. Available routes: ${available}` : `Unknown route name: ${name}`,\n );\n}\n\nfunction resolveTarget(\n target: { path: string } | { hash?: string; name: string; params?: RouteParams; query?: ResolvedQueryParams },\n routesByName: ReadonlyMap<string, RouteRecord>,\n base = '/',\n): string {\n if ('path' in target) return target.path;\n\n const route = getRouteByName(target.name, routesByName);\n const path = buildUrl(base, route.path, target.params, target.query);\n\n return target.hash ? `${path}#${target.hash}` : path;\n}\n\n// ─── Internal error carrier ──────────────────────────────────────────────────\n//\n// Carries error context alongside the original error without mutating the thrown\n// object. The carrier is unwrapped before reaching external callers so error\n// identity and `cause` chains are preserved.\n\nconst ROUTER_ERROR = Symbol('wayfinder.routerError');\n\ntype RouterErrorCarrier = {\n [ROUTER_ERROR]: true;\n readonly error: unknown;\n readonly context: RouterErrorContext;\n};\n\nfunction carryError(error: unknown, context: RouterErrorContext): RouterErrorCarrier {\n return { [ROUTER_ERROR]: true, context, error };\n}\n\nfunction isRouterErrorCarrier(value: unknown): value is RouterErrorCarrier {\n return value !== null && typeof value === 'object' && ROUTER_ERROR in (value as Record<symbol, unknown>);\n}\n\nfunction unwrapCarrier(value: unknown): never {\n if (isRouterErrorCarrier(value)) throw value.error;\n\n throw value;\n}\n\n// ─── Internal types ───────────────────────────────────────────────────────────\n\ntype NavigationDecision =\n | {\n branch: RouteMatchBranch;\n location: RouteLocation;\n params: RouteParams;\n record: RouteRecord;\n resolvedQuery: ResolvedQueryParams;\n type: 'matched';\n }\n | { location: RouteLocation; params: RouteParams; type: 'unmatched' }\n | { location: RouteLocation; params: RouteParams; redirectTo: string; type: 'redirect' };\n\n// ─── Router class ─────────────────────────────────────────────────────────────\n\nclass Router<TRoutes extends RouteTable = RouteTable> {\n readonly #base: string;\n readonly #globalMiddleware: readonly Middleware[];\n readonly #globalCoerceSearch?: CoerceSearchFn;\n readonly #history: HistoryDriver;\n readonly #records: readonly RouteRecord[];\n readonly #routesByName: ReadonlyMap<string, RouteRecord>;\n readonly #onError?: RouterOptions<TRoutes>['onError'];\n readonly #scroll?: RouterOptions<TRoutes>['scroll'];\n readonly #useViewTransition: boolean;\n\n // Mutable navigation state\n readonly #beforeLeaveBlockers = new Set<RegisteredBlocker>();\n readonly #navigation = createNavigationCoordinator();\n #currentState: RouteState;\n #disposed = false;\n readonly #disposeController = new AbortController();\n #lastHref = '/';\n readonly #listeners = new Set<(state: RouteState) => void>();\n readonly #preloaded = new Map<string, unknown[]>();\n readonly #preloads = new Map<string, Promise<RouteState | null>>();\n // Compiled notFound fallback record\n readonly #notFoundRecord: RouteRecord | null;\n\n readonly #unlistenHistory: () => void;\n\n /** Resolves when the constructor-triggered navigation has settled; rejects if it fails. */\n readonly ready: Promise<void>;\n\n constructor(options: RouterOptions<TRoutes>) {\n const compiled = compileRoutes(options);\n\n this.#base = normalizePath(options.base ?? '/');\n this.#globalMiddleware = (options.middleware ?? []) as unknown as Middleware[];\n this.#globalCoerceSearch = options.coerceSearch;\n this.#history = options.history ?? createBrowserHistory();\n this.#onError = options.onError;\n this.#scroll = options.scroll;\n this.#useViewTransition = options.viewTransition ?? false;\n this.#records = compiled.records as unknown as readonly RouteRecord[];\n this.#routesByName = compiled.routesByName as unknown as ReadonlyMap<string, RouteRecord>;\n this.#currentState = createRouteState({\n location: { hash: '', historyState: null, pathname: '/', query: {} },\n matches: [] as RouteMatchBranch,\n status: 'idle',\n });\n\n // Build a synthetic RouteRecord for the notFound fallback.\n if (options.notFound) {\n const nf = options.notFound;\n const leafDef: RouteBranchDef = {\n dataFn: nf.data,\n name: '__notFound__',\n };\n\n this.#notFoundRecord = {\n branchDefs: [leafDef],\n leaf: leafDef,\n matcher: { paramNames: [], pattern: /(?:)/, prefixPattern: /(?:)/ },\n ownMiddleware: (nf.middleware ?? []) as unknown as Middleware[],\n path: '/*',\n };\n } else {\n this.#notFoundRecord = null;\n }\n\n this.#unlistenHistory = this.#registerHistoryListener();\n\n const { hash, pathname, search } = this.#history.location;\n\n this.#lastHref = `${pathname}${search}${hash}`;\n\n const attempt = this.#navigation.begin();\n\n const navigationPromise = this.#handleRoute(\n attempt,\n readLocation(this.#base, this.#history),\n (location, replace) => {\n if (!attempt.isCurrent()) return;\n\n const href = this.#hrefForLocation(location);\n\n if (replace) this.#history.replace(href, location.historyState);\n\n this.#lastHref = href;\n },\n undefined,\n 0,\n false,\n ).then(() => undefined);\n\n // ready rejects with the original error (carrier unwrapped) for external consumers.\n this.ready = navigationPromise.catch(unwrapCarrier);\n // Attach a silent handler so an unawaited ready promise doesn't trigger\n // an unhandled-rejection warning. External consumers can still await ready\n // and receive the rejection: each .catch() subscriber fires independently.\n this.ready.catch(() => {});\n // #runInBackground receives the raw promise so it can extract carrier context for onError.\n this.#runInBackground(navigationPromise, { source: 'initial-navigation' });\n\n // Router actions are intentionally bound once so they remain safe when destructured.\n this.beforeLeave = this.beforeLeave.bind(this);\n this.createViewRegistry = this.createViewRegistry.bind(this);\n this.dispose = this.dispose.bind(this);\n this.getSnapshot = this.getSnapshot.bind(this);\n this.isActive = this.isActive.bind(this);\n this.load = this.load.bind(this);\n this.match = this.match.bind(this);\n this.navigate = this.navigate.bind(this);\n this.preload = this.preload.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.url = this.url.bind(this);\n this.waitFor = this.waitFor.bind(this);\n }\n\n // ─── Public state ─────────────────────────────────────────────────────────\n\n /**\n * Returns the current immutable router state snapshot.\n *\n * Compatible with React's `useSyncExternalStore`:\n * ```ts\n * const state = useSyncExternalStore(\n * (cb) => router.subscribe(cb),\n * () => router.getSnapshot()\n * );\n * ```\n */\n getSnapshot(): RouteState {\n return this.#currentState;\n }\n\n createViewRegistry<const TViews extends RouteViewMap<TRoutes>, TNotFound = never>(\n views: TViews & Record<Exclude<keyof TViews, RouteViewName<TRoutes>>, never>,\n options?: { notFound?: TNotFound },\n ): RouteViewRegistry<TViews[keyof TViews] | TNotFound> {\n return {\n resolve: (state) => {\n const name = state.matches.at(-1)?.name;\n\n if (name === '__notFound__') return options?.notFound;\n\n return name ? (views[name as keyof TViews] as TViews[keyof TViews]) : undefined;\n },\n };\n }\n\n // ─── Subscription ─────────────────────────────────────────────────────────\n\n /**\n * Subscribe to state changes. The listener is called on each subsequent state change;\n * use `getSnapshot()` to read the current value immediately.\n */\n subscribe(listener: (state: RouteState) => void): Unsubscribe {\n this.#assertNotDisposed();\n this.#listeners.add(listener);\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n // ─── Navigation ───────────────────────────────────────────────────────────\n\n /**\n * Navigate using a named route target or a raw path target.\n *\n * If a data loader throws after terminal execution begins, history has already committed\n * the destination and the returned Promise rejects with the loader error.\n */\n navigate(\n target: NamedNavigationTarget<TRoutes> | RawNavigationTarget | string,\n options?: NavigateOptions,\n ): Promise<void> {\n const normalized = typeof target === 'string' ? { path: target } : target;\n const destination = resolveTarget(normalized, this.#routesByName);\n\n return this.#navigateToPath(destination, options);\n }\n\n // ─── URL helpers ──────────────────────────────────────────────────────────\n\n /** Build a URL for a named route, including optional params and query string. */\n url<Name extends RouteName<TRoutes>>(\n name: Name,\n params?: PathParams<RoutePathByName<TRoutes, Name>>,\n query?: ResolvedQueryParams,\n ): string {\n const route = getRouteByName(name, this.#routesByName);\n\n return buildUrl(this.#base, route.path, params, query);\n }\n\n /**\n * Build an anchor-ready href for a named route: the address-bar form for the configured\n * history driver. `url()` returns the router-internal path; under `createHashHistory`\n * the same route lives behind `#`, and `href()` returns that form for `<a>` elements.\n */\n href<Name extends RouteName<TRoutes>>(\n name: Name,\n params?: PathParams<RoutePathByName<TRoutes, Name>>,\n query?: ResolvedQueryParams,\n ): string {\n const route = getRouteByName(name, this.#routesByName);\n const url = buildUrl(this.#base, route.path, params, query);\n\n return this.#history.href?.(url) ?? url;\n }\n\n /** Returns true when the current location matches the named route by prefix (default) or exactly. */\n isActive<Name extends RouteName<TRoutes>>(name: Name, options: IsActiveOptions = {}): boolean {\n const route = getRouteByName(name, this.#routesByName);\n const pathname = this.#currentState.location.pathname;\n const exact = options.exact ?? false;\n\n return exact ? matchRouteFor(pathname, [route]).record != null : matchesPrefix(pathname, route);\n }\n\n /** Match a pathname to a route branch without running middleware or data loaders. Returns null for redirects or no match. */\n match(pathname: string): RouteMatchBranch | null {\n const normalizedPathname = stripBase(normalizePath(pathname), this.#base);\n const { params, record } = matchRouteFor(normalizedPathname, this.#records);\n\n if (!record || record.redirect) return null;\n\n const branch = buildMatchBranch(\n record.branchDefs,\n params,\n normalizedPathname,\n record.branchDefs.map(() => undefined),\n );\n\n return branch.length ? branch : null;\n }\n\n /**\n * Load a URL into a route state including data loader results, without modifying\n * router state or history. Follows declarative redirects but does not cache results.\n * Middleware is not executed: use `navigate()` when middleware side effects are needed.\n */\n async load(url: string, options?: { signal?: AbortSignal }): Promise<RouteState | null> {\n const prepared = await this.#resolveUrl(url);\n\n if (prepared.type !== 'matched') return null;\n\n const { location, params, record, resolvedQuery } = prepared;\n const defs = record.branchDefs;\n const hasData = defs.some((d) => d.dataFn != null);\n let dataResults: unknown[] = defs.map(() => undefined);\n let error: unknown;\n let status: 'error' | 'idle' = 'idle';\n\n if (hasData) {\n const effectiveSignal = options?.signal ?? new AbortController().signal;\n const branch = buildMatchBranch(defs, params, location.pathname, dataResults);\n const context = createRouteContext<TRoutes>(location, resolvedQuery, params, branch, () => Promise.resolve());\n\n try {\n dataResults = await this.#loadData(defs, context, effectiveSignal);\n } catch (e) {\n error = e;\n status = 'error';\n }\n }\n\n return createRouteState({\n error,\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status,\n });\n }\n\n async preload(target: NamedNavigationTarget<TRoutes>): Promise<RouteState | null> {\n this.#assertNotDisposed();\n\n const destination = this.#resolveDestination(resolveTarget(target, this.#routesByName, this.#base));\n const existing = this.#preloads.get(destination);\n\n if (existing) return existing;\n\n const work = this.load(destination, { signal: this.#disposeController.signal })\n .then((state) => {\n if (this.#disposed) throw this.#disposeController.signal.reason;\n\n if (state?.status === 'error') throw state.error;\n\n if (state) {\n const key = this.#hrefForLocation(state.location);\n\n if (this.#preloaded.size >= 20) this.#preloaded.delete(this.#preloaded.keys().next().value!);\n\n this.#preloaded.set(\n key,\n state.matches.map((match) => match.data),\n );\n }\n\n return state;\n })\n .catch((error) => {\n if (this.#onError) this.#reportError(error, { source: 'preload' });\n\n throw error;\n })\n .finally(() => {\n this.#preloads.delete(destination);\n });\n\n this.#preloads.set(destination, work);\n\n return work;\n }\n\n /**\n * Returns a Promise that resolves the next time the router reaches `status: 'idle'`\n * and the active matches include a route named `name`.\n *\n * - Resolves immediately if the router is already `idle` at `name`.\n * - Rejects immediately if the router is already in `status: 'error'`.\n * - If the router is currently `idle` at a **different** route and no navigation is in\n * flight, this promise will not resolve until a future navigation lands on `name`.\n * Typical use-case is awaiting a navigation you just triggered:\n * `router.navigate(target); await router.waitFor('routeName')`.\n * @throws {WayfinderDisposedError} if the router is disposed while the promise is pending,\n * or if called after the router has already been disposed.\n */\n waitFor(name: RouteName<TRoutes>): Promise<RouteState> {\n this.#assertNotDisposed();\n\n return new Promise((resolve, reject) => {\n const matchesName = (state: RouteState): boolean =>\n state.status === 'idle' && state.matches.some((m) => m.name === name);\n\n if (this.#currentState.status === 'error') {\n reject(this.#currentState.error);\n\n return;\n }\n\n if (matchesName(this.#currentState)) {\n resolve(this.#currentState);\n\n return;\n }\n\n const unsub = this.subscribe((state) => {\n if (matchesName(state)) {\n unsub();\n resolve(state);\n } else if (state.status === 'error') {\n unsub();\n reject(state.error);\n }\n });\n\n this.#disposeController.signal.addEventListener(\n 'abort',\n () => {\n unsub();\n reject(this.#disposeController.signal.reason);\n },\n { once: true },\n );\n });\n }\n\n // ─── Navigation guards ────────────────────────────────────────────────────\n\n /**\n * Register a leave guard. Called before user-triggered navigation attempts.\n * Return `false` to cancel; `true` to allow.\n * Returns a function that removes the guard.\n *\n * Use `options.routes` to scope the guard to specific routes (fires only when navigating\n * away from a route whose name appears in the array, checked against any node in the active branch).\n */\n beforeLeave(blocker: BeforeLeaveBlocker, options?: BeforeLeaveOptions<TRoutes>): Unsubscribe {\n this.#assertNotDisposed();\n\n const entry: RegisteredBlocker = {\n handler: blocker,\n routes: options?.routes as string[] | undefined,\n };\n\n this.#beforeLeaveBlockers.add(entry);\n\n return () => {\n this.#beforeLeaveBlockers.delete(entry);\n };\n }\n\n // ─── Lifecycle ────────────────────────────────────────────────────────────\n\n get disposalSignal(): AbortSignal {\n return this.#disposeController.signal;\n }\n\n get disposed(): boolean {\n return this.#disposed;\n }\n\n /** Dispose event listeners and prevent further router interaction. Idempotent. */\n dispose(): void {\n if (this.#disposed) return;\n\n this.#disposed = true;\n this.#beforeLeaveBlockers.clear();\n this.#listeners.clear();\n this.#preloaded.clear();\n this.#preloads.clear();\n this.#navigation.invalidate(new WayfinderDisposedError());\n this.#unlistenHistory();\n // Abort the disposal signal last: waitFor() listeners clean themselves up via this signal.\n this.#disposeController.abort(new WayfinderDisposedError());\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n // ─── Private: assertions ──────────────────────────────────────────────────\n\n #assertNotDisposed(): void {\n if (this.#disposed) throw new WayfinderDisposedError();\n }\n\n // ─── Private: history listener ────────────────────────────────────────────\n\n #registerHistoryListener(): () => void {\n return this.#history.onPopstate(() => {\n const { hash, pathname, search } = this.#history.location;\n const newHref = `${pathname}${search}${hash}`;\n const previousHref = this.#lastHref;\n\n if (newHref === previousHref) return;\n\n this.#runInBackground(this.#handleHistoryNavigation(newHref, previousHref), { source: 'history-listener' });\n });\n }\n\n async #handleHistoryNavigation(newHref: string, previousHref: string): Promise<void> {\n const attempt = this.#navigation.begin();\n const activeMatchNames = this.#currentState.matches.map((m) => m.name);\n const destination = this.#navigationDestination(newHref);\n const allowed = await runLeaveBlockers(this.#beforeLeaveBlockers, activeMatchNames, destination);\n\n if (!attempt.isCurrent()) return;\n\n if (!allowed) {\n this.#history.replace(previousHref, this.#currentState.location.historyState);\n\n return;\n }\n\n const terminalRan = await this.#handleRoute(\n attempt,\n readLocation(this.#base, this.#history),\n (location, replace) => {\n if (!attempt.isCurrent()) return;\n\n const href = this.#hrefForLocation(location);\n\n if (replace) this.#history.replace(href, location.historyState);\n\n this.#lastHref = href;\n },\n undefined,\n 0,\n false,\n );\n\n if (attempt.isCurrent() && !terminalRan) {\n this.#history.replace(previousHref, this.#currentState.location.historyState);\n }\n }\n\n // ─── Private: error handling ──────────────────────────────────────────────\n\n #reportError(error: unknown, context: RouterErrorContext): void {\n reportError(error, context, this.#onError);\n }\n\n #runInBackground(promise: Promise<void>, context: RouterErrorContext): void {\n void promise.catch((value) => {\n if (isRouterErrorCarrier(value)) {\n this.#reportError(value.error, value.context);\n } else {\n this.#reportError(value, context);\n }\n });\n }\n\n // ─── Private: listener notification ──────────────────────────────────────\n\n #notifyListeners(): void {\n for (const listener of [...this.#listeners]) {\n try {\n listener(this.#currentState);\n } catch (error) {\n // A throwing subscriber must not abort the rest of the notify pass or\n // corrupt navigation state; surface it as an unhandled error instead.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n }\n\n // ─── Private: data loaders ────────────────────────────────────────────────\n\n /**\n * Run all data loaders and return their results. Per-def `onError` boundaries are applied.\n */\n async #loadData(\n defs: readonly RouteBranchDef[],\n context: RouteContext<RouteParams, TRoutes>,\n signal: AbortSignal,\n ): Promise<unknown[]> {\n return Promise.all(\n defs.map(async (def) => {\n if (!def.dataFn) return undefined;\n\n const dataFn = def.dataFn as unknown as DataFn<RouteParams, TRoutes>;\n\n try {\n return await dataFn({ ...context, signal } as DataContext<RouteParams, TRoutes>);\n } catch (err) {\n if (def.onError) return def.onError(err, { ...context, signal } as unknown as DataContext);\n\n throw err;\n }\n }),\n );\n }\n\n // ─── Private: URL resolution ──────────────────────────────────────────────\n\n /** Parse a URL, call #prepareRoute, and follow declarative redirects up to 5 hops. */\n async #resolveUrl(url: string): Promise<NavigationDecision> {\n let destination = url;\n\n for (let i = 0; i < 5; i += 1) {\n const parsed = new URL(destination, 'http://localhost');\n const location: RouteLocation = {\n hash: parsed.hash.replace(/^#/, ''),\n historyState: null,\n pathname: stripBase(parsed.pathname, this.#base),\n query: parseQuery(parsed.search),\n };\n\n const prepared = await this.#prepareRoute(location);\n\n if (prepared.type !== 'redirect') return prepared;\n\n destination = this.#resolveDestination(prepared.redirectTo);\n }\n\n throw new WayfinderRedirectLoopError();\n }\n\n // ─── Private: route preparation ───────────────────────────────────────────\n\n async #prepareRoute(location: RouteLocation): Promise<NavigationDecision> {\n const { params, record } = matchRouteFor(location.pathname, this.#records);\n\n if (!record) {\n return { location, params, type: 'unmatched' };\n }\n\n if (record.redirect) {\n return {\n location,\n params,\n redirectTo: resolveTarget(record.redirect, this.#routesByName, this.#base),\n type: 'redirect',\n };\n }\n\n let resolvedQuery: ResolvedQueryParams = location.query;\n\n const coerce: CoerceSearchFn | undefined = record.coerceSearch ?? this.#globalCoerceSearch;\n\n if (coerce) {\n try {\n resolvedQuery = coerce(location.query);\n } catch (err) {\n this.#reportError(err, { source: 'coerce-search' });\n resolvedQuery = location.query;\n }\n }\n\n return {\n branch: buildMatchBranch(\n record.branchDefs,\n params,\n location.pathname,\n record.branchDefs.map(() => undefined),\n ),\n location,\n params,\n record,\n resolvedQuery,\n type: 'matched',\n };\n }\n\n // ─── Private: terminal (data only) ────────────────────────────────────────\n\n async #runTerminal(\n record: RouteRecord,\n context: RouteContext<RouteParams, TRoutes>,\n location: RouteLocation,\n params: RouteParams,\n signal: AbortSignal,\n isCurrent: () => boolean,\n onDataError?: (error: unknown) => void,\n ): Promise<void> {\n if (!isCurrent()) return;\n\n const defs = record.branchDefs;\n const hasData = defs.some((d) => d.dataFn != null);\n let dataResults: unknown[] = defs.map(() => undefined);\n\n if (hasData) {\n const preloadKey = this.#hrefForLocation(location);\n const preloading = this.#preloads.get(preloadKey);\n\n if (preloading) {\n await preloading.catch(() => undefined);\n\n if (!isCurrent()) return;\n }\n\n const cached = this.#preloaded.get(preloadKey);\n\n if (cached) {\n this.#preloaded.delete(preloadKey);\n dataResults = cached;\n } else {\n this.#currentState = createRouteState({\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status: 'loading',\n });\n this.#notifyListeners();\n\n try {\n dataResults = await this.#loadData(defs, context, signal);\n } catch (error) {\n if (!isCurrent()) return;\n\n this.#currentState = createRouteState({\n error,\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status: 'error',\n });\n onDataError?.(error);\n throw error;\n }\n }\n }\n\n if (!isCurrent()) return;\n\n this.#currentState = createRouteState({\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status: 'idle',\n });\n }\n\n // ─── Private: main navigation orchestrator ────────────────────────────────\n\n /**\n * Declarative redirects reuse the active attempt and replace the final history entry.\n * Middleware redirects call `ctx.navigate()`, which starts a new attempt.\n */\n async #handleRoute(\n attempt: NavigationAttempt,\n currentLocation: RouteLocation,\n commit: (location: RouteLocation, replace: boolean) => void,\n useTransition?: boolean,\n depth = 0,\n replace = false,\n ): Promise<boolean> {\n const previousState = this.#currentState;\n const isCurrent = (): boolean => attempt.isCurrent() && !this.#disposed;\n const prepared = await this.#prepareRoute(currentLocation);\n\n if (!isCurrent()) return false;\n\n if (prepared.type === 'redirect') {\n if (depth >= 5) throw new WayfinderRedirectLoopError();\n\n return this.#handleRoute(\n attempt,\n this.#locationFromPath(prepared.redirectTo, currentLocation.historyState),\n commit,\n useTransition,\n depth + 1,\n true,\n );\n }\n\n if (prepared.type === 'unmatched') {\n // Fall back to notFound record when defined.\n if (this.#notFoundRecord) {\n const nfDefs = [this.#notFoundRecord.leaf];\n const nfBranch = buildMatchBranch(nfDefs, {}, currentLocation.pathname, [undefined]);\n let committed = false;\n let dataError: unknown;\n let hasDataError = false;\n let terminalRan = false;\n\n // Apply global coerceSearch to the unmatched location so notFound handlers\n // receive typed query params, consistent with matched-route behaviour.\n let nfResolvedQuery: ResolvedQueryParams = currentLocation.query;\n let notified = false;\n\n if (this.#globalCoerceSearch) {\n try {\n nfResolvedQuery = this.#globalCoerceSearch(currentLocation.query);\n } catch (err) {\n this.#reportError(err, { source: 'coerce-search' });\n }\n }\n\n const run = async (): Promise<void> => {\n if (!isCurrent()) return;\n\n const context = createRouteContext<TRoutes>(\n currentLocation,\n nfResolvedQuery,\n {},\n nfBranch,\n (target, options) => this.navigate(target, options),\n );\n\n terminalRan = await executeMiddlewarePipeline(\n context,\n [...this.#globalMiddleware, ...this.#notFoundRecord!.ownMiddleware] as unknown as Middleware<TRoutes>[],\n async () => {\n if (!isCurrent()) return;\n\n committed = true;\n commit(currentLocation, replace);\n\n if (!isCurrent()) return;\n\n await this.#runTerminal(\n this.#notFoundRecord!,\n context,\n currentLocation,\n {},\n attempt.signal,\n isCurrent,\n (error) => {\n dataError = error;\n hasDataError = true;\n },\n );\n\n if (!isCurrent()) return;\n\n // Swap and scroll while the view transition is still open: the new view renders\n // and the scroll resets before the new-state capture, so neither change lands\n // as an uncovered jump after the animation ends.\n notified = true;\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n },\n (error) =>\n isRouterErrorCarrier(error) || (hasDataError && error === dataError)\n ? error\n : carryError(error, { routeName: '__notFound__', source: 'middleware' }),\n );\n };\n\n try {\n await this.#runWithTransition(run, useTransition);\n } catch (error) {\n if (hasDataError && error === dataError) {\n throw carryError(error, { routeName: '__notFound__', source: 'data-loader' });\n }\n\n throw error;\n } finally {\n // Abort and error paths skip the in-run swap above; they still settle here.\n if (isCurrent() && committed && !notified) {\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n }\n }\n\n return terminalRan && committed;\n }\n\n if (!isCurrent()) return false;\n\n commit(prepared.location, replace);\n\n if (!isCurrent()) return false;\n\n this.#currentState = createRouteState({\n location: prepared.location,\n matches: [] as RouteMatchBranch,\n status: 'idle',\n });\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n\n return true;\n }\n\n const { branch, location, params, record, resolvedQuery } = prepared;\n let committed = false;\n let dataError: unknown;\n let hasDataError = false;\n let terminalRan = false;\n let notified = false;\n\n const run = async (): Promise<void> => {\n if (!isCurrent()) return;\n\n const context = createRouteContext<TRoutes>(location, resolvedQuery, params, branch, (target, options) =>\n this.navigate(target, options),\n );\n\n terminalRan = await executeMiddlewarePipeline(\n context,\n [...this.#globalMiddleware, ...record.ownMiddleware] as unknown as Middleware<TRoutes>[],\n async () => {\n if (!isCurrent()) return;\n\n committed = true;\n commit(location, replace);\n\n if (!isCurrent()) return;\n\n await this.#runTerminal(record, context, location, params, attempt.signal, isCurrent, (error) => {\n dataError = error;\n hasDataError = true;\n });\n\n if (!isCurrent()) return;\n\n // Swap and scroll while the view transition is still open: the new view renders\n // and the scroll resets before the new-state capture, so neither change lands\n // as an uncovered jump after the animation ends.\n notified = true;\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n },\n (error) =>\n isRouterErrorCarrier(error) || (hasDataError && error === dataError)\n ? error\n : carryError(error, { routeName: record.leaf.name, source: 'middleware' }),\n );\n };\n\n try {\n await this.#runWithTransition(run, useTransition);\n } catch (error) {\n if (hasDataError && error === dataError) {\n throw carryError(error, { routeName: record.leaf.name, source: 'data-loader' });\n }\n\n throw error;\n } finally {\n // Abort and error paths skip the in-run swap above; they still settle here.\n if (isCurrent() && committed && !notified) {\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n }\n }\n\n return terminalRan && committed;\n }\n\n async #runWithTransition(run: () => Promise<void>, useTransition?: boolean): Promise<void> {\n if ((useTransition ?? this.#useViewTransition) && typeof document !== 'undefined') {\n const startViewTransition = (\n document as Document & {\n startViewTransition?: (callback: () => void | Promise<void>) => { finished: Promise<void> };\n }\n ).startViewTransition;\n\n if (startViewTransition) {\n await startViewTransition.call(document, run).finished;\n\n return;\n }\n }\n\n await run();\n }\n\n #applyScroll(to: RouteState, from: RouteState): void {\n if (!this.#scroll || typeof window === 'undefined') return;\n\n const decision = this.#scroll(to, from);\n\n if (decision === 'preserve') return;\n\n if (decision === 'top') {\n window.scrollTo(0, 0);\n\n return;\n }\n\n window.scrollTo(decision.x, decision.y);\n }\n\n // ─── Private: destination resolution ─────────────────────────────────────\n\n #resolveDestination(path: string): string {\n const parsed = new URL(path, 'http://localhost');\n const normalizedPath = stripBase(parsed.pathname, this.#base);\n\n return `${joinPaths(this.#base, normalizedPath)}${parsed.search}${parsed.hash}`;\n }\n\n #locationFromPath(path: string, historyState: unknown): RouteLocation {\n const parsed = new URL(this.#resolveDestination(path), 'http://localhost');\n\n return {\n hash: parsed.hash.replace(/^#/, ''),\n historyState,\n pathname: stripBase(parsed.pathname, this.#base),\n query: parseQuery(parsed.search),\n };\n }\n\n #hrefForLocation(location: RouteLocation): string {\n const search = new URLSearchParams();\n\n for (const [key, value] of Object.entries(location.query)) {\n if (Array.isArray(value))\n value.forEach((item) => {\n search.append(key, item);\n });\n else search.set(key, value);\n }\n\n const query = search.toString();\n const hash = location.hash ? `#${location.hash}` : '';\n\n return `${joinPaths(this.#base, location.pathname)}${query ? `?${query}` : ''}${hash}`;\n }\n\n #navigationDestination(href: string): NavigationDestination {\n const parsed = new URL(href, 'http://localhost');\n const pathname = stripBase(parsed.pathname, this.#base);\n const { params, record } = matchRouteFor(pathname, this.#records);\n\n return {\n name: record?.leaf.name,\n params,\n pathname,\n query: parseQuery(parsed.search),\n };\n }\n\n /** User-initiated navigation. History changes only after middleware reaches the terminal stage. */\n async #navigateToPath(path: string, options: NavigateOptions = {}): Promise<void> {\n this.#assertNotDisposed();\n\n const destination = this.#resolveDestination(path);\n\n if (!options.force && destination === this.#lastHref) return;\n\n const attempt = this.#navigation.begin();\n const activeMatchNames = this.#currentState.matches.map((match) => match.name);\n const allowed = await runLeaveBlockers(\n this.#beforeLeaveBlockers,\n activeMatchNames,\n this.#navigationDestination(destination),\n );\n\n if (!attempt.isCurrent() || !allowed) return;\n\n try {\n await this.#handleRoute(\n attempt,\n this.#locationFromPath(destination, options.state),\n (location, replace) => {\n if (!attempt.isCurrent()) return;\n\n const href = this.#hrefForLocation(location);\n\n if (replace) this.#history.replace(href, location.historyState);\n else this.#history.push(href, location.historyState);\n\n this.#lastHref = href;\n },\n options.viewTransition,\n 0,\n options.replace ?? false,\n );\n } catch (value) {\n throw isRouterErrorCarrier(value) ? value.error : value;\n }\n }\n}\n\n// ─── Public factory ───────────────────────────────────────────────────────────\n\n/**\n * Create a new router instance from a route table.\n *\n * @example\n * const router = createRouter({\n * routes: {\n * home: { path: '/' },\n * userDetail: { path: '/users/:id', data: fetchUser },\n * },\n * });\n */\nexport function createRouter<const TRoutes extends RouteTable>(options: RouterOptions<TRoutes>): Router<TRoutes> {\n return new Router(options);\n}\n\n// Export the Router type (not the constructor value) for type annotations.\nexport type { Router };\n"],"mappings":";;;;;;;;AAyDA,SAAS,eAAe,GAAc,GAA6D;CACjG,IAAMA,IAAQC,EAAa,IAAIC,CAAI;CAEnC,IAAIF,GAAO,OAAOA;CAElB,IAAMG,IAAY,CAAC,GAAGF,EAAa,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI;CAEpD,MAAM,IAAIG,EACRD,IAAY,uBAAuBD,EAAK,sBAAsBC,MAAc,uBAAuBD,GACrG;AACF;AAEA,SAAS,cACP,GACA,GACA,IAAO,KACC;CACR,IAAI,UAAUG,GAAQ,OAAOA,EAAO;CAEpC,IAAML,IAAQ,eAAeK,EAAO,MAAMJ,CAAY,GAChDK,IAAOC,EAASC,GAAMR,EAAM,MAAMK,EAAO,QAAQA,EAAO,KAAK;CAEnE,OAAOA,EA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M;EACjC;CACF;CAGA,MAAMtD,GAAgB,GAAc,IAA2B,CAAC,GAAkB;EAChF,KAAKJ,GAAmB;EAExB,IAAMG,IAAc,KAAKyB,GAAoBvE,CAAI;EAEjD,IAAI,CAACQ,EAAQ,SAASsC,MAAgB,KAAKnB,IAAW;EAEtD,IAAMI,IAAU,KAAKC,GAAY,MAAM,GACjC4D,IAAmB,KAAKxE,GAAc,QAAQ,KAAK,MAAU2D,EAAM,IAAI,GACvEe,IAAU,MAAMC,EACpB,KAAKR,IACLK,GACA,KAAKC,GAAuB/C,CAAW,CACzC;EAEA,IAAKf,EAAQ,UAAU,KAAM+D,GAE7B,IAAI;GACF,MAAM,KAAK5D,GACTH,GACA,KAAKsF,GAAkBvE,GAAatC,EAAQ,KAAK,IAChD,GAAU,MAAY;IACrB,IAAI,CAACuB,EAAQ,UAAU,GAAG;IAE1B,IAAMK,IAAO,KAAKC,GAAiBC,CAAQ;IAK3C,AAHIC,IAAS,KAAK1B,GAAS,QAAQuB,GAAME,EAAS,YAAY,IACzD,KAAKzB,GAAS,KAAKuB,GAAME,EAAS,YAAY,GAEnD,KAAKX,KAAYS;GACnB,GACA5B,EAAQ,gBACR,GACAA,EAAQ,WAAW,EACrB;EACF,SAASJ,GAAO;GACd,MAAM,qBAAqBA,CAAK,IAAIA,EAAM,QAAQA;EACpD;CACF;AACF;AAeA,SAAgB,aAA+C,GAAkD;CAC/G,OAAO,IAAI,OAAOI,CAAO;AAC3B"}
1
+ {"version":3,"file":"router.js","names":["route","routesByName","name","available","WayfinderRouteError","target","path","buildUrl","base","ROUTER_ERROR","MAX_REDIRECT_HOPS","value","createNavigationCoordinator","compiled","compileRoutes","options","#base","normalizePath","#globalMiddleware","#globalCoerceSearch","#history","createBrowserHistory","#onError","#scroll","#useViewTransition","#records","#routesByName","#currentState","createRouteState","nf","leafDef","#notFoundRecord","#unlistenHistory","#registerHistoryListener","initialHref","pathname","search","hash","#lastHref","attempt","#navigation","navigationPromise","#handleRoute","state","href","#hrefForLocation","location","replace","#runInBackground","views","#assertNotDisposed","#listeners","listener","destination","#navigateToPath","params","query","url","matchRouteFor","matchesPrefix","normalizedPathname","stripBase","record","branch","buildMatchBranch","prepared","#resolveWithRedirects","defs","hasData","d","dataResults","error","status","effectiveSignal","context","createRouteContext","resolvedQuery","#loadData","#resolveDestination","existing","#preloads","work","#disposeController","#disposed","key","#preloaded","match","#reportError","m","unsub","resolve","reject","entry","blocker","#beforeLeaveBlockers","WayfinderDisposedError","newHref","previousHref","#handleHistoryNavigation","activeMatchNames","#navigationDestination","allowed","runLeaveBlockers","terminalRan","def","dataFn","err","hopped","hop","#prepareRoute","#locationFromPath","historyState","WayfinderRedirectLoopError","coerce","#coerceQuery","#runTerminal","isCurrent","preloadKey","preloading","cached","#notifyListeners","signal","onDataError","previousState","commit","#applyScroll","shouldReplace","committed","dataError","hasDataError","notified","executeMiddlewarePipeline","#runWithTransition","useTransition","startViewTransition","run","decision","to","from","parsed","normalizedPath","joinPaths","parseQuery","item"],"sources":["../src/router.ts"],"sourcesContent":["import { createNavigationCoordinator, type NavigationAttempt } from './_navigation';\nimport { compileRoutes } from './compile';\nimport {\n buildMatchBranch,\n createRouteContext,\n createRouteState,\n executeMiddlewarePipeline,\n reportError,\n} from './context';\nimport { WayfinderDisposedError, WayfinderRedirectLoopError, WayfinderRouteError } from './errors';\nimport { type RegisteredBlocker, runLeaveBlockers } from './guards';\nimport { createBrowserHistory } from './history';\nimport { buildUrl, joinPaths, matchesPrefix, matchRouteFor, normalizePath, parseQuery, stripBase } from './path';\nimport type {\n BeforeLeaveBlocker,\n BeforeLeaveOptions,\n CoerceSearchFn,\n DataContext,\n DataFn,\n HistoryDriver,\n IsActiveOptions,\n Middleware,\n NamedNavigationTarget,\n NavigateOptions,\n NavigationDestination,\n PathParams,\n RawNavigationTarget,\n ResolvedQueryParams,\n RouteBranchDef,\n RouteContext,\n RouteLocation,\n RouteMatchBranch,\n RouteName,\n RouteParams,\n RoutePathByName,\n RouteRecord,\n RouterErrorContext,\n RouterOptions,\n RouteState,\n RouteTable,\n RouteViewMap,\n RouteViewName,\n RouteViewRegistry,\n Unsubscribe,\n} from './types';\n\n// ─── Module-level helpers ────────────────────────────────────────────────────\n\nfunction getRouteByName(name: string, routesByName: ReadonlyMap<string, RouteRecord>): RouteRecord {\n const route = routesByName.get(name);\n\n if (route) return route;\n\n const available = [...routesByName.keys()].join(', ');\n\n throw new WayfinderRouteError(\n available ? `Unknown route name: ${name}. Available routes: ${available}` : `Unknown route name: ${name}`,\n );\n}\n\nfunction resolveTarget(\n target: { path: string } | { hash?: string; name: string; params?: RouteParams; query?: ResolvedQueryParams },\n routesByName: ReadonlyMap<string, RouteRecord>,\n base = '/',\n): string {\n if ('path' in target) return target.path;\n\n const route = getRouteByName(target.name, routesByName);\n const path = buildUrl(base, route.path, target.params, target.query);\n\n return target.hash ? `${path}#${target.hash}` : path;\n}\n\n// ─── Internal error carrier ──────────────────────────────────────────────────\n//\n// Carries error context alongside the original error without mutating the thrown\n// object. The carrier is unwrapped before reaching external callers so error\n// identity and `cause` chains are preserved.\n\nconst ROUTER_ERROR = Symbol('wayfinder.routerError');\n\n/** Declarative redirect hops the router follows before declaring a loop. */\nconst MAX_REDIRECT_HOPS = 5;\n\ntype RouterErrorCarrier = {\n [ROUTER_ERROR]: true;\n readonly error: unknown;\n readonly context: RouterErrorContext;\n};\n\nfunction carryError(error: unknown, context: RouterErrorContext): RouterErrorCarrier {\n return { [ROUTER_ERROR]: true, context, error };\n}\n\nfunction isRouterErrorCarrier(value: unknown): value is RouterErrorCarrier {\n return value !== null && typeof value === 'object' && ROUTER_ERROR in (value as Record<symbol, unknown>);\n}\n\nfunction unwrapCarrier(value: unknown): never {\n if (isRouterErrorCarrier(value)) throw value.error;\n\n throw value;\n}\n\n// ─── Internal types ───────────────────────────────────────────────────────────\n\ntype NavigationDecision =\n | {\n branch: RouteMatchBranch;\n location: RouteLocation;\n params: RouteParams;\n record: RouteRecord;\n resolvedQuery: ResolvedQueryParams;\n type: 'matched';\n }\n | { location: RouteLocation; params: RouteParams; type: 'unmatched' }\n | { location: RouteLocation; params: RouteParams; redirectTo: string; type: 'redirect' };\n\n/** The decision left after declarative redirects have been followed. */\ntype TerminalDecision = Exclude<NavigationDecision, { type: 'redirect' }>;\n\n// ─── Router class ─────────────────────────────────────────────────────────────\n\nclass Router<TRoutes extends RouteTable = RouteTable> {\n readonly #base: string;\n readonly #globalMiddleware: readonly Middleware[];\n readonly #globalCoerceSearch?: CoerceSearchFn;\n readonly #history: HistoryDriver;\n readonly #records: readonly RouteRecord[];\n readonly #routesByName: ReadonlyMap<string, RouteRecord>;\n readonly #onError?: RouterOptions<TRoutes>['onError'];\n readonly #scroll?: RouterOptions<TRoutes>['scroll'];\n readonly #useViewTransition: boolean;\n\n // Mutable navigation state\n readonly #beforeLeaveBlockers = new Set<RegisteredBlocker>();\n readonly #navigation = createNavigationCoordinator();\n #currentState: RouteState;\n #disposed = false;\n readonly #disposeController = new AbortController();\n #lastHref = '/';\n readonly #listeners = new Set<(state: RouteState) => void>();\n readonly #preloaded = new Map<string, unknown[]>();\n readonly #preloads = new Map<string, Promise<RouteState | null>>();\n // Compiled notFound fallback record\n readonly #notFoundRecord: RouteRecord | null;\n\n readonly #unlistenHistory: () => void;\n\n /** Resolves when the constructor-triggered navigation has settled; rejects if it fails. */\n readonly ready: Promise<void>;\n\n constructor(options: RouterOptions<TRoutes>) {\n const compiled = compileRoutes(options);\n\n this.#base = normalizePath(options.base ?? '/');\n this.#globalMiddleware = (options.middleware ?? []) as unknown as Middleware[];\n this.#globalCoerceSearch = options.coerceSearch;\n this.#history = options.history ?? createBrowserHistory();\n this.#onError = options.onError;\n this.#scroll = options.scroll;\n this.#useViewTransition = options.viewTransition ?? false;\n this.#records = compiled.records as unknown as readonly RouteRecord[];\n this.#routesByName = compiled.routesByName as unknown as ReadonlyMap<string, RouteRecord>;\n this.#currentState = createRouteState({\n location: { hash: '', historyState: null, pathname: '/', query: {} },\n matches: [] as RouteMatchBranch,\n status: 'idle',\n });\n\n // Build a synthetic RouteRecord for the notFound fallback.\n if (options.notFound) {\n const nf = options.notFound;\n const leafDef: RouteBranchDef = {\n dataFn: nf.data,\n name: '__notFound__',\n };\n\n this.#notFoundRecord = {\n branchDefs: [leafDef],\n leaf: leafDef,\n matcher: { paramNames: [], pattern: /(?:)/, prefixPattern: /(?:)/ },\n ownMiddleware: (nf.middleware ?? []) as unknown as Middleware[],\n path: '/*',\n };\n } else {\n this.#notFoundRecord = null;\n }\n\n this.#unlistenHistory = this.#registerHistoryListener();\n\n const { hash, pathname, search, state } = this.#history.location;\n const initialHref = `${pathname}${search}${hash}`;\n\n this.#lastHref = initialHref;\n\n const attempt = this.#navigation.begin();\n\n const navigationPromise = this.#handleRoute(\n attempt,\n initialHref,\n state,\n (location, replace) => {\n if (!attempt.isCurrent()) return;\n\n const href = this.#hrefForLocation(location);\n\n if (replace) this.#history.replace(href, location.historyState);\n\n this.#lastHref = href;\n },\n undefined,\n false,\n ).then(() => undefined);\n\n // ready rejects with the original error (carrier unwrapped) for external consumers.\n this.ready = navigationPromise.catch(unwrapCarrier);\n // Attach a silent handler so an unawaited ready promise doesn't trigger\n // an unhandled-rejection warning. External consumers can still await ready\n // and receive the rejection: each .catch() subscriber fires independently.\n this.ready.catch(() => {});\n // #runInBackground receives the raw promise so it can extract carrier context for onError.\n this.#runInBackground(navigationPromise, { source: 'initial-navigation' });\n\n // Router actions are intentionally bound once so they remain safe when destructured.\n this.beforeLeave = this.beforeLeave.bind(this);\n this.createViewRegistry = this.createViewRegistry.bind(this);\n this.dispose = this.dispose.bind(this);\n this.getSnapshot = this.getSnapshot.bind(this);\n this.isActive = this.isActive.bind(this);\n this.load = this.load.bind(this);\n this.match = this.match.bind(this);\n this.navigate = this.navigate.bind(this);\n this.preload = this.preload.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.url = this.url.bind(this);\n this.waitFor = this.waitFor.bind(this);\n }\n\n // ─── Public state ─────────────────────────────────────────────────────────\n\n /**\n * Returns the current immutable router state snapshot.\n *\n * Compatible with React's `useSyncExternalStore`:\n * ```ts\n * const state = useSyncExternalStore(\n * (cb) => router.subscribe(cb),\n * () => router.getSnapshot()\n * );\n * ```\n */\n getSnapshot(): RouteState {\n return this.#currentState;\n }\n\n createViewRegistry<const TViews extends RouteViewMap<TRoutes>, TNotFound = never>(\n views: TViews & Record<Exclude<keyof TViews, RouteViewName<TRoutes>>, never>,\n options?: { notFound?: TNotFound },\n ): RouteViewRegistry<TViews[keyof TViews] | TNotFound> {\n return {\n resolve: (state) => {\n const name = state.matches.at(-1)?.name;\n\n if (name === '__notFound__') return options?.notFound;\n\n return name ? (views[name as keyof TViews] as TViews[keyof TViews]) : undefined;\n },\n };\n }\n\n // ─── Subscription ─────────────────────────────────────────────────────────\n\n /**\n * Subscribe to state changes. The listener is called on each subsequent state change;\n * use `getSnapshot()` to read the current value immediately.\n */\n subscribe(listener: (state: RouteState) => void): Unsubscribe {\n this.#assertNotDisposed();\n this.#listeners.add(listener);\n\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n // ─── Navigation ───────────────────────────────────────────────────────────\n\n /**\n * Navigate using a named route target or a raw path target.\n *\n * If a data loader throws after terminal execution begins, history has already committed\n * the destination and the returned Promise rejects with the loader error.\n */\n navigate(\n target: NamedNavigationTarget<TRoutes> | RawNavigationTarget | string,\n options?: NavigateOptions,\n ): Promise<void> {\n const normalized = typeof target === 'string' ? { path: target } : target;\n const destination = resolveTarget(normalized, this.#routesByName, this.#base);\n\n return this.#navigateToPath(destination, options);\n }\n\n // ─── URL helpers ──────────────────────────────────────────────────────────\n\n /** Build a URL for a named route, including optional params and query string. */\n url<Name extends RouteName<TRoutes>>(\n name: Name,\n params?: PathParams<RoutePathByName<TRoutes, Name>>,\n query?: ResolvedQueryParams,\n ): string {\n const route = getRouteByName(name, this.#routesByName);\n\n return buildUrl(this.#base, route.path, params, query);\n }\n\n /**\n * Build an anchor-ready href for a named route: the address-bar form for the configured\n * history driver. `url()` returns the router-internal path; under `createHashHistory`\n * the same route lives behind `#`, and `href()` returns that form for `<a>` elements.\n */\n href<Name extends RouteName<TRoutes>>(\n name: Name,\n params?: PathParams<RoutePathByName<TRoutes, Name>>,\n query?: ResolvedQueryParams,\n ): string {\n const route = getRouteByName(name, this.#routesByName);\n const url = buildUrl(this.#base, route.path, params, query);\n\n return this.#history.href?.(url) ?? url;\n }\n\n /** Returns true when the current location matches the named route by prefix (default) or exactly. */\n isActive<Name extends RouteName<TRoutes>>(name: Name, options: IsActiveOptions = {}): boolean {\n const route = getRouteByName(name, this.#routesByName);\n const pathname = this.#currentState.location.pathname;\n const exact = options.exact ?? false;\n\n return exact ? matchRouteFor(pathname, [route]).record != null : matchesPrefix(pathname, route);\n }\n\n /** Match a pathname to a route branch without running middleware or data loaders. Returns null for redirects or no match. */\n match(pathname: string): RouteMatchBranch | null {\n const normalizedPathname = stripBase(normalizePath(pathname), this.#base);\n const { params, record } = matchRouteFor(normalizedPathname, this.#records);\n\n if (!record || record.redirect) return null;\n\n const branch = buildMatchBranch(\n record.branchDefs,\n params,\n normalizedPathname,\n record.branchDefs.map(() => undefined),\n );\n\n return branch.length ? branch : null;\n }\n\n /**\n * Load a router-internal URL into a route state including data loader results,\n * without modifying router state or history. Follows declarative redirects but\n * does not cache results. Middleware is not executed: use `navigate()` when\n * middleware side effects are needed. An unmatched URL resolves to the\n * `notFound` route when configured; otherwise `null` is returned.\n */\n async load(url: string, options?: { signal?: AbortSignal }): Promise<RouteState | null> {\n const { decision: prepared } = await this.#resolveWithRedirects(url, null);\n\n if (prepared.type !== 'matched') return null;\n\n const { location, params, record, resolvedQuery } = prepared;\n const defs = record.branchDefs;\n const hasData = defs.some((d) => d.dataFn != null);\n let dataResults: unknown[] = defs.map(() => undefined);\n let error: unknown;\n let status: 'error' | 'idle' = 'idle';\n\n if (hasData) {\n const effectiveSignal = options?.signal ?? new AbortController().signal;\n const branch = buildMatchBranch(defs, params, location.pathname, dataResults);\n const context = createRouteContext<TRoutes>(location, resolvedQuery, params, branch, () => Promise.resolve());\n\n try {\n dataResults = await this.#loadData(defs, context, effectiveSignal);\n } catch (e) {\n error = e;\n status = 'error';\n }\n }\n\n return createRouteState({\n error,\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status,\n });\n }\n\n async preload(target: NamedNavigationTarget<TRoutes>): Promise<RouteState | null> {\n this.#assertNotDisposed();\n\n const destination = this.#resolveDestination(resolveTarget(target, this.#routesByName, this.#base));\n const existing = this.#preloads.get(destination);\n\n if (existing) return existing;\n\n const work = this.load(destination, { signal: this.#disposeController.signal })\n .then((state) => {\n if (this.#disposed) throw this.#disposeController.signal.reason;\n\n if (state?.status === 'error') throw state.error;\n\n if (state) {\n const key = this.#hrefForLocation(state.location);\n\n if (this.#preloaded.size >= 20) this.#preloaded.delete(this.#preloaded.keys().next().value!);\n\n this.#preloaded.set(\n key,\n state.matches.map((match) => match.data),\n );\n }\n\n return state;\n })\n .catch((error) => {\n if (this.#onError) this.#reportError(error, { source: 'preload' });\n\n throw error;\n })\n .finally(() => {\n this.#preloads.delete(destination);\n });\n\n this.#preloads.set(destination, work);\n\n return work;\n }\n\n /**\n * Returns a Promise that resolves the next time the router reaches `status: 'idle'`\n * and the active matches include a route named `name`.\n *\n * - Resolves immediately if the router is already `idle` at `name`.\n * - Rejects immediately if the router is already in `status: 'error'`.\n * - If the router is currently `idle` at a **different** route and no navigation is in\n * flight, this promise will not resolve until a future navigation lands on `name`.\n * Typical use-case is awaiting a navigation you just triggered:\n * `router.navigate(target); await router.waitFor('routeName')`.\n * @throws {WayfinderDisposedError} if the router is disposed while the promise is pending,\n * or if called after the router has already been disposed.\n */\n waitFor(name: RouteName<TRoutes>): Promise<RouteState> {\n this.#assertNotDisposed();\n\n return new Promise((resolve, reject) => {\n const matchesName = (state: RouteState): boolean =>\n state.status === 'idle' && state.matches.some((m) => m.name === name);\n\n if (this.#currentState.status === 'error') {\n reject(this.#currentState.error);\n\n return;\n }\n\n if (matchesName(this.#currentState)) {\n resolve(this.#currentState);\n\n return;\n }\n\n const unsub = this.subscribe((state) => {\n if (matchesName(state)) {\n unsub();\n resolve(state);\n } else if (state.status === 'error') {\n unsub();\n reject(state.error);\n }\n });\n\n this.#disposeController.signal.addEventListener(\n 'abort',\n () => {\n unsub();\n reject(this.#disposeController.signal.reason);\n },\n { once: true },\n );\n });\n }\n\n // ─── Navigation guards ────────────────────────────────────────────────────\n\n /**\n * Register a leave guard. Called before user-triggered navigation attempts.\n * Return `false` to cancel; `true` to allow.\n * Returns a function that removes the guard.\n *\n * Use `options.routes` to scope the guard to specific routes (fires only when navigating\n * away from a route whose name appears in the array, checked against any node in the active branch).\n */\n beforeLeave(blocker: BeforeLeaveBlocker, options?: BeforeLeaveOptions<TRoutes>): Unsubscribe {\n this.#assertNotDisposed();\n\n const entry: RegisteredBlocker = {\n handler: blocker,\n routes: options?.routes as string[] | undefined,\n };\n\n this.#beforeLeaveBlockers.add(entry);\n\n return () => {\n this.#beforeLeaveBlockers.delete(entry);\n };\n }\n\n // ─── Lifecycle ────────────────────────────────────────────────────────────\n\n get disposalSignal(): AbortSignal {\n return this.#disposeController.signal;\n }\n\n get disposed(): boolean {\n return this.#disposed;\n }\n\n /** Dispose event listeners and prevent further router interaction. Idempotent. */\n dispose(): void {\n if (this.#disposed) return;\n\n this.#disposed = true;\n this.#beforeLeaveBlockers.clear();\n this.#listeners.clear();\n this.#preloaded.clear();\n this.#preloads.clear();\n this.#navigation.invalidate(new WayfinderDisposedError());\n this.#unlistenHistory();\n // Abort the disposal signal last: waitFor() listeners clean themselves up via this signal.\n this.#disposeController.abort(new WayfinderDisposedError());\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n // ─── Private: assertions ──────────────────────────────────────────────────\n\n #assertNotDisposed(): void {\n if (this.#disposed) throw new WayfinderDisposedError();\n }\n\n // ─── Private: history listener ────────────────────────────────────────────\n\n #registerHistoryListener(): () => void {\n return this.#history.onPopstate(() => {\n const { hash, pathname, search } = this.#history.location;\n const newHref = `${pathname}${search}${hash}`;\n const previousHref = this.#lastHref;\n\n if (newHref === previousHref) return;\n\n this.#runInBackground(this.#handleHistoryNavigation(newHref, previousHref), { source: 'history-listener' });\n });\n }\n\n async #handleHistoryNavigation(newHref: string, previousHref: string): Promise<void> {\n const attempt = this.#navigation.begin();\n const activeMatchNames = this.#currentState.matches.map((m) => m.name);\n const destination = this.#navigationDestination(newHref);\n const allowed = await runLeaveBlockers(this.#beforeLeaveBlockers, activeMatchNames, destination);\n\n if (!attempt.isCurrent()) return;\n\n if (!allowed) {\n this.#history.replace(previousHref, this.#currentState.location.historyState);\n\n return;\n }\n\n const terminalRan = await this.#handleRoute(\n attempt,\n newHref,\n this.#history.location.state,\n (location, replace) => {\n if (!attempt.isCurrent()) return;\n\n const href = this.#hrefForLocation(location);\n\n if (replace) this.#history.replace(href, location.historyState);\n\n this.#lastHref = href;\n },\n undefined,\n false,\n );\n\n if (attempt.isCurrent() && !terminalRan) {\n this.#history.replace(previousHref, this.#currentState.location.historyState);\n }\n }\n\n // ─── Private: error handling ──────────────────────────────────────────────\n\n #reportError(error: unknown, context: RouterErrorContext): void {\n reportError(error, context, this.#onError);\n }\n\n #runInBackground(promise: Promise<void>, context: RouterErrorContext): void {\n void promise.catch((value) => {\n if (isRouterErrorCarrier(value)) {\n this.#reportError(value.error, value.context);\n } else {\n this.#reportError(value, context);\n }\n });\n }\n\n // ─── Private: listener notification ──────────────────────────────────────\n\n #notifyListeners(): void {\n for (const listener of [...this.#listeners]) {\n try {\n listener(this.#currentState);\n } catch (error) {\n // A throwing subscriber must not abort the rest of the notify pass or\n // corrupt navigation state; surface it as an unhandled error instead.\n queueMicrotask(() => {\n throw error;\n });\n }\n }\n }\n\n // ─── Private: data loaders ────────────────────────────────────────────────\n\n /**\n * Run all data loaders and return their results. Per-def `onError` boundaries are applied.\n */\n async #loadData(\n defs: readonly RouteBranchDef[],\n context: RouteContext<RouteParams, TRoutes>,\n signal: AbortSignal,\n ): Promise<unknown[]> {\n return Promise.all(\n defs.map(async (def) => {\n if (!def.dataFn) return undefined;\n\n const dataFn = def.dataFn as unknown as DataFn<RouteParams, TRoutes>;\n\n try {\n return await dataFn({ ...context, signal } as DataContext<RouteParams, TRoutes>);\n } catch (err) {\n if (def.onError) return def.onError(err, { ...context, signal } as unknown as DataContext);\n\n throw err;\n }\n }),\n );\n }\n\n // ─── Private: URL resolution ──────────────────────────────────────────────\n\n /**\n * Resolve a router-internal URL to its terminal route, following declarative\n * redirects. This is the single redirect-following implementation shared by\n * navigations and `load()`. `hopped` reports whether any redirect was\n * followed; hopped navigations must replace rather than push history.\n */\n async #resolveWithRedirects(\n url: string,\n historyState: unknown,\n ): Promise<{ decision: TerminalDecision; hopped: boolean }> {\n let destination = url;\n let hopped = false;\n\n for (let hop = 0; ; hop += 1) {\n const prepared = await this.#prepareRoute(this.#locationFromPath(destination, historyState));\n\n if (prepared.type !== 'redirect') return { decision: prepared, hopped };\n\n if (hop >= MAX_REDIRECT_HOPS) throw new WayfinderRedirectLoopError();\n\n destination = prepared.redirectTo;\n hopped = true;\n }\n }\n\n /** Run a coercion function with fallback to the raw query, reporting failures through `onError`. */\n #coerceQuery(location: RouteLocation, coerce?: CoerceSearchFn): ResolvedQueryParams {\n if (!coerce) return location.query;\n\n try {\n return coerce(location.query);\n } catch (err) {\n this.#reportError(err, { source: 'coerce-search' });\n\n return location.query;\n }\n }\n\n // ─── Private: route preparation ───────────────────────────────────────────\n\n async #prepareRoute(location: RouteLocation): Promise<NavigationDecision> {\n const { params, record } = matchRouteFor(location.pathname, this.#records);\n\n if (!record) {\n // The configured notFound fallback is a plain route record: fold it into a\n // matched decision so fallback navigations run through the same pipeline.\n if (this.#notFoundRecord) {\n return {\n branch: buildMatchBranch(this.#notFoundRecord.branchDefs, {}, location.pathname, [undefined]),\n location,\n params: {},\n record: this.#notFoundRecord,\n resolvedQuery: this.#coerceQuery(location, this.#globalCoerceSearch),\n type: 'matched',\n };\n }\n\n return { location, params, type: 'unmatched' };\n }\n\n if (record.redirect) {\n return {\n location,\n params,\n redirectTo: resolveTarget(record.redirect, this.#routesByName, this.#base),\n type: 'redirect',\n };\n }\n\n const resolvedQuery = this.#coerceQuery(location, record.coerceSearch ?? this.#globalCoerceSearch);\n\n return {\n branch: buildMatchBranch(\n record.branchDefs,\n params,\n location.pathname,\n record.branchDefs.map(() => undefined),\n ),\n location,\n params,\n record,\n resolvedQuery,\n type: 'matched',\n };\n }\n\n // ─── Private: terminal (data only) ────────────────────────────────────────\n\n async #runTerminal(\n record: RouteRecord,\n context: RouteContext<RouteParams, TRoutes>,\n location: RouteLocation,\n params: RouteParams,\n signal: AbortSignal,\n isCurrent: () => boolean,\n onDataError?: (error: unknown) => void,\n ): Promise<void> {\n if (!isCurrent()) return;\n\n const defs = record.branchDefs;\n const hasData = defs.some((d) => d.dataFn != null);\n let dataResults: unknown[] = defs.map(() => undefined);\n\n if (hasData) {\n const preloadKey = this.#hrefForLocation(location);\n const preloading = this.#preloads.get(preloadKey);\n\n if (preloading) {\n await preloading.catch(() => undefined);\n\n if (!isCurrent()) return;\n }\n\n const cached = this.#preloaded.get(preloadKey);\n\n if (cached) {\n this.#preloaded.delete(preloadKey);\n dataResults = cached;\n } else {\n this.#currentState = createRouteState({\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status: 'loading',\n });\n this.#notifyListeners();\n\n try {\n dataResults = await this.#loadData(defs, context, signal);\n } catch (error) {\n if (!isCurrent()) return;\n\n this.#currentState = createRouteState({\n error,\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status: 'error',\n });\n onDataError?.(error);\n throw error;\n }\n }\n }\n\n if (!isCurrent()) return;\n\n this.#currentState = createRouteState({\n location,\n matches: buildMatchBranch(defs, params, location.pathname, dataResults),\n status: 'idle',\n });\n }\n\n // ─── Private: main navigation orchestrator ────────────────────────────────\n\n /**\n * Run a navigation to completion: resolve (following declarative redirects),\n * middleware, history commit, terminal data loaders, scroll, and notification.\n * Declarative redirects reuse the active attempt and replace the final history\n * entry. Middleware redirects call `ctx.navigate()`, which starts a new attempt.\n */\n async #handleRoute(\n attempt: NavigationAttempt,\n url: string,\n historyState: unknown,\n commit: (location: RouteLocation, replace: boolean) => void,\n useTransition: boolean | undefined,\n replace: boolean,\n ): Promise<boolean> {\n const previousState = this.#currentState;\n const isCurrent = (): boolean => attempt.isCurrent() && !this.#disposed;\n const { decision: prepared, hopped } = await this.#resolveWithRedirects(url, historyState);\n\n if (!isCurrent()) return false;\n\n if (prepared.type === 'unmatched') {\n commit(prepared.location, replace || hopped);\n\n if (!isCurrent()) return false;\n\n this.#currentState = createRouteState({\n location: prepared.location,\n matches: [] as RouteMatchBranch,\n status: 'idle',\n });\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n\n return true;\n }\n\n const { branch, location, params, record, resolvedQuery } = prepared;\n const shouldReplace = replace || hopped;\n let committed = false;\n let dataError: unknown;\n let hasDataError = false;\n let terminalRan = false;\n let notified = false;\n\n const run = async (): Promise<void> => {\n if (!isCurrent()) return;\n\n const context = createRouteContext<TRoutes>(location, resolvedQuery, params, branch, (target, options) =>\n this.navigate(target, options),\n );\n\n terminalRan = await executeMiddlewarePipeline(\n context,\n [...this.#globalMiddleware, ...record.ownMiddleware] as unknown as Middleware<TRoutes>[],\n async () => {\n if (!isCurrent()) return;\n\n committed = true;\n commit(location, shouldReplace);\n\n if (!isCurrent()) return;\n\n await this.#runTerminal(record, context, location, params, attempt.signal, isCurrent, (error) => {\n dataError = error;\n hasDataError = true;\n });\n\n if (!isCurrent()) return;\n\n // Swap and scroll while the view transition is still open: the new view renders\n // and the scroll resets before the new-state capture, so neither change lands\n // as an uncovered jump after the animation ends.\n notified = true;\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n },\n (error) =>\n isRouterErrorCarrier(error) || (hasDataError && error === dataError)\n ? error\n : carryError(error, { routeName: record.leaf.name, source: 'middleware' }),\n );\n };\n\n try {\n await this.#runWithTransition(run, useTransition);\n } catch (error) {\n if (hasDataError && error === dataError) {\n throw carryError(error, { routeName: record.leaf.name, source: 'data-loader' });\n }\n\n throw error;\n } finally {\n // Abort and error paths skip the in-run swap above; they still settle here.\n if (isCurrent() && committed && !notified) {\n this.#notifyListeners();\n this.#applyScroll(this.#currentState, previousState);\n }\n }\n\n return terminalRan && committed;\n }\n\n async #runWithTransition(run: () => Promise<void>, useTransition?: boolean): Promise<void> {\n if ((useTransition ?? this.#useViewTransition) && typeof document !== 'undefined') {\n const startViewTransition = (\n document as Document & {\n startViewTransition?: (callback: () => void | Promise<void>) => { finished: Promise<void> };\n }\n ).startViewTransition;\n\n if (startViewTransition) {\n await startViewTransition.call(document, run).finished;\n\n return;\n }\n }\n\n await run();\n }\n\n #applyScroll(to: RouteState, from: RouteState): void {\n if (!this.#scroll || typeof window === 'undefined') return;\n\n const decision = this.#scroll(to, from);\n\n if (decision === 'preserve') return;\n\n if (decision === 'top') {\n window.scrollTo(0, 0);\n\n return;\n }\n\n window.scrollTo(decision.x, decision.y);\n }\n\n // ─── Private: destination resolution ─────────────────────────────────────\n\n #resolveDestination(path: string): string {\n const parsed = new URL(path, 'http://localhost');\n const normalizedPath = stripBase(parsed.pathname, this.#base);\n\n return `${joinPaths(this.#base, normalizedPath)}${parsed.search}${parsed.hash}`;\n }\n\n #locationFromPath(path: string, historyState: unknown): RouteLocation {\n const parsed = new URL(this.#resolveDestination(path), 'http://localhost');\n\n return {\n hash: parsed.hash.replace(/^#/, ''),\n historyState,\n pathname: stripBase(parsed.pathname, this.#base),\n query: parseQuery(parsed.search),\n };\n }\n\n #hrefForLocation(location: RouteLocation): string {\n const search = new URLSearchParams();\n\n for (const [key, value] of Object.entries(location.query)) {\n if (Array.isArray(value))\n value.forEach((item) => {\n search.append(key, item);\n });\n else search.set(key, value);\n }\n\n const query = search.toString();\n const hash = location.hash ? `#${location.hash}` : '';\n\n return `${joinPaths(this.#base, location.pathname)}${query ? `?${query}` : ''}${hash}`;\n }\n\n #navigationDestination(href: string): NavigationDestination {\n const parsed = new URL(href, 'http://localhost');\n const pathname = stripBase(parsed.pathname, this.#base);\n const { params, record } = matchRouteFor(pathname, this.#records);\n\n return {\n name: record?.leaf.name,\n params,\n pathname,\n query: parseQuery(parsed.search),\n };\n }\n\n /** User-initiated navigation. History changes only after middleware reaches the terminal stage. */\n async #navigateToPath(path: string, options: NavigateOptions = {}): Promise<void> {\n this.#assertNotDisposed();\n\n const destination = this.#resolveDestination(path);\n\n if (!options.force && destination === this.#lastHref) return;\n\n const attempt = this.#navigation.begin();\n const activeMatchNames = this.#currentState.matches.map((match) => match.name);\n const allowed = await runLeaveBlockers(\n this.#beforeLeaveBlockers,\n activeMatchNames,\n this.#navigationDestination(destination),\n );\n\n if (!attempt.isCurrent() || !allowed) return;\n\n try {\n await this.#handleRoute(\n attempt,\n destination,\n options.state,\n (location, replace) => {\n if (!attempt.isCurrent()) return;\n\n const href = this.#hrefForLocation(location);\n\n if (replace) this.#history.replace(href, location.historyState);\n else this.#history.push(href, location.historyState);\n\n this.#lastHref = href;\n },\n options.viewTransition,\n options.replace ?? false,\n );\n } catch (value) {\n throw isRouterErrorCarrier(value) ? value.error : value;\n }\n }\n}\n\n// ─── Public factory ───────────────────────────────────────────────────────────\n\n/**\n * Create a new router instance from a route table.\n *\n * @example\n * const router = createRouter({\n * routes: {\n * home: { path: '/' },\n * userDetail: { path: '/users/:id', data: fetchUser },\n * },\n * });\n */\nexport function createRouter<const TRoutes extends RouteTable>(options: RouterOptions<TRoutes>): Router<TRoutes> {\n return new Router(options);\n}\n\n// Export the Router type (not the constructor value) for type annotations.\nexport type { Router };\n"],"mappings":";;;;;;;;AAgDA,SAAS,eAAe,GAAc,GAA6D;CACjG,IAAMA,IAAQC,EAAa,IAAIC,CAAI;CAEnC,IAAIF,GAAO,OAAOA;CAElB,IAAMG,IAAY,CAAC,GAAGF,EAAa,KAAK,CAAC,CAAC,CAAC,KAAK,IAAI;CAEpD,MAAM,IAAIG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