@tanstack/router-core 1.114.24 → 1.114.29

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,3 +1,13 @@
1
+ import { Store, batch } from "@tanstack/store";
2
+ import { createMemoryHistory, createBrowserHistory, parseHref } from "@tanstack/history";
3
+ import invariant from "tiny-invariant";
4
+ import { pick, createControlledPromise, deepEqual, replaceEqualDeep, last, functionalUpdate } from "./utils.js";
5
+ import { trimPath, trimPathLeft, parsePathname, resolvePath, cleanPath, trimPathRight, matchPathname, interpolatePath, joinPaths } from "./path.js";
6
+ import { isNotFound } from "./not-found.js";
7
+ import { setupScrollRestoration } from "./scroll-restoration.js";
8
+ import { defaultParseSearch, defaultStringifySearch } from "./searchParams.js";
9
+ import { rootRouteId } from "./root.js";
10
+ import { isResolvedRedirect, isRedirect } from "./redirect.js";
1
11
  function defaultSerializeError(err) {
2
12
  if (err instanceof Error) {
3
13
  const obj = {
@@ -21,8 +31,1693 @@ function getLocationChangeInfo(routerState) {
21
31
  const hashChanged = (fromLocation == null ? void 0 : fromLocation.hash) !== toLocation.hash;
22
32
  return { fromLocation, toLocation, pathChanged, hrefChanged, hashChanged };
23
33
  }
34
+ class RouterCore {
35
+ /**
36
+ * @deprecated Use the `createRouter` function instead
37
+ */
38
+ constructor(options) {
39
+ this.tempLocationKey = `${Math.round(
40
+ Math.random() * 1e7
41
+ )}`;
42
+ this.resetNextScroll = true;
43
+ this.shouldViewTransition = void 0;
44
+ this.isViewTransitionTypesSupported = void 0;
45
+ this.subscribers = /* @__PURE__ */ new Set();
46
+ this.isScrollRestoring = false;
47
+ this.isScrollRestorationSetup = false;
48
+ this.startTransition = (fn) => fn();
49
+ this.update = (newOptions) => {
50
+ var _a;
51
+ if (newOptions.notFoundRoute) {
52
+ console.warn(
53
+ "The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/framework/react/guide/not-found-errors#migrating-from-notfoundroute for more info."
54
+ );
55
+ }
56
+ const previousOptions = this.options;
57
+ this.options = {
58
+ ...this.options,
59
+ ...newOptions
60
+ };
61
+ this.isServer = this.options.isServer ?? typeof document === "undefined";
62
+ this.pathParamsDecodeCharMap = this.options.pathParamsAllowedCharacters ? new Map(
63
+ this.options.pathParamsAllowedCharacters.map((char) => [
64
+ encodeURIComponent(char),
65
+ char
66
+ ])
67
+ ) : void 0;
68
+ if (!this.basepath || newOptions.basepath && newOptions.basepath !== previousOptions.basepath) {
69
+ if (newOptions.basepath === void 0 || newOptions.basepath === "" || newOptions.basepath === "/") {
70
+ this.basepath = "/";
71
+ } else {
72
+ this.basepath = `/${trimPath(newOptions.basepath)}`;
73
+ }
74
+ }
75
+ if (
76
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
77
+ !this.history || this.options.history && this.options.history !== this.history
78
+ ) {
79
+ this.history = this.options.history ?? (this.isServer ? createMemoryHistory({
80
+ initialEntries: [this.basepath || "/"]
81
+ }) : createBrowserHistory());
82
+ this.latestLocation = this.parseLocation();
83
+ }
84
+ if (this.options.routeTree !== this.routeTree) {
85
+ this.routeTree = this.options.routeTree;
86
+ this.buildRouteTree();
87
+ }
88
+ if (!this.__store) {
89
+ this.__store = new Store(getInitialRouterState(this.latestLocation), {
90
+ onUpdate: () => {
91
+ this.__store.state = {
92
+ ...this.state,
93
+ cachedMatches: this.state.cachedMatches.filter(
94
+ (d) => !["redirected"].includes(d.status)
95
+ )
96
+ };
97
+ }
98
+ });
99
+ setupScrollRestoration(this);
100
+ }
101
+ if (typeof window !== "undefined" && "CSS" in window && // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
102
+ typeof ((_a = window.CSS) == null ? void 0 : _a.supports) === "function") {
103
+ this.isViewTransitionTypesSupported = window.CSS.supports(
104
+ "selector(:active-view-transition-type(a)"
105
+ );
106
+ }
107
+ };
108
+ this.buildRouteTree = () => {
109
+ this.routesById = {};
110
+ this.routesByPath = {};
111
+ const notFoundRoute = this.options.notFoundRoute;
112
+ if (notFoundRoute) {
113
+ notFoundRoute.init({
114
+ originalIndex: 99999999999,
115
+ defaultSsr: this.options.defaultSsr
116
+ });
117
+ this.routesById[notFoundRoute.id] = notFoundRoute;
118
+ }
119
+ const recurseRoutes = (childRoutes) => {
120
+ childRoutes.forEach((childRoute, i) => {
121
+ childRoute.init({
122
+ originalIndex: i,
123
+ defaultSsr: this.options.defaultSsr
124
+ });
125
+ const existingRoute = this.routesById[childRoute.id];
126
+ invariant(
127
+ !existingRoute,
128
+ `Duplicate routes found with id: ${String(childRoute.id)}`
129
+ );
130
+ this.routesById[childRoute.id] = childRoute;
131
+ if (!childRoute.isRoot && childRoute.path) {
132
+ const trimmedFullPath = trimPathRight(childRoute.fullPath);
133
+ if (!this.routesByPath[trimmedFullPath] || childRoute.fullPath.endsWith("/")) {
134
+ this.routesByPath[trimmedFullPath] = childRoute;
135
+ }
136
+ }
137
+ const children = childRoute.children;
138
+ if (children == null ? void 0 : children.length) {
139
+ recurseRoutes(children);
140
+ }
141
+ });
142
+ };
143
+ recurseRoutes([this.routeTree]);
144
+ const scoredRoutes = [];
145
+ const routes = Object.values(this.routesById);
146
+ routes.forEach((d, i) => {
147
+ var _a;
148
+ if (d.isRoot || !d.path) {
149
+ return;
150
+ }
151
+ const trimmed = trimPathLeft(d.fullPath);
152
+ const parsed = parsePathname(trimmed);
153
+ while (parsed.length > 1 && ((_a = parsed[0]) == null ? void 0 : _a.value) === "/") {
154
+ parsed.shift();
155
+ }
156
+ const scores = parsed.map((segment) => {
157
+ if (segment.value === "/") {
158
+ return 0.75;
159
+ }
160
+ if (segment.type === "param") {
161
+ return 0.5;
162
+ }
163
+ if (segment.type === "wildcard") {
164
+ return 0.25;
165
+ }
166
+ return 1;
167
+ });
168
+ scoredRoutes.push({ child: d, trimmed, parsed, index: i, scores });
169
+ });
170
+ this.flatRoutes = scoredRoutes.sort((a, b) => {
171
+ const minLength = Math.min(a.scores.length, b.scores.length);
172
+ for (let i = 0; i < minLength; i++) {
173
+ if (a.scores[i] !== b.scores[i]) {
174
+ return b.scores[i] - a.scores[i];
175
+ }
176
+ }
177
+ if (a.scores.length !== b.scores.length) {
178
+ return b.scores.length - a.scores.length;
179
+ }
180
+ for (let i = 0; i < minLength; i++) {
181
+ if (a.parsed[i].value !== b.parsed[i].value) {
182
+ return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
183
+ }
184
+ }
185
+ return a.index - b.index;
186
+ }).map((d, i) => {
187
+ d.child.rank = i;
188
+ return d.child;
189
+ });
190
+ };
191
+ this.subscribe = (eventType, fn) => {
192
+ const listener = {
193
+ eventType,
194
+ fn
195
+ };
196
+ this.subscribers.add(listener);
197
+ return () => {
198
+ this.subscribers.delete(listener);
199
+ };
200
+ };
201
+ this.emit = (routerEvent) => {
202
+ this.subscribers.forEach((listener) => {
203
+ if (listener.eventType === routerEvent.type) {
204
+ listener.fn(routerEvent);
205
+ }
206
+ });
207
+ };
208
+ this.parseLocation = (previousLocation, locationToParse) => {
209
+ const parse = ({
210
+ pathname,
211
+ search,
212
+ hash,
213
+ state
214
+ }) => {
215
+ const parsedSearch = this.options.parseSearch(search);
216
+ const searchStr = this.options.stringifySearch(parsedSearch);
217
+ return {
218
+ pathname,
219
+ searchStr,
220
+ search: replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.search, parsedSearch),
221
+ hash: hash.split("#").reverse()[0] ?? "",
222
+ href: `${pathname}${searchStr}${hash}`,
223
+ state: replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.state, state)
224
+ };
225
+ };
226
+ const location = parse(locationToParse ?? this.history.location);
227
+ const { __tempLocation, __tempKey } = location.state;
228
+ if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
229
+ const parsedTempLocation = parse(__tempLocation);
230
+ parsedTempLocation.state.key = location.state.key;
231
+ delete parsedTempLocation.state.__tempLocation;
232
+ return {
233
+ ...parsedTempLocation,
234
+ maskedLocation: location
235
+ };
236
+ }
237
+ return location;
238
+ };
239
+ this.resolvePathWithBase = (from, path) => {
240
+ const resolvedPath = resolvePath({
241
+ basepath: this.basepath,
242
+ base: from,
243
+ to: cleanPath(path),
244
+ trailingSlash: this.options.trailingSlash,
245
+ caseSensitive: this.options.caseSensitive
246
+ });
247
+ return resolvedPath;
248
+ };
249
+ this.matchRoutes = (pathnameOrNext, locationSearchOrOpts, opts) => {
250
+ if (typeof pathnameOrNext === "string") {
251
+ return this.matchRoutesInternal(
252
+ {
253
+ pathname: pathnameOrNext,
254
+ search: locationSearchOrOpts
255
+ },
256
+ opts
257
+ );
258
+ } else {
259
+ return this.matchRoutesInternal(pathnameOrNext, locationSearchOrOpts);
260
+ }
261
+ };
262
+ this.getMatchedRoutes = (next, dest) => {
263
+ let routeParams = {};
264
+ const trimmedPath = trimPathRight(next.pathname);
265
+ const getMatchedParams = (route) => {
266
+ const result = matchPathname(this.basepath, trimmedPath, {
267
+ to: route.fullPath,
268
+ caseSensitive: route.options.caseSensitive ?? this.options.caseSensitive,
269
+ fuzzy: true
270
+ });
271
+ return result;
272
+ };
273
+ let foundRoute = (dest == null ? void 0 : dest.to) !== void 0 ? this.routesByPath[dest.to] : void 0;
274
+ if (foundRoute) {
275
+ routeParams = getMatchedParams(foundRoute);
276
+ } else {
277
+ foundRoute = this.flatRoutes.find((route) => {
278
+ const matchedParams = getMatchedParams(route);
279
+ if (matchedParams) {
280
+ routeParams = matchedParams;
281
+ return true;
282
+ }
283
+ return false;
284
+ });
285
+ }
286
+ let routeCursor = foundRoute || this.routesById[rootRouteId];
287
+ const matchedRoutes = [routeCursor];
288
+ while (routeCursor.parentRoute) {
289
+ routeCursor = routeCursor.parentRoute;
290
+ matchedRoutes.unshift(routeCursor);
291
+ }
292
+ return { matchedRoutes, routeParams, foundRoute };
293
+ };
294
+ this.cancelMatch = (id) => {
295
+ const match = this.getMatch(id);
296
+ if (!match) return;
297
+ match.abortController.abort();
298
+ clearTimeout(match.pendingTimeout);
299
+ };
300
+ this.cancelMatches = () => {
301
+ var _a;
302
+ (_a = this.state.pendingMatches) == null ? void 0 : _a.forEach((match) => {
303
+ this.cancelMatch(match.id);
304
+ });
305
+ };
306
+ this.buildLocation = (opts) => {
307
+ const build = (dest = {}, matchedRoutesResult) => {
308
+ var _a, _b, _c, _d, _e, _f, _g;
309
+ const fromMatches = dest._fromLocation ? this.matchRoutes(dest._fromLocation, { _buildLocation: true }) : this.state.matches;
310
+ const fromMatch = dest.from != null ? fromMatches.find(
311
+ (d) => matchPathname(this.basepath, trimPathRight(d.pathname), {
312
+ to: dest.from,
313
+ caseSensitive: false,
314
+ fuzzy: false
315
+ })
316
+ ) : void 0;
317
+ const fromPath = (fromMatch == null ? void 0 : fromMatch.pathname) || this.latestLocation.pathname;
318
+ invariant(
319
+ dest.from == null || fromMatch != null,
320
+ "Could not find match for from: " + dest.from
321
+ );
322
+ const fromSearch = ((_a = this.state.pendingMatches) == null ? void 0 : _a.length) ? (_b = last(this.state.pendingMatches)) == null ? void 0 : _b.search : ((_c = last(fromMatches)) == null ? void 0 : _c.search) || this.latestLocation.search;
323
+ const stayingMatches = matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.filter(
324
+ (d) => fromMatches.find((e) => e.routeId === d.id)
325
+ );
326
+ let pathname;
327
+ if (dest.to) {
328
+ const resolvePathTo = (fromMatch == null ? void 0 : fromMatch.fullPath) || ((_d = last(fromMatches)) == null ? void 0 : _d.fullPath) || this.latestLocation.pathname;
329
+ pathname = this.resolvePathWithBase(resolvePathTo, `${dest.to}`);
330
+ } else {
331
+ const fromRouteByFromPathRouteId = this.routesById[(_e = stayingMatches == null ? void 0 : stayingMatches.find((route) => {
332
+ const interpolatedPath = interpolatePath({
333
+ path: route.fullPath,
334
+ params: (matchedRoutesResult == null ? void 0 : matchedRoutesResult.routeParams) ?? {},
335
+ decodeCharMap: this.pathParamsDecodeCharMap
336
+ }).interpolatedPath;
337
+ const pathname2 = joinPaths([this.basepath, interpolatedPath]);
338
+ return pathname2 === fromPath;
339
+ })) == null ? void 0 : _e.id];
340
+ pathname = this.resolvePathWithBase(
341
+ fromPath,
342
+ (fromRouteByFromPathRouteId == null ? void 0 : fromRouteByFromPathRouteId.to) ?? fromPath
343
+ );
344
+ }
345
+ const prevParams = { ...(_f = last(fromMatches)) == null ? void 0 : _f.params };
346
+ let nextParams = (dest.params ?? true) === true ? prevParams : {
347
+ ...prevParams,
348
+ ...functionalUpdate(dest.params, prevParams)
349
+ };
350
+ if (Object.keys(nextParams).length > 0) {
351
+ matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.map((route) => {
352
+ var _a2;
353
+ return ((_a2 = route.options.params) == null ? void 0 : _a2.stringify) ?? route.options.stringifyParams;
354
+ }).filter(Boolean).forEach((fn) => {
355
+ nextParams = { ...nextParams, ...fn(nextParams) };
356
+ });
357
+ }
358
+ pathname = interpolatePath({
359
+ path: pathname,
360
+ params: nextParams ?? {},
361
+ leaveWildcards: false,
362
+ leaveParams: opts.leaveParams,
363
+ decodeCharMap: this.pathParamsDecodeCharMap
364
+ }).interpolatedPath;
365
+ let search = fromSearch;
366
+ if (opts._includeValidateSearch && ((_g = this.options.search) == null ? void 0 : _g.strict)) {
367
+ let validatedSearch = {};
368
+ matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.forEach((route) => {
369
+ try {
370
+ if (route.options.validateSearch) {
371
+ validatedSearch = {
372
+ ...validatedSearch,
373
+ ...validateSearch(route.options.validateSearch, {
374
+ ...validatedSearch,
375
+ ...search
376
+ }) ?? {}
377
+ };
378
+ }
379
+ } catch {
380
+ }
381
+ });
382
+ search = validatedSearch;
383
+ }
384
+ const applyMiddlewares = (search2) => {
385
+ const allMiddlewares = (matchedRoutesResult == null ? void 0 : matchedRoutesResult.matchedRoutes.reduce(
386
+ (acc, route) => {
387
+ var _a2;
388
+ const middlewares = [];
389
+ if ("search" in route.options) {
390
+ if ((_a2 = route.options.search) == null ? void 0 : _a2.middlewares) {
391
+ middlewares.push(...route.options.search.middlewares);
392
+ }
393
+ } else if (route.options.preSearchFilters || route.options.postSearchFilters) {
394
+ const legacyMiddleware = ({
395
+ search: search3,
396
+ next
397
+ }) => {
398
+ let nextSearch = search3;
399
+ if ("preSearchFilters" in route.options && route.options.preSearchFilters) {
400
+ nextSearch = route.options.preSearchFilters.reduce(
401
+ (prev, next2) => next2(prev),
402
+ search3
403
+ );
404
+ }
405
+ const result = next(nextSearch);
406
+ if ("postSearchFilters" in route.options && route.options.postSearchFilters) {
407
+ return route.options.postSearchFilters.reduce(
408
+ (prev, next2) => next2(prev),
409
+ result
410
+ );
411
+ }
412
+ return result;
413
+ };
414
+ middlewares.push(legacyMiddleware);
415
+ }
416
+ if (opts._includeValidateSearch && route.options.validateSearch) {
417
+ const validate = ({ search: search3, next }) => {
418
+ const result = next(search3);
419
+ try {
420
+ const validatedSearch = {
421
+ ...result,
422
+ ...validateSearch(
423
+ route.options.validateSearch,
424
+ result
425
+ ) ?? {}
426
+ };
427
+ return validatedSearch;
428
+ } catch {
429
+ return result;
430
+ }
431
+ };
432
+ middlewares.push(validate);
433
+ }
434
+ return acc.concat(middlewares);
435
+ },
436
+ []
437
+ )) ?? [];
438
+ const final = ({ search: search3 }) => {
439
+ if (!dest.search) {
440
+ return {};
441
+ }
442
+ if (dest.search === true) {
443
+ return search3;
444
+ }
445
+ return functionalUpdate(dest.search, search3);
446
+ };
447
+ allMiddlewares.push(final);
448
+ const applyNext = (index, currentSearch) => {
449
+ if (index >= allMiddlewares.length) {
450
+ return currentSearch;
451
+ }
452
+ const middleware = allMiddlewares[index];
453
+ const next = (newSearch) => {
454
+ return applyNext(index + 1, newSearch);
455
+ };
456
+ return middleware({ search: currentSearch, next });
457
+ };
458
+ return applyNext(0, search2);
459
+ };
460
+ search = applyMiddlewares(search);
461
+ search = replaceEqualDeep(fromSearch, search);
462
+ const searchStr = this.options.stringifySearch(search);
463
+ const hash = dest.hash === true ? this.latestLocation.hash : dest.hash ? functionalUpdate(dest.hash, this.latestLocation.hash) : void 0;
464
+ const hashStr = hash ? `#${hash}` : "";
465
+ let nextState = dest.state === true ? this.latestLocation.state : dest.state ? functionalUpdate(dest.state, this.latestLocation.state) : {};
466
+ nextState = replaceEqualDeep(this.latestLocation.state, nextState);
467
+ return {
468
+ pathname,
469
+ search,
470
+ searchStr,
471
+ state: nextState,
472
+ hash: hash ?? "",
473
+ href: `${pathname}${searchStr}${hashStr}`,
474
+ unmaskOnReload: dest.unmaskOnReload
475
+ };
476
+ };
477
+ const buildWithMatches = (dest = {}, maskedDest) => {
478
+ var _a;
479
+ const next = build(dest);
480
+ let maskedNext = maskedDest ? build(maskedDest) : void 0;
481
+ if (!maskedNext) {
482
+ let params = {};
483
+ const foundMask = (_a = this.options.routeMasks) == null ? void 0 : _a.find((d) => {
484
+ const match = matchPathname(this.basepath, next.pathname, {
485
+ to: d.from,
486
+ caseSensitive: false,
487
+ fuzzy: false
488
+ });
489
+ if (match) {
490
+ params = match;
491
+ return true;
492
+ }
493
+ return false;
494
+ });
495
+ if (foundMask) {
496
+ const { from: _from, ...maskProps } = foundMask;
497
+ maskedDest = {
498
+ ...pick(opts, ["from"]),
499
+ ...maskProps,
500
+ params
501
+ };
502
+ maskedNext = build(maskedDest);
503
+ }
504
+ }
505
+ const nextMatches = this.getMatchedRoutes(next, dest);
506
+ const final = build(dest, nextMatches);
507
+ if (maskedNext) {
508
+ const maskedMatches = this.getMatchedRoutes(maskedNext, maskedDest);
509
+ const maskedFinal = build(maskedDest, maskedMatches);
510
+ final.maskedLocation = maskedFinal;
511
+ }
512
+ return final;
513
+ };
514
+ if (opts.mask) {
515
+ return buildWithMatches(opts, {
516
+ ...pick(opts, ["from"]),
517
+ ...opts.mask
518
+ });
519
+ }
520
+ return buildWithMatches(opts);
521
+ };
522
+ this.commitLocation = ({
523
+ viewTransition,
524
+ ignoreBlocker,
525
+ ...next
526
+ }) => {
527
+ const isSameState = () => {
528
+ const ignoredProps = [
529
+ "key",
530
+ "__TSR_index",
531
+ "__hashScrollIntoViewOptions"
532
+ ];
533
+ ignoredProps.forEach((prop) => {
534
+ next.state[prop] = this.latestLocation.state[prop];
535
+ });
536
+ const isEqual = deepEqual(next.state, this.latestLocation.state);
537
+ ignoredProps.forEach((prop) => {
538
+ delete next.state[prop];
539
+ });
540
+ return isEqual;
541
+ };
542
+ const isSameUrl = this.latestLocation.href === next.href;
543
+ const previousCommitPromise = this.commitLocationPromise;
544
+ this.commitLocationPromise = createControlledPromise(() => {
545
+ previousCommitPromise == null ? void 0 : previousCommitPromise.resolve();
546
+ });
547
+ if (isSameUrl && isSameState()) {
548
+ this.load();
549
+ } else {
550
+ let { maskedLocation, hashScrollIntoView, ...nextHistory } = next;
551
+ if (maskedLocation) {
552
+ nextHistory = {
553
+ ...maskedLocation,
554
+ state: {
555
+ ...maskedLocation.state,
556
+ __tempKey: void 0,
557
+ __tempLocation: {
558
+ ...nextHistory,
559
+ search: nextHistory.searchStr,
560
+ state: {
561
+ ...nextHistory.state,
562
+ __tempKey: void 0,
563
+ __tempLocation: void 0,
564
+ key: void 0
565
+ }
566
+ }
567
+ }
568
+ };
569
+ if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) {
570
+ nextHistory.state.__tempKey = this.tempLocationKey;
571
+ }
572
+ }
573
+ nextHistory.state.__hashScrollIntoViewOptions = hashScrollIntoView ?? this.options.defaultHashScrollIntoView ?? true;
574
+ this.shouldViewTransition = viewTransition;
575
+ this.history[next.replace ? "replace" : "push"](
576
+ nextHistory.href,
577
+ nextHistory.state,
578
+ { ignoreBlocker }
579
+ );
580
+ }
581
+ this.resetNextScroll = next.resetScroll ?? true;
582
+ if (!this.history.subscribers.size) {
583
+ this.load();
584
+ }
585
+ return this.commitLocationPromise;
586
+ };
587
+ this.buildAndCommitLocation = ({
588
+ replace,
589
+ resetScroll,
590
+ hashScrollIntoView,
591
+ viewTransition,
592
+ ignoreBlocker,
593
+ href,
594
+ ...rest
595
+ } = {}) => {
596
+ if (href) {
597
+ const currentIndex = this.history.location.state.__TSR_index;
598
+ const parsed = parseHref(href, {
599
+ __TSR_index: replace ? currentIndex : currentIndex + 1
600
+ });
601
+ rest.to = parsed.pathname;
602
+ rest.search = this.options.parseSearch(parsed.search);
603
+ rest.hash = parsed.hash.slice(1);
604
+ }
605
+ const location = this.buildLocation({
606
+ ...rest,
607
+ _includeValidateSearch: true
608
+ });
609
+ return this.commitLocation({
610
+ ...location,
611
+ viewTransition,
612
+ replace,
613
+ resetScroll,
614
+ hashScrollIntoView,
615
+ ignoreBlocker
616
+ });
617
+ };
618
+ this.navigate = ({ to, reloadDocument, href, ...rest }) => {
619
+ if (reloadDocument) {
620
+ if (!href) {
621
+ const location = this.buildLocation({ to, ...rest });
622
+ href = this.history.createHref(location.href);
623
+ }
624
+ if (rest.replace) {
625
+ window.location.replace(href);
626
+ } else {
627
+ window.location.href = href;
628
+ }
629
+ return;
630
+ }
631
+ return this.buildAndCommitLocation({
632
+ ...rest,
633
+ href,
634
+ to
635
+ });
636
+ };
637
+ this.load = async (opts) => {
638
+ this.latestLocation = this.parseLocation(this.latestLocation);
639
+ let redirect;
640
+ let notFound;
641
+ let loadPromise;
642
+ loadPromise = new Promise((resolve) => {
643
+ this.startTransition(async () => {
644
+ var _a;
645
+ try {
646
+ const next = this.latestLocation;
647
+ const prevLocation = this.state.resolvedLocation;
648
+ this.cancelMatches();
649
+ let pendingMatches;
650
+ batch(() => {
651
+ pendingMatches = this.matchRoutes(next);
652
+ this.__store.setState((s) => ({
653
+ ...s,
654
+ status: "pending",
655
+ isLoading: true,
656
+ location: next,
657
+ pendingMatches,
658
+ // If a cached moved to pendingMatches, remove it from cachedMatches
659
+ cachedMatches: s.cachedMatches.filter((d) => {
660
+ return !pendingMatches.find((e) => e.id === d.id);
661
+ })
662
+ }));
663
+ });
664
+ if (!this.state.redirect) {
665
+ this.emit({
666
+ type: "onBeforeNavigate",
667
+ ...getLocationChangeInfo({
668
+ resolvedLocation: prevLocation,
669
+ location: next
670
+ })
671
+ });
672
+ }
673
+ this.emit({
674
+ type: "onBeforeLoad",
675
+ ...getLocationChangeInfo({
676
+ resolvedLocation: prevLocation,
677
+ location: next
678
+ })
679
+ });
680
+ await this.loadMatches({
681
+ sync: opts == null ? void 0 : opts.sync,
682
+ matches: pendingMatches,
683
+ location: next,
684
+ // eslint-disable-next-line @typescript-eslint/require-await
685
+ onReady: async () => {
686
+ this.startViewTransition(async () => {
687
+ let exitingMatches;
688
+ let enteringMatches;
689
+ let stayingMatches;
690
+ batch(() => {
691
+ this.__store.setState((s) => {
692
+ const previousMatches = s.matches;
693
+ const newMatches = s.pendingMatches || s.matches;
694
+ exitingMatches = previousMatches.filter(
695
+ (match) => !newMatches.find((d) => d.id === match.id)
696
+ );
697
+ enteringMatches = newMatches.filter(
698
+ (match) => !previousMatches.find((d) => d.id === match.id)
699
+ );
700
+ stayingMatches = previousMatches.filter(
701
+ (match) => newMatches.find((d) => d.id === match.id)
702
+ );
703
+ return {
704
+ ...s,
705
+ isLoading: false,
706
+ loadedAt: Date.now(),
707
+ matches: newMatches,
708
+ pendingMatches: void 0,
709
+ cachedMatches: [
710
+ ...s.cachedMatches,
711
+ ...exitingMatches.filter((d) => d.status !== "error")
712
+ ]
713
+ };
714
+ });
715
+ this.clearExpiredCache();
716
+ });
717
+ [
718
+ [exitingMatches, "onLeave"],
719
+ [enteringMatches, "onEnter"],
720
+ [stayingMatches, "onStay"]
721
+ ].forEach(([matches, hook]) => {
722
+ matches.forEach((match) => {
723
+ var _a2, _b;
724
+ (_b = (_a2 = this.looseRoutesById[match.routeId].options)[hook]) == null ? void 0 : _b.call(_a2, match);
725
+ });
726
+ });
727
+ });
728
+ }
729
+ });
730
+ } catch (err) {
731
+ if (isResolvedRedirect(err)) {
732
+ redirect = err;
733
+ if (!this.isServer) {
734
+ this.navigate({
735
+ ...redirect,
736
+ replace: true,
737
+ ignoreBlocker: true
738
+ });
739
+ }
740
+ } else if (isNotFound(err)) {
741
+ notFound = err;
742
+ }
743
+ this.__store.setState((s) => ({
744
+ ...s,
745
+ statusCode: redirect ? redirect.statusCode : notFound ? 404 : s.matches.some((d) => d.status === "error") ? 500 : 200,
746
+ redirect
747
+ }));
748
+ }
749
+ if (this.latestLoadPromise === loadPromise) {
750
+ (_a = this.commitLocationPromise) == null ? void 0 : _a.resolve();
751
+ this.latestLoadPromise = void 0;
752
+ this.commitLocationPromise = void 0;
753
+ }
754
+ resolve();
755
+ });
756
+ });
757
+ this.latestLoadPromise = loadPromise;
758
+ await loadPromise;
759
+ while (this.latestLoadPromise && loadPromise !== this.latestLoadPromise) {
760
+ await this.latestLoadPromise;
761
+ }
762
+ if (this.hasNotFoundMatch()) {
763
+ this.__store.setState((s) => ({
764
+ ...s,
765
+ statusCode: 404
766
+ }));
767
+ }
768
+ };
769
+ this.startViewTransition = (fn) => {
770
+ const shouldViewTransition = this.shouldViewTransition ?? this.options.defaultViewTransition;
771
+ delete this.shouldViewTransition;
772
+ if (shouldViewTransition && typeof document !== "undefined" && "startViewTransition" in document && typeof document.startViewTransition === "function") {
773
+ let startViewTransitionParams;
774
+ if (typeof shouldViewTransition === "object" && this.isViewTransitionTypesSupported) {
775
+ startViewTransitionParams = {
776
+ update: fn,
777
+ types: shouldViewTransition.types
778
+ };
779
+ } else {
780
+ startViewTransitionParams = fn;
781
+ }
782
+ document.startViewTransition(startViewTransitionParams);
783
+ } else {
784
+ fn();
785
+ }
786
+ };
787
+ this.updateMatch = (id, updater) => {
788
+ var _a;
789
+ let updated;
790
+ const isPending = (_a = this.state.pendingMatches) == null ? void 0 : _a.find((d) => d.id === id);
791
+ const isMatched = this.state.matches.find((d) => d.id === id);
792
+ const isCached = this.state.cachedMatches.find((d) => d.id === id);
793
+ const matchesKey = isPending ? "pendingMatches" : isMatched ? "matches" : isCached ? "cachedMatches" : "";
794
+ if (matchesKey) {
795
+ this.__store.setState((s) => {
796
+ var _a2;
797
+ return {
798
+ ...s,
799
+ [matchesKey]: (_a2 = s[matchesKey]) == null ? void 0 : _a2.map(
800
+ (d) => d.id === id ? updated = updater(d) : d
801
+ )
802
+ };
803
+ });
804
+ }
805
+ return updated;
806
+ };
807
+ this.getMatch = (matchId) => {
808
+ return [
809
+ ...this.state.cachedMatches,
810
+ ...this.state.pendingMatches ?? [],
811
+ ...this.state.matches
812
+ ].find((d) => d.id === matchId);
813
+ };
814
+ this.loadMatches = async ({
815
+ location,
816
+ matches,
817
+ preload: allPreload,
818
+ onReady,
819
+ updateMatch = this.updateMatch,
820
+ sync
821
+ }) => {
822
+ let firstBadMatchIndex;
823
+ let rendered = false;
824
+ const triggerOnReady = async () => {
825
+ if (!rendered) {
826
+ rendered = true;
827
+ await (onReady == null ? void 0 : onReady());
828
+ }
829
+ };
830
+ const resolvePreload = (matchId) => {
831
+ return !!(allPreload && !this.state.matches.find((d) => d.id === matchId));
832
+ };
833
+ if (!this.isServer && !this.state.matches.length) {
834
+ triggerOnReady();
835
+ }
836
+ const handleRedirectAndNotFound = (match, err) => {
837
+ var _a, _b, _c, _d;
838
+ if (isResolvedRedirect(err)) {
839
+ if (!err.reloadDocument) {
840
+ throw err;
841
+ }
842
+ }
843
+ if (isRedirect(err) || isNotFound(err)) {
844
+ updateMatch(match.id, (prev) => ({
845
+ ...prev,
846
+ status: isRedirect(err) ? "redirected" : isNotFound(err) ? "notFound" : "error",
847
+ isFetching: false,
848
+ error: err,
849
+ beforeLoadPromise: void 0,
850
+ loaderPromise: void 0
851
+ }));
852
+ if (!err.routeId) {
853
+ err.routeId = match.routeId;
854
+ }
855
+ (_a = match.beforeLoadPromise) == null ? void 0 : _a.resolve();
856
+ (_b = match.loaderPromise) == null ? void 0 : _b.resolve();
857
+ (_c = match.loadPromise) == null ? void 0 : _c.resolve();
858
+ if (isRedirect(err)) {
859
+ rendered = true;
860
+ err = this.resolveRedirect({ ...err, _fromLocation: location });
861
+ throw err;
862
+ } else if (isNotFound(err)) {
863
+ this._handleNotFound(matches, err, {
864
+ updateMatch
865
+ });
866
+ (_d = this.serverSsr) == null ? void 0 : _d.onMatchSettled({
867
+ router: this,
868
+ match: this.getMatch(match.id)
869
+ });
870
+ throw err;
871
+ }
872
+ }
873
+ };
874
+ try {
875
+ await new Promise((resolveAll, rejectAll) => {
876
+ ;
877
+ (async () => {
878
+ var _a, _b, _c, _d;
879
+ try {
880
+ const handleSerialError = (index, err, routerCode) => {
881
+ var _a2, _b2;
882
+ const { id: matchId, routeId } = matches[index];
883
+ const route = this.looseRoutesById[routeId];
884
+ if (err instanceof Promise) {
885
+ throw err;
886
+ }
887
+ err.routerCode = routerCode;
888
+ firstBadMatchIndex = firstBadMatchIndex ?? index;
889
+ handleRedirectAndNotFound(this.getMatch(matchId), err);
890
+ try {
891
+ (_b2 = (_a2 = route.options).onError) == null ? void 0 : _b2.call(_a2, err);
892
+ } catch (errorHandlerErr) {
893
+ err = errorHandlerErr;
894
+ handleRedirectAndNotFound(this.getMatch(matchId), err);
895
+ }
896
+ updateMatch(matchId, (prev) => {
897
+ var _a3, _b3;
898
+ (_a3 = prev.beforeLoadPromise) == null ? void 0 : _a3.resolve();
899
+ (_b3 = prev.loadPromise) == null ? void 0 : _b3.resolve();
900
+ return {
901
+ ...prev,
902
+ error: err,
903
+ status: "error",
904
+ isFetching: false,
905
+ updatedAt: Date.now(),
906
+ abortController: new AbortController(),
907
+ beforeLoadPromise: void 0
908
+ };
909
+ });
910
+ };
911
+ for (const [index, { id: matchId, routeId }] of matches.entries()) {
912
+ const existingMatch = this.getMatch(matchId);
913
+ const parentMatchId = (_a = matches[index - 1]) == null ? void 0 : _a.id;
914
+ const route = this.looseRoutesById[routeId];
915
+ const pendingMs = route.options.pendingMs ?? this.options.defaultPendingMs;
916
+ const shouldPending = !!(onReady && !this.isServer && !resolvePreload(matchId) && (route.options.loader || route.options.beforeLoad) && typeof pendingMs === "number" && pendingMs !== Infinity && (route.options.pendingComponent ?? ((_b = this.options) == null ? void 0 : _b.defaultPendingComponent)));
917
+ let executeBeforeLoad = true;
918
+ if (
919
+ // If we are in the middle of a load, either of these will be present
920
+ // (not to be confused with `loadPromise`, which is always defined)
921
+ existingMatch.beforeLoadPromise || existingMatch.loaderPromise
922
+ ) {
923
+ if (shouldPending) {
924
+ setTimeout(() => {
925
+ try {
926
+ triggerOnReady();
927
+ } catch {
928
+ }
929
+ }, pendingMs);
930
+ }
931
+ await existingMatch.beforeLoadPromise;
932
+ executeBeforeLoad = this.getMatch(matchId).status !== "success";
933
+ }
934
+ if (executeBeforeLoad) {
935
+ try {
936
+ updateMatch(matchId, (prev) => {
937
+ const prevLoadPromise = prev.loadPromise;
938
+ return {
939
+ ...prev,
940
+ loadPromise: createControlledPromise(() => {
941
+ prevLoadPromise == null ? void 0 : prevLoadPromise.resolve();
942
+ }),
943
+ beforeLoadPromise: createControlledPromise()
944
+ };
945
+ });
946
+ const abortController = new AbortController();
947
+ let pendingTimeout;
948
+ if (shouldPending) {
949
+ pendingTimeout = setTimeout(() => {
950
+ try {
951
+ triggerOnReady();
952
+ } catch {
953
+ }
954
+ }, pendingMs);
955
+ }
956
+ const { paramsError, searchError } = this.getMatch(matchId);
957
+ if (paramsError) {
958
+ handleSerialError(index, paramsError, "PARSE_PARAMS");
959
+ }
960
+ if (searchError) {
961
+ handleSerialError(index, searchError, "VALIDATE_SEARCH");
962
+ }
963
+ const getParentMatchContext = () => parentMatchId ? this.getMatch(parentMatchId).context : this.options.context ?? {};
964
+ updateMatch(matchId, (prev) => ({
965
+ ...prev,
966
+ isFetching: "beforeLoad",
967
+ fetchCount: prev.fetchCount + 1,
968
+ abortController,
969
+ pendingTimeout,
970
+ context: {
971
+ ...getParentMatchContext(),
972
+ ...prev.__routeContext
973
+ }
974
+ }));
975
+ const { search, params, context, cause } = this.getMatch(matchId);
976
+ const preload = resolvePreload(matchId);
977
+ const beforeLoadFnContext = {
978
+ search,
979
+ abortController,
980
+ params,
981
+ preload,
982
+ context,
983
+ location,
984
+ navigate: (opts) => this.navigate({ ...opts, _fromLocation: location }),
985
+ buildLocation: this.buildLocation,
986
+ cause: preload ? "preload" : cause,
987
+ matches
988
+ };
989
+ const beforeLoadContext = await ((_d = (_c = route.options).beforeLoad) == null ? void 0 : _d.call(_c, beforeLoadFnContext)) ?? {};
990
+ if (isRedirect(beforeLoadContext) || isNotFound(beforeLoadContext)) {
991
+ handleSerialError(index, beforeLoadContext, "BEFORE_LOAD");
992
+ }
993
+ updateMatch(matchId, (prev) => {
994
+ return {
995
+ ...prev,
996
+ __beforeLoadContext: beforeLoadContext,
997
+ context: {
998
+ ...getParentMatchContext(),
999
+ ...prev.__routeContext,
1000
+ ...beforeLoadContext
1001
+ },
1002
+ abortController
1003
+ };
1004
+ });
1005
+ } catch (err) {
1006
+ handleSerialError(index, err, "BEFORE_LOAD");
1007
+ }
1008
+ updateMatch(matchId, (prev) => {
1009
+ var _a2;
1010
+ (_a2 = prev.beforeLoadPromise) == null ? void 0 : _a2.resolve();
1011
+ return {
1012
+ ...prev,
1013
+ beforeLoadPromise: void 0,
1014
+ isFetching: false
1015
+ };
1016
+ });
1017
+ }
1018
+ }
1019
+ const validResolvedMatches = matches.slice(0, firstBadMatchIndex);
1020
+ const matchPromises = [];
1021
+ validResolvedMatches.forEach(({ id: matchId, routeId }, index) => {
1022
+ matchPromises.push(
1023
+ (async () => {
1024
+ const { loaderPromise: prevLoaderPromise } = this.getMatch(matchId);
1025
+ let loaderShouldRunAsync = false;
1026
+ let loaderIsRunningAsync = false;
1027
+ if (prevLoaderPromise) {
1028
+ await prevLoaderPromise;
1029
+ const match = this.getMatch(matchId);
1030
+ if (match.error) {
1031
+ handleRedirectAndNotFound(match, match.error);
1032
+ }
1033
+ } else {
1034
+ const parentMatchPromise = matchPromises[index - 1];
1035
+ const route = this.looseRoutesById[routeId];
1036
+ const getLoaderContext = () => {
1037
+ const {
1038
+ params,
1039
+ loaderDeps,
1040
+ abortController,
1041
+ context,
1042
+ cause
1043
+ } = this.getMatch(matchId);
1044
+ const preload2 = resolvePreload(matchId);
1045
+ return {
1046
+ params,
1047
+ deps: loaderDeps,
1048
+ preload: !!preload2,
1049
+ parentMatchPromise,
1050
+ abortController,
1051
+ context,
1052
+ location,
1053
+ navigate: (opts) => this.navigate({ ...opts, _fromLocation: location }),
1054
+ cause: preload2 ? "preload" : cause,
1055
+ route
1056
+ };
1057
+ };
1058
+ const age = Date.now() - this.getMatch(matchId).updatedAt;
1059
+ const preload = resolvePreload(matchId);
1060
+ const staleAge = preload ? route.options.preloadStaleTime ?? this.options.defaultPreloadStaleTime ?? 3e4 : route.options.staleTime ?? this.options.defaultStaleTime ?? 0;
1061
+ const shouldReloadOption = route.options.shouldReload;
1062
+ const shouldReload = typeof shouldReloadOption === "function" ? shouldReloadOption(getLoaderContext()) : shouldReloadOption;
1063
+ updateMatch(matchId, (prev) => ({
1064
+ ...prev,
1065
+ loaderPromise: createControlledPromise(),
1066
+ preload: !!preload && !this.state.matches.find((d) => d.id === matchId)
1067
+ }));
1068
+ const runLoader = async () => {
1069
+ var _a2, _b2, _c2, _d2, _e, _f, _g, _h, _i, _j, _k;
1070
+ try {
1071
+ const potentialPendingMinPromise = async () => {
1072
+ const latestMatch = this.getMatch(matchId);
1073
+ if (latestMatch.minPendingPromise) {
1074
+ await latestMatch.minPendingPromise;
1075
+ }
1076
+ };
1077
+ try {
1078
+ this.loadRouteChunk(route);
1079
+ updateMatch(matchId, (prev) => ({
1080
+ ...prev,
1081
+ isFetching: "loader"
1082
+ }));
1083
+ const loaderData = await ((_b2 = (_a2 = route.options).loader) == null ? void 0 : _b2.call(_a2, getLoaderContext()));
1084
+ handleRedirectAndNotFound(
1085
+ this.getMatch(matchId),
1086
+ loaderData
1087
+ );
1088
+ await route._lazyPromise;
1089
+ await potentialPendingMinPromise();
1090
+ const assetContext = {
1091
+ matches,
1092
+ match: this.getMatch(matchId),
1093
+ params: this.getMatch(matchId).params,
1094
+ loaderData
1095
+ };
1096
+ const headFnContent = (_d2 = (_c2 = route.options).head) == null ? void 0 : _d2.call(_c2, assetContext);
1097
+ const meta = headFnContent == null ? void 0 : headFnContent.meta;
1098
+ const links = headFnContent == null ? void 0 : headFnContent.links;
1099
+ const headScripts = headFnContent == null ? void 0 : headFnContent.scripts;
1100
+ const scripts = (_f = (_e = route.options).scripts) == null ? void 0 : _f.call(_e, assetContext);
1101
+ const headers = (_h = (_g = route.options).headers) == null ? void 0 : _h.call(_g, {
1102
+ loaderData
1103
+ });
1104
+ updateMatch(matchId, (prev) => ({
1105
+ ...prev,
1106
+ error: void 0,
1107
+ status: "success",
1108
+ isFetching: false,
1109
+ updatedAt: Date.now(),
1110
+ loaderData,
1111
+ meta,
1112
+ links,
1113
+ headScripts,
1114
+ headers,
1115
+ scripts
1116
+ }));
1117
+ } catch (e) {
1118
+ let error = e;
1119
+ await potentialPendingMinPromise();
1120
+ handleRedirectAndNotFound(this.getMatch(matchId), e);
1121
+ try {
1122
+ (_j = (_i = route.options).onError) == null ? void 0 : _j.call(_i, e);
1123
+ } catch (onErrorError) {
1124
+ error = onErrorError;
1125
+ handleRedirectAndNotFound(
1126
+ this.getMatch(matchId),
1127
+ onErrorError
1128
+ );
1129
+ }
1130
+ updateMatch(matchId, (prev) => ({
1131
+ ...prev,
1132
+ error,
1133
+ status: "error",
1134
+ isFetching: false
1135
+ }));
1136
+ }
1137
+ (_k = this.serverSsr) == null ? void 0 : _k.onMatchSettled({
1138
+ router: this,
1139
+ match: this.getMatch(matchId)
1140
+ });
1141
+ await route._componentsPromise;
1142
+ } catch (err) {
1143
+ updateMatch(matchId, (prev) => ({
1144
+ ...prev,
1145
+ loaderPromise: void 0
1146
+ }));
1147
+ handleRedirectAndNotFound(this.getMatch(matchId), err);
1148
+ }
1149
+ };
1150
+ const { status, invalid } = this.getMatch(matchId);
1151
+ loaderShouldRunAsync = status === "success" && (invalid || (shouldReload ?? age > staleAge));
1152
+ if (preload && route.options.preload === false) {
1153
+ } else if (loaderShouldRunAsync && !sync) {
1154
+ loaderIsRunningAsync = true;
1155
+ (async () => {
1156
+ try {
1157
+ await runLoader();
1158
+ const { loaderPromise, loadPromise } = this.getMatch(matchId);
1159
+ loaderPromise == null ? void 0 : loaderPromise.resolve();
1160
+ loadPromise == null ? void 0 : loadPromise.resolve();
1161
+ updateMatch(matchId, (prev) => ({
1162
+ ...prev,
1163
+ loaderPromise: void 0
1164
+ }));
1165
+ } catch (err) {
1166
+ if (isResolvedRedirect(err)) {
1167
+ await this.navigate(err);
1168
+ }
1169
+ }
1170
+ })();
1171
+ } else if (status !== "success" || loaderShouldRunAsync && sync) {
1172
+ await runLoader();
1173
+ }
1174
+ }
1175
+ if (!loaderIsRunningAsync) {
1176
+ const { loaderPromise, loadPromise } = this.getMatch(matchId);
1177
+ loaderPromise == null ? void 0 : loaderPromise.resolve();
1178
+ loadPromise == null ? void 0 : loadPromise.resolve();
1179
+ }
1180
+ updateMatch(matchId, (prev) => ({
1181
+ ...prev,
1182
+ isFetching: loaderIsRunningAsync ? prev.isFetching : false,
1183
+ loaderPromise: loaderIsRunningAsync ? prev.loaderPromise : void 0,
1184
+ invalid: false
1185
+ }));
1186
+ return this.getMatch(matchId);
1187
+ })()
1188
+ );
1189
+ });
1190
+ await Promise.all(matchPromises);
1191
+ resolveAll();
1192
+ } catch (err) {
1193
+ rejectAll(err);
1194
+ }
1195
+ })();
1196
+ });
1197
+ await triggerOnReady();
1198
+ } catch (err) {
1199
+ if (isRedirect(err) || isNotFound(err)) {
1200
+ if (isNotFound(err) && !allPreload) {
1201
+ await triggerOnReady();
1202
+ }
1203
+ throw err;
1204
+ }
1205
+ }
1206
+ return matches;
1207
+ };
1208
+ this.invalidate = (opts) => {
1209
+ const invalidate = (d) => {
1210
+ var _a;
1211
+ if (((_a = opts == null ? void 0 : opts.filter) == null ? void 0 : _a.call(opts, d)) ?? true) {
1212
+ return {
1213
+ ...d,
1214
+ invalid: true,
1215
+ ...d.status === "error" ? { status: "pending", error: void 0 } : {}
1216
+ };
1217
+ }
1218
+ return d;
1219
+ };
1220
+ this.__store.setState((s) => {
1221
+ var _a;
1222
+ return {
1223
+ ...s,
1224
+ matches: s.matches.map(invalidate),
1225
+ cachedMatches: s.cachedMatches.map(invalidate),
1226
+ pendingMatches: (_a = s.pendingMatches) == null ? void 0 : _a.map(invalidate)
1227
+ };
1228
+ });
1229
+ return this.load({ sync: opts == null ? void 0 : opts.sync });
1230
+ };
1231
+ this.resolveRedirect = (err) => {
1232
+ const redirect = err;
1233
+ if (!redirect.href) {
1234
+ redirect.href = this.buildLocation(redirect).href;
1235
+ }
1236
+ return redirect;
1237
+ };
1238
+ this.clearCache = (opts) => {
1239
+ const filter = opts == null ? void 0 : opts.filter;
1240
+ if (filter !== void 0) {
1241
+ this.__store.setState((s) => {
1242
+ return {
1243
+ ...s,
1244
+ cachedMatches: s.cachedMatches.filter(
1245
+ (m) => !filter(m)
1246
+ )
1247
+ };
1248
+ });
1249
+ } else {
1250
+ this.__store.setState((s) => {
1251
+ return {
1252
+ ...s,
1253
+ cachedMatches: []
1254
+ };
1255
+ });
1256
+ }
1257
+ };
1258
+ this.clearExpiredCache = () => {
1259
+ const filter = (d) => {
1260
+ const route = this.looseRoutesById[d.routeId];
1261
+ if (!route.options.loader) {
1262
+ return true;
1263
+ }
1264
+ const gcTime = (d.preload ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime : route.options.gcTime ?? this.options.defaultGcTime) ?? 5 * 60 * 1e3;
1265
+ return !(d.status !== "error" && Date.now() - d.updatedAt < gcTime);
1266
+ };
1267
+ this.clearCache({ filter });
1268
+ };
1269
+ this.loadRouteChunk = (route) => {
1270
+ if (route._lazyPromise === void 0) {
1271
+ if (route.lazyFn) {
1272
+ route._lazyPromise = route.lazyFn().then((lazyRoute) => {
1273
+ const { id: _id, ...options2 } = lazyRoute.options;
1274
+ Object.assign(route.options, options2);
1275
+ });
1276
+ } else {
1277
+ route._lazyPromise = Promise.resolve();
1278
+ }
1279
+ }
1280
+ if (route._componentsPromise === void 0) {
1281
+ route._componentsPromise = route._lazyPromise.then(
1282
+ () => Promise.all(
1283
+ componentTypes.map(async (type) => {
1284
+ const component = route.options[type];
1285
+ if (component == null ? void 0 : component.preload) {
1286
+ await component.preload();
1287
+ }
1288
+ })
1289
+ )
1290
+ );
1291
+ }
1292
+ return route._componentsPromise;
1293
+ };
1294
+ this.preloadRoute = async (opts) => {
1295
+ const next = this.buildLocation(opts);
1296
+ let matches = this.matchRoutes(next, {
1297
+ throwOnError: true,
1298
+ preload: true,
1299
+ dest: opts
1300
+ });
1301
+ const activeMatchIds = new Set(
1302
+ [...this.state.matches, ...this.state.pendingMatches ?? []].map(
1303
+ (d) => d.id
1304
+ )
1305
+ );
1306
+ const loadedMatchIds = /* @__PURE__ */ new Set([
1307
+ ...activeMatchIds,
1308
+ ...this.state.cachedMatches.map((d) => d.id)
1309
+ ]);
1310
+ batch(() => {
1311
+ matches.forEach((match) => {
1312
+ if (!loadedMatchIds.has(match.id)) {
1313
+ this.__store.setState((s) => ({
1314
+ ...s,
1315
+ cachedMatches: [...s.cachedMatches, match]
1316
+ }));
1317
+ }
1318
+ });
1319
+ });
1320
+ try {
1321
+ matches = await this.loadMatches({
1322
+ matches,
1323
+ location: next,
1324
+ preload: true,
1325
+ updateMatch: (id, updater) => {
1326
+ if (activeMatchIds.has(id)) {
1327
+ matches = matches.map((d) => d.id === id ? updater(d) : d);
1328
+ } else {
1329
+ this.updateMatch(id, updater);
1330
+ }
1331
+ }
1332
+ });
1333
+ return matches;
1334
+ } catch (err) {
1335
+ if (isRedirect(err)) {
1336
+ if (err.reloadDocument) {
1337
+ return void 0;
1338
+ }
1339
+ return await this.preloadRoute({
1340
+ ...err,
1341
+ _fromLocation: next
1342
+ });
1343
+ }
1344
+ if (!isNotFound(err)) {
1345
+ console.error(err);
1346
+ }
1347
+ return void 0;
1348
+ }
1349
+ };
1350
+ this.matchRoute = (location, opts) => {
1351
+ const matchLocation = {
1352
+ ...location,
1353
+ to: location.to ? this.resolvePathWithBase(
1354
+ location.from || "",
1355
+ location.to
1356
+ ) : void 0,
1357
+ params: location.params || {},
1358
+ leaveParams: true
1359
+ };
1360
+ const next = this.buildLocation(matchLocation);
1361
+ if ((opts == null ? void 0 : opts.pending) && this.state.status !== "pending") {
1362
+ return false;
1363
+ }
1364
+ const pending = (opts == null ? void 0 : opts.pending) === void 0 ? !this.state.isLoading : opts.pending;
1365
+ const baseLocation = pending ? this.latestLocation : this.state.resolvedLocation || this.state.location;
1366
+ const match = matchPathname(this.basepath, baseLocation.pathname, {
1367
+ ...opts,
1368
+ to: next.pathname
1369
+ });
1370
+ if (!match) {
1371
+ return false;
1372
+ }
1373
+ if (location.params) {
1374
+ if (!deepEqual(match, location.params, { partial: true })) {
1375
+ return false;
1376
+ }
1377
+ }
1378
+ if (match && ((opts == null ? void 0 : opts.includeSearch) ?? true)) {
1379
+ return deepEqual(baseLocation.search, next.search, { partial: true }) ? match : false;
1380
+ }
1381
+ return match;
1382
+ };
1383
+ this._handleNotFound = (matches, err, {
1384
+ updateMatch = this.updateMatch
1385
+ } = {}) => {
1386
+ var _a;
1387
+ const routeCursor = this.routesById[err.routeId ?? ""] ?? this.routeTree;
1388
+ const matchesByRouteId = {};
1389
+ for (const match of matches) {
1390
+ matchesByRouteId[match.routeId] = match;
1391
+ }
1392
+ if (!routeCursor.options.notFoundComponent && ((_a = this.options) == null ? void 0 : _a.defaultNotFoundComponent)) {
1393
+ routeCursor.options.notFoundComponent = this.options.defaultNotFoundComponent;
1394
+ }
1395
+ invariant(
1396
+ routeCursor.options.notFoundComponent,
1397
+ "No notFoundComponent found. Please set a notFoundComponent on your route or provide a defaultNotFoundComponent to the router."
1398
+ );
1399
+ const matchForRoute = matchesByRouteId[routeCursor.id];
1400
+ invariant(
1401
+ matchForRoute,
1402
+ "Could not find match for route: " + routeCursor.id
1403
+ );
1404
+ updateMatch(matchForRoute.id, (prev) => ({
1405
+ ...prev,
1406
+ status: "notFound",
1407
+ error: err,
1408
+ isFetching: false
1409
+ }));
1410
+ if (err.routerCode === "BEFORE_LOAD" && routeCursor.parentRoute) {
1411
+ err.routeId = routeCursor.parentRoute.id;
1412
+ this._handleNotFound(matches, err, {
1413
+ updateMatch
1414
+ });
1415
+ }
1416
+ };
1417
+ this.hasNotFoundMatch = () => {
1418
+ return this.__store.state.matches.some(
1419
+ (d) => d.status === "notFound" || d.globalNotFound
1420
+ );
1421
+ };
1422
+ this.update({
1423
+ defaultPreloadDelay: 50,
1424
+ defaultPendingMs: 1e3,
1425
+ defaultPendingMinMs: 500,
1426
+ context: void 0,
1427
+ ...options,
1428
+ caseSensitive: options.caseSensitive ?? false,
1429
+ notFoundMode: options.notFoundMode ?? "fuzzy",
1430
+ stringifySearch: options.stringifySearch ?? defaultStringifySearch,
1431
+ parseSearch: options.parseSearch ?? defaultParseSearch
1432
+ });
1433
+ if (typeof document !== "undefined") {
1434
+ window.__TSR_ROUTER__ = this;
1435
+ }
1436
+ }
1437
+ get state() {
1438
+ return this.__store.state;
1439
+ }
1440
+ get looseRoutesById() {
1441
+ return this.routesById;
1442
+ }
1443
+ matchRoutesInternal(next, opts) {
1444
+ const { foundRoute, matchedRoutes, routeParams } = this.getMatchedRoutes(
1445
+ next,
1446
+ opts == null ? void 0 : opts.dest
1447
+ );
1448
+ let isGlobalNotFound = false;
1449
+ if (
1450
+ // If we found a route, and it's not an index route and we have left over path
1451
+ foundRoute ? foundRoute.path !== "/" && routeParams["**"] : (
1452
+ // Or if we didn't find a route and we have left over path
1453
+ trimPathRight(next.pathname)
1454
+ )
1455
+ ) {
1456
+ if (this.options.notFoundRoute) {
1457
+ matchedRoutes.push(this.options.notFoundRoute);
1458
+ } else {
1459
+ isGlobalNotFound = true;
1460
+ }
1461
+ }
1462
+ const globalNotFoundRouteId = (() => {
1463
+ if (!isGlobalNotFound) {
1464
+ return void 0;
1465
+ }
1466
+ if (this.options.notFoundMode !== "root") {
1467
+ for (let i = matchedRoutes.length - 1; i >= 0; i--) {
1468
+ const route = matchedRoutes[i];
1469
+ if (route.children) {
1470
+ return route.id;
1471
+ }
1472
+ }
1473
+ }
1474
+ return rootRouteId;
1475
+ })();
1476
+ const parseErrors = matchedRoutes.map((route) => {
1477
+ var _a;
1478
+ let parsedParamsError;
1479
+ const parseParams = ((_a = route.options.params) == null ? void 0 : _a.parse) ?? route.options.parseParams;
1480
+ if (parseParams) {
1481
+ try {
1482
+ const parsedParams = parseParams(routeParams);
1483
+ Object.assign(routeParams, parsedParams);
1484
+ } catch (err) {
1485
+ parsedParamsError = new PathParamError(err.message, {
1486
+ cause: err
1487
+ });
1488
+ if (opts == null ? void 0 : opts.throwOnError) {
1489
+ throw parsedParamsError;
1490
+ }
1491
+ return parsedParamsError;
1492
+ }
1493
+ }
1494
+ return;
1495
+ });
1496
+ const matches = [];
1497
+ const getParentContext = (parentMatch) => {
1498
+ const parentMatchId = parentMatch == null ? void 0 : parentMatch.id;
1499
+ const parentContext = !parentMatchId ? this.options.context ?? {} : parentMatch.context ?? this.options.context ?? {};
1500
+ return parentContext;
1501
+ };
1502
+ matchedRoutes.forEach((route, index) => {
1503
+ var _a, _b;
1504
+ const parentMatch = matches[index - 1];
1505
+ const [preMatchSearch, strictMatchSearch, searchError] = (() => {
1506
+ const parentSearch = (parentMatch == null ? void 0 : parentMatch.search) ?? next.search;
1507
+ const parentStrictSearch = (parentMatch == null ? void 0 : parentMatch._strictSearch) ?? {};
1508
+ try {
1509
+ const strictSearch = validateSearch(route.options.validateSearch, { ...parentSearch }) ?? {};
1510
+ return [
1511
+ {
1512
+ ...parentSearch,
1513
+ ...strictSearch
1514
+ },
1515
+ { ...parentStrictSearch, ...strictSearch },
1516
+ void 0
1517
+ ];
1518
+ } catch (err) {
1519
+ let searchParamError = err;
1520
+ if (!(err instanceof SearchParamError)) {
1521
+ searchParamError = new SearchParamError(err.message, {
1522
+ cause: err
1523
+ });
1524
+ }
1525
+ if (opts == null ? void 0 : opts.throwOnError) {
1526
+ throw searchParamError;
1527
+ }
1528
+ return [parentSearch, {}, searchParamError];
1529
+ }
1530
+ })();
1531
+ const loaderDeps = ((_b = (_a = route.options).loaderDeps) == null ? void 0 : _b.call(_a, {
1532
+ search: preMatchSearch
1533
+ })) ?? "";
1534
+ const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : "";
1535
+ const { usedParams, interpolatedPath } = interpolatePath({
1536
+ path: route.fullPath,
1537
+ params: routeParams,
1538
+ decodeCharMap: this.pathParamsDecodeCharMap
1539
+ });
1540
+ const matchId = interpolatePath({
1541
+ path: route.id,
1542
+ params: routeParams,
1543
+ leaveWildcards: true,
1544
+ decodeCharMap: this.pathParamsDecodeCharMap
1545
+ }).interpolatedPath + loaderDepsHash;
1546
+ const existingMatch = this.getMatch(matchId);
1547
+ const previousMatch = this.state.matches.find(
1548
+ (d) => d.routeId === route.id
1549
+ );
1550
+ const cause = previousMatch ? "stay" : "enter";
1551
+ let match;
1552
+ if (existingMatch) {
1553
+ match = {
1554
+ ...existingMatch,
1555
+ cause,
1556
+ params: previousMatch ? replaceEqualDeep(previousMatch.params, routeParams) : routeParams,
1557
+ _strictParams: usedParams,
1558
+ search: previousMatch ? replaceEqualDeep(previousMatch.search, preMatchSearch) : replaceEqualDeep(existingMatch.search, preMatchSearch),
1559
+ _strictSearch: strictMatchSearch
1560
+ };
1561
+ } else {
1562
+ const status = route.options.loader || route.options.beforeLoad || route.lazyFn || routeNeedsPreload(route) ? "pending" : "success";
1563
+ match = {
1564
+ id: matchId,
1565
+ index,
1566
+ routeId: route.id,
1567
+ params: previousMatch ? replaceEqualDeep(previousMatch.params, routeParams) : routeParams,
1568
+ _strictParams: usedParams,
1569
+ pathname: joinPaths([this.basepath, interpolatedPath]),
1570
+ updatedAt: Date.now(),
1571
+ search: previousMatch ? replaceEqualDeep(previousMatch.search, preMatchSearch) : preMatchSearch,
1572
+ _strictSearch: strictMatchSearch,
1573
+ searchError: void 0,
1574
+ status,
1575
+ isFetching: false,
1576
+ error: void 0,
1577
+ paramsError: parseErrors[index],
1578
+ __routeContext: {},
1579
+ __beforeLoadContext: {},
1580
+ context: {},
1581
+ abortController: new AbortController(),
1582
+ fetchCount: 0,
1583
+ cause,
1584
+ loaderDeps: previousMatch ? replaceEqualDeep(previousMatch.loaderDeps, loaderDeps) : loaderDeps,
1585
+ invalid: false,
1586
+ preload: false,
1587
+ links: void 0,
1588
+ scripts: void 0,
1589
+ headScripts: void 0,
1590
+ meta: void 0,
1591
+ staticData: route.options.staticData || {},
1592
+ loadPromise: createControlledPromise(),
1593
+ fullPath: route.fullPath
1594
+ };
1595
+ }
1596
+ if (!(opts == null ? void 0 : opts.preload)) {
1597
+ match.globalNotFound = globalNotFoundRouteId === route.id;
1598
+ }
1599
+ match.searchError = searchError;
1600
+ const parentContext = getParentContext(parentMatch);
1601
+ match.context = {
1602
+ ...parentContext,
1603
+ ...match.__routeContext,
1604
+ ...match.__beforeLoadContext
1605
+ };
1606
+ matches.push(match);
1607
+ });
1608
+ matches.forEach((match, index) => {
1609
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1610
+ const route = this.looseRoutesById[match.routeId];
1611
+ const existingMatch = this.getMatch(match.id);
1612
+ if (!existingMatch && (opts == null ? void 0 : opts._buildLocation) !== true) {
1613
+ const parentMatch = matches[index - 1];
1614
+ const parentContext = getParentContext(parentMatch);
1615
+ const contextFnContext = {
1616
+ deps: match.loaderDeps,
1617
+ params: match.params,
1618
+ context: parentContext,
1619
+ location: next,
1620
+ navigate: (opts2) => this.navigate({ ...opts2, _fromLocation: next }),
1621
+ buildLocation: this.buildLocation,
1622
+ cause: match.cause,
1623
+ abortController: match.abortController,
1624
+ preload: !!match.preload,
1625
+ matches
1626
+ };
1627
+ match.__routeContext = ((_b = (_a = route.options).context) == null ? void 0 : _b.call(_a, contextFnContext)) ?? {};
1628
+ match.context = {
1629
+ ...parentContext,
1630
+ ...match.__routeContext,
1631
+ ...match.__beforeLoadContext
1632
+ };
1633
+ }
1634
+ if (match.status === "success") {
1635
+ match.headers = (_d = (_c = route.options).headers) == null ? void 0 : _d.call(_c, {
1636
+ loaderData: match.loaderData
1637
+ });
1638
+ const assetContext = {
1639
+ matches,
1640
+ match,
1641
+ params: match.params,
1642
+ loaderData: match.loaderData
1643
+ };
1644
+ const headFnContent = (_f = (_e = route.options).head) == null ? void 0 : _f.call(_e, assetContext);
1645
+ match.links = headFnContent == null ? void 0 : headFnContent.links;
1646
+ match.headScripts = headFnContent == null ? void 0 : headFnContent.scripts;
1647
+ match.meta = headFnContent == null ? void 0 : headFnContent.meta;
1648
+ match.scripts = (_h = (_g = route.options).scripts) == null ? void 0 : _h.call(_g, assetContext);
1649
+ }
1650
+ });
1651
+ return matches;
1652
+ }
1653
+ }
1654
+ class SearchParamError extends Error {
1655
+ }
1656
+ class PathParamError extends Error {
1657
+ }
1658
+ function lazyFn(fn, key) {
1659
+ return async (...args) => {
1660
+ const imported = await fn();
1661
+ return imported[key || "default"](...args);
1662
+ };
1663
+ }
1664
+ function getInitialRouterState(location) {
1665
+ return {
1666
+ loadedAt: 0,
1667
+ isLoading: false,
1668
+ isTransitioning: false,
1669
+ status: "idle",
1670
+ resolvedLocation: void 0,
1671
+ location,
1672
+ matches: [],
1673
+ pendingMatches: [],
1674
+ cachedMatches: [],
1675
+ statusCode: 200
1676
+ };
1677
+ }
1678
+ function validateSearch(validateSearch2, input) {
1679
+ if (validateSearch2 == null) return {};
1680
+ if ("~standard" in validateSearch2) {
1681
+ const result = validateSearch2["~standard"].validate(input);
1682
+ if (result instanceof Promise)
1683
+ throw new SearchParamError("Async validation not supported");
1684
+ if (result.issues)
1685
+ throw new SearchParamError(JSON.stringify(result.issues, void 0, 2), {
1686
+ cause: result
1687
+ });
1688
+ return result.value;
1689
+ }
1690
+ if ("parse" in validateSearch2) {
1691
+ return validateSearch2.parse(input);
1692
+ }
1693
+ if (typeof validateSearch2 === "function") {
1694
+ return validateSearch2(input);
1695
+ }
1696
+ return {};
1697
+ }
1698
+ const componentTypes = [
1699
+ "component",
1700
+ "errorComponent",
1701
+ "pendingComponent",
1702
+ "notFoundComponent"
1703
+ ];
1704
+ function routeNeedsPreload(route) {
1705
+ var _a;
1706
+ for (const componentType of componentTypes) {
1707
+ if ((_a = route.options[componentType]) == null ? void 0 : _a.preload) {
1708
+ return true;
1709
+ }
1710
+ }
1711
+ return false;
1712
+ }
24
1713
  export {
1714
+ PathParamError,
1715
+ RouterCore,
1716
+ SearchParamError,
1717
+ componentTypes,
25
1718
  defaultSerializeError,
26
- getLocationChangeInfo
1719
+ getInitialRouterState,
1720
+ getLocationChangeInfo,
1721
+ lazyFn
27
1722
  };
28
1723
  //# sourceMappingURL=router.js.map