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