@tanstack/react-router 1.114.23 → 1.114.25

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