@tanstack/router-core 1.121.19 → 1.121.21

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