@tanstack/router-core 0.0.1-beta.8 → 1.20.3-alpha.1

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