@tanstack/react-router 1.7.1 → 1.8.0

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 (200) hide show
  1. package/dist/cjs/CatchBoundary.cjs +106 -0
  2. package/dist/cjs/CatchBoundary.cjs.map +1 -0
  3. package/dist/cjs/Matches.cjs +278 -0
  4. package/dist/cjs/Matches.cjs.map +1 -0
  5. package/{build/cjs/RouterProvider.js → dist/cjs/RouterProvider.cjs} +55 -58
  6. package/dist/cjs/RouterProvider.cjs.map +1 -0
  7. package/dist/cjs/awaited.cjs +51 -0
  8. package/dist/cjs/awaited.cjs.map +1 -0
  9. package/dist/cjs/defer.cjs +30 -0
  10. package/dist/cjs/defer.cjs.map +1 -0
  11. package/dist/cjs/fileRoute.cjs +19 -0
  12. package/dist/cjs/fileRoute.cjs.map +1 -0
  13. package/dist/cjs/history.d.cts +7 -0
  14. package/{build/cjs/index.js → dist/cjs/index.cjs} +39 -51
  15. package/dist/cjs/index.cjs.map +1 -0
  16. package/dist/cjs/lazyRouteComponent.cjs +40 -0
  17. package/dist/cjs/lazyRouteComponent.cjs.map +1 -0
  18. package/dist/cjs/link.cjs +196 -0
  19. package/dist/cjs/link.cjs.map +1 -0
  20. package/dist/cjs/link.d.cts +85 -0
  21. package/{build/cjs/path.js → dist/cjs/path.cjs} +77 -94
  22. package/dist/cjs/path.cjs.map +1 -0
  23. package/dist/cjs/qss.cjs +45 -0
  24. package/dist/cjs/qss.cjs.map +1 -0
  25. package/dist/cjs/redirects.cjs +15 -0
  26. package/dist/cjs/redirects.cjs.map +1 -0
  27. package/dist/cjs/route.cjs +143 -0
  28. package/dist/cjs/route.cjs.map +1 -0
  29. package/dist/cjs/router.cjs +1070 -0
  30. package/dist/cjs/router.cjs.map +1 -0
  31. package/dist/cjs/routerContext.cjs +29 -0
  32. package/dist/cjs/routerContext.cjs.map +1 -0
  33. package/{build/cjs/scroll-restoration.js → dist/cjs/scroll-restoration.cjs} +58 -75
  34. package/dist/cjs/scroll-restoration.cjs.map +1 -0
  35. package/{build/cjs/searchParams.js → dist/cjs/searchParams.cjs} +18 -36
  36. package/dist/cjs/searchParams.cjs.map +1 -0
  37. package/dist/cjs/useBlocker.cjs +36 -0
  38. package/dist/cjs/useBlocker.cjs.map +1 -0
  39. package/dist/cjs/useNavigate.cjs +55 -0
  40. package/dist/cjs/useNavigate.cjs.map +1 -0
  41. package/dist/cjs/useParams.cjs +16 -0
  42. package/dist/cjs/useParams.cjs.map +1 -0
  43. package/dist/cjs/useRouteContext.cjs +11 -0
  44. package/dist/cjs/useRouteContext.cjs.map +1 -0
  45. package/dist/cjs/useRouter.cjs +33 -0
  46. package/dist/cjs/useRouter.cjs.map +1 -0
  47. package/dist/cjs/useRouterState.cjs +12 -0
  48. package/dist/cjs/useRouterState.cjs.map +1 -0
  49. package/dist/cjs/useSearch.cjs +13 -0
  50. package/dist/cjs/useSearch.cjs.map +1 -0
  51. package/{build/cjs/utils.js → dist/cjs/utils.cjs} +25 -116
  52. package/dist/cjs/utils.cjs.map +1 -0
  53. package/dist/esm/CatchBoundary.d.ts +36 -0
  54. package/dist/esm/CatchBoundary.js +89 -0
  55. package/dist/esm/CatchBoundary.js.map +1 -0
  56. package/dist/esm/Matches.d.ts +71 -0
  57. package/dist/esm/Matches.js +261 -0
  58. package/{build/cjs → dist/esm}/Matches.js.map +1 -1
  59. package/dist/esm/RouterProvider.d.ts +27 -0
  60. package/dist/esm/RouterProvider.js +136 -0
  61. package/{build/cjs → dist/esm}/RouterProvider.js.map +1 -1
  62. package/dist/esm/awaited.d.ts +9 -0
  63. package/dist/esm/awaited.js +51 -0
  64. package/dist/esm/awaited.js.map +1 -0
  65. package/dist/esm/defer.d.ts +22 -0
  66. package/dist/esm/defer.js +30 -0
  67. package/{build/cjs → dist/esm}/defer.js.map +1 -1
  68. package/dist/esm/fileRoute.d.ts +21 -0
  69. package/dist/esm/fileRoute.js +19 -0
  70. package/dist/esm/fileRoute.js.map +1 -0
  71. package/{build/types → dist/esm}/history.d.ts +1 -1
  72. package/dist/esm/index.d.ts +30 -0
  73. package/dist/esm/index.js +118 -0
  74. package/dist/esm/index.js.map +1 -0
  75. package/dist/esm/lazyRouteComponent.d.ts +2 -0
  76. package/dist/esm/lazyRouteComponent.js +23 -0
  77. package/{build/cjs → dist/esm}/lazyRouteComponent.js.map +1 -1
  78. package/{build/types → dist/esm}/link.d.ts +3 -1
  79. package/dist/esm/link.js +179 -0
  80. package/dist/esm/link.js.map +1 -0
  81. package/dist/esm/location.d.ts +12 -0
  82. package/dist/esm/path.d.ts +17 -0
  83. package/dist/esm/path.js +200 -0
  84. package/dist/esm/path.js.map +1 -0
  85. package/dist/esm/qss.d.ts +2 -0
  86. package/dist/esm/qss.js +45 -0
  87. package/dist/esm/qss.js.map +1 -0
  88. package/dist/esm/redirects.d.ts +11 -0
  89. package/dist/esm/redirects.js +15 -0
  90. package/{build/cjs → dist/esm}/redirects.js.map +1 -1
  91. package/dist/esm/route.d.ts +300 -0
  92. package/dist/esm/route.js +143 -0
  93. package/dist/esm/route.js.map +1 -0
  94. package/dist/esm/routeInfo.d.ts +31 -0
  95. package/dist/esm/router.d.ts +201 -0
  96. package/dist/esm/router.js +1070 -0
  97. package/{build/cjs → dist/esm}/router.js.map +1 -1
  98. package/dist/esm/routerContext.d.ts +3 -0
  99. package/dist/esm/routerContext.js +13 -0
  100. package/{build/cjs → dist/esm}/routerContext.js.map +1 -1
  101. package/dist/esm/scroll-restoration.d.ts +18 -0
  102. package/dist/esm/scroll-restoration.js +168 -0
  103. package/dist/esm/scroll-restoration.js.map +1 -0
  104. package/dist/esm/searchParams.d.ts +7 -0
  105. package/dist/esm/searchParams.js +63 -0
  106. package/{build/cjs → dist/esm}/searchParams.js.map +1 -1
  107. package/dist/esm/useBlocker.d.ts +9 -0
  108. package/dist/esm/useBlocker.js +19 -0
  109. package/{build/cjs → dist/esm}/useBlocker.js.map +1 -1
  110. package/dist/esm/useNavigate.d.ts +20 -0
  111. package/dist/esm/useNavigate.js +38 -0
  112. package/{build/cjs → dist/esm}/useNavigate.js.map +1 -1
  113. package/dist/esm/useParams.d.ts +7 -0
  114. package/dist/esm/useParams.js +16 -0
  115. package/{build/cjs → dist/esm}/useParams.js.map +1 -1
  116. package/dist/esm/useRouteContext.d.ts +7 -0
  117. package/dist/esm/useRouteContext.js +11 -0
  118. package/{build/cjs → dist/esm}/useRouteContext.js.map +1 -1
  119. package/dist/esm/useRouter.d.ts +5 -0
  120. package/dist/esm/useRouter.js +16 -0
  121. package/{build/cjs → dist/esm}/useRouter.js.map +1 -1
  122. package/dist/esm/useRouterState.d.ts +6 -0
  123. package/dist/esm/useRouterState.js +12 -0
  124. package/{build/cjs → dist/esm}/useRouterState.js.map +1 -1
  125. package/dist/esm/useSearch.d.ts +7 -0
  126. package/dist/esm/useSearch.js +13 -0
  127. package/dist/esm/useSearch.js.map +1 -0
  128. package/dist/esm/utils.d.ts +46 -0
  129. package/dist/esm/utils.js +137 -0
  130. package/{build/cjs → dist/esm}/utils.js.map +1 -1
  131. package/package.json +43 -22
  132. package/src/fileRoute.ts +4 -5
  133. package/src/link.tsx +5 -4
  134. package/src/route.ts +5 -6
  135. package/src/useSearch.tsx +5 -2
  136. package/build/cjs/CatchBoundary.js +0 -128
  137. package/build/cjs/CatchBoundary.js.map +0 -1
  138. package/build/cjs/Matches.js +0 -260
  139. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js +0 -29
  140. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js.map +0 -1
  141. package/build/cjs/awaited.js +0 -60
  142. package/build/cjs/awaited.js.map +0 -1
  143. package/build/cjs/defer.js +0 -42
  144. package/build/cjs/fileRoute.js +0 -31
  145. package/build/cjs/fileRoute.js.map +0 -1
  146. package/build/cjs/index.js.map +0 -1
  147. package/build/cjs/lazyRouteComponent.js +0 -54
  148. package/build/cjs/link.js +0 -224
  149. package/build/cjs/link.js.map +0 -1
  150. package/build/cjs/path.js.map +0 -1
  151. package/build/cjs/qss.js +0 -63
  152. package/build/cjs/qss.js.map +0 -1
  153. package/build/cjs/redirects.js +0 -28
  154. package/build/cjs/route.js +0 -292
  155. package/build/cjs/route.js.map +0 -1
  156. package/build/cjs/router.js +0 -1116
  157. package/build/cjs/routerContext.js +0 -42
  158. package/build/cjs/scroll-restoration.js.map +0 -1
  159. package/build/cjs/useBlocker.js +0 -55
  160. package/build/cjs/useNavigate.js +0 -88
  161. package/build/cjs/useParams.js +0 -27
  162. package/build/cjs/useRouteContext.js +0 -23
  163. package/build/cjs/useRouter.js +0 -44
  164. package/build/cjs/useRouterState.js +0 -24
  165. package/build/cjs/useSearch.js +0 -25
  166. package/build/cjs/useSearch.js.map +0 -1
  167. package/build/esm/index.js +0 -2874
  168. package/build/esm/index.js.map +0 -1
  169. package/build/stats-html.html +0 -4838
  170. package/build/stats-react.json +0 -1471
  171. package/build/umd/index.development.js +0 -3573
  172. package/build/umd/index.development.js.map +0 -1
  173. package/build/umd/index.production.js +0 -22
  174. package/build/umd/index.production.js.map +0 -1
  175. /package/{build/types/CatchBoundary.d.ts → dist/cjs/CatchBoundary.d.cts} +0 -0
  176. /package/{build/types/Matches.d.ts → dist/cjs/Matches.d.cts} +0 -0
  177. /package/{build/types/RouterProvider.d.ts → dist/cjs/RouterProvider.d.cts} +0 -0
  178. /package/{build/types/awaited.d.ts → dist/cjs/awaited.d.cts} +0 -0
  179. /package/{build/types/defer.d.ts → dist/cjs/defer.d.cts} +0 -0
  180. /package/{build/types/fileRoute.d.ts → dist/cjs/fileRoute.d.cts} +0 -0
  181. /package/{build/types/index.d.ts → dist/cjs/index.d.cts} +0 -0
  182. /package/{build/types/lazyRouteComponent.d.ts → dist/cjs/lazyRouteComponent.d.cts} +0 -0
  183. /package/{build/types/location.d.ts → dist/cjs/location.d.cts} +0 -0
  184. /package/{build/types/path.d.ts → dist/cjs/path.d.cts} +0 -0
  185. /package/{build/types/qss.d.ts → dist/cjs/qss.d.cts} +0 -0
  186. /package/{build/types/redirects.d.ts → dist/cjs/redirects.d.cts} +0 -0
  187. /package/{build/types/route.d.ts → dist/cjs/route.d.cts} +0 -0
  188. /package/{build/types/routeInfo.d.ts → dist/cjs/routeInfo.d.cts} +0 -0
  189. /package/{build/types/router.d.ts → dist/cjs/router.d.cts} +0 -0
  190. /package/{build/types/routerContext.d.ts → dist/cjs/routerContext.d.cts} +0 -0
  191. /package/{build/types/scroll-restoration.d.ts → dist/cjs/scroll-restoration.d.cts} +0 -0
  192. /package/{build/types/searchParams.d.ts → dist/cjs/searchParams.d.cts} +0 -0
  193. /package/{build/types/useBlocker.d.ts → dist/cjs/useBlocker.d.cts} +0 -0
  194. /package/{build/types/useNavigate.d.ts → dist/cjs/useNavigate.d.cts} +0 -0
  195. /package/{build/types/useParams.d.ts → dist/cjs/useParams.d.cts} +0 -0
  196. /package/{build/types/useRouteContext.d.ts → dist/cjs/useRouteContext.d.cts} +0 -0
  197. /package/{build/types/useRouter.d.ts → dist/cjs/useRouter.d.cts} +0 -0
  198. /package/{build/types/useRouterState.d.ts → dist/cjs/useRouterState.d.cts} +0 -0
  199. /package/{build/types/useSearch.d.ts → dist/cjs/useSearch.d.cts} +0 -0
  200. /package/{build/types/utils.d.ts → dist/cjs/utils.d.cts} +0 -0
@@ -0,0 +1,1070 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const history = require("@tanstack/history");
4
+ const store = require("@tanstack/store");
5
+ const searchParams = require("./searchParams.cjs");
6
+ const utils = require("./utils.cjs");
7
+ const RouterProvider = require("./RouterProvider.cjs");
8
+ const path = require("./path.cjs");
9
+ const invariant = require("tiny-invariant");
10
+ const redirects = require("./redirects.cjs");
11
+ const componentTypes = [
12
+ "component",
13
+ "errorComponent",
14
+ "pendingComponent"
15
+ ];
16
+ class Router {
17
+ constructor(options) {
18
+ this.tempLocationKey = `${Math.round(
19
+ Math.random() * 1e7
20
+ )}`;
21
+ this.resetNextScroll = true;
22
+ this.navigateTimeout = null;
23
+ this.latestLoadPromise = Promise.resolve();
24
+ this.subscribers = /* @__PURE__ */ new Set();
25
+ this.injectedHtml = [];
26
+ this.startReactTransition = (fn) => fn();
27
+ this.update = (newOptions) => {
28
+ const previousOptions = this.options;
29
+ this.options = {
30
+ ...this.options,
31
+ ...newOptions
32
+ };
33
+ if (!this.basepath || newOptions.basepath && newOptions.basepath !== previousOptions.basepath) {
34
+ if (newOptions.basepath === void 0 || newOptions.basepath === "" || newOptions.basepath === "/") {
35
+ this.basepath = "/";
36
+ } else {
37
+ this.basepath = `/${path.trimPath(newOptions.basepath)}`;
38
+ }
39
+ }
40
+ if (!this.history || this.options.history && this.options.history !== this.history) {
41
+ this.history = this.options.history ?? (typeof document !== "undefined" ? history.createBrowserHistory() : history.createMemoryHistory({
42
+ initialEntries: [this.options.basepath || "/"]
43
+ }));
44
+ this.latestLocation = this.parseLocation();
45
+ }
46
+ if (this.options.routeTree !== this.routeTree) {
47
+ this.routeTree = this.options.routeTree;
48
+ this.buildRouteTree();
49
+ }
50
+ if (!this.__store) {
51
+ this.__store = new store.Store(getInitialRouterState(this.latestLocation), {
52
+ onUpdate: () => {
53
+ this.__store.state = {
54
+ ...this.state,
55
+ status: this.state.isTransitioning || this.state.isLoading ? "pending" : "idle"
56
+ };
57
+ }
58
+ });
59
+ }
60
+ };
61
+ this.buildRouteTree = () => {
62
+ this.routesById = {};
63
+ this.routesByPath = {};
64
+ const notFoundRoute = this.options.notFoundRoute;
65
+ if (notFoundRoute) {
66
+ notFoundRoute.init({ originalIndex: 99999999999 });
67
+ this.routesById[notFoundRoute.id] = notFoundRoute;
68
+ }
69
+ const recurseRoutes = (childRoutes) => {
70
+ childRoutes.forEach((childRoute, i) => {
71
+ childRoute.init({ originalIndex: i });
72
+ const existingRoute = this.routesById[childRoute.id];
73
+ invariant(
74
+ !existingRoute,
75
+ `Duplicate routes found with id: ${String(childRoute.id)}`
76
+ );
77
+ this.routesById[childRoute.id] = childRoute;
78
+ if (!childRoute.isRoot && childRoute.path) {
79
+ const trimmedFullPath = path.trimPathRight(childRoute.fullPath);
80
+ if (!this.routesByPath[trimmedFullPath] || childRoute.fullPath.endsWith("/")) {
81
+ this.routesByPath[trimmedFullPath] = childRoute;
82
+ }
83
+ }
84
+ const children = childRoute.children;
85
+ if (children == null ? void 0 : children.length) {
86
+ recurseRoutes(children);
87
+ }
88
+ });
89
+ };
90
+ recurseRoutes([this.routeTree]);
91
+ const scoredRoutes = [];
92
+ Object.values(this.routesById).forEach((d, i) => {
93
+ var _a;
94
+ if (d.isRoot || !d.path) {
95
+ return;
96
+ }
97
+ const trimmed = path.trimPathLeft(d.fullPath);
98
+ const parsed = path.parsePathname(trimmed);
99
+ while (parsed.length > 1 && ((_a = parsed[0]) == null ? void 0 : _a.value) === "/") {
100
+ parsed.shift();
101
+ }
102
+ const scores = parsed.map((d2) => {
103
+ if (d2.value === "/") {
104
+ return 0.75;
105
+ }
106
+ if (d2.type === "param") {
107
+ return 0.5;
108
+ }
109
+ if (d2.type === "wildcard") {
110
+ return 0.25;
111
+ }
112
+ return 1;
113
+ });
114
+ scoredRoutes.push({ child: d, trimmed, parsed, index: i, scores });
115
+ });
116
+ this.flatRoutes = scoredRoutes.sort((a, b) => {
117
+ const minLength = Math.min(a.scores.length, b.scores.length);
118
+ for (let i = 0; i < minLength; i++) {
119
+ if (a.scores[i] !== b.scores[i]) {
120
+ return b.scores[i] - a.scores[i];
121
+ }
122
+ }
123
+ if (a.scores.length !== b.scores.length) {
124
+ return b.scores.length - a.scores.length;
125
+ }
126
+ for (let i = 0; i < minLength; i++) {
127
+ if (a.parsed[i].value !== b.parsed[i].value) {
128
+ return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
129
+ }
130
+ }
131
+ return a.index - b.index;
132
+ }).map((d, i) => {
133
+ d.child.rank = i;
134
+ return d.child;
135
+ });
136
+ };
137
+ this.subscribe = (eventType, fn) => {
138
+ const listener = {
139
+ eventType,
140
+ fn
141
+ };
142
+ this.subscribers.add(listener);
143
+ return () => {
144
+ this.subscribers.delete(listener);
145
+ };
146
+ };
147
+ this.emit = (routerEvent) => {
148
+ this.subscribers.forEach((listener) => {
149
+ if (listener.eventType === routerEvent.type) {
150
+ listener.fn(routerEvent);
151
+ }
152
+ });
153
+ };
154
+ this.checkLatest = (promise) => {
155
+ return this.latestLoadPromise !== promise ? this.latestLoadPromise : void 0;
156
+ };
157
+ this.parseLocation = (previousLocation) => {
158
+ const parse = ({
159
+ pathname,
160
+ search,
161
+ hash,
162
+ state
163
+ }) => {
164
+ const parsedSearch = this.options.parseSearch(search);
165
+ return {
166
+ pathname,
167
+ searchStr: search,
168
+ search: utils.replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.search, parsedSearch),
169
+ hash: hash.split("#").reverse()[0] ?? "",
170
+ href: `${pathname}${search}${hash}`,
171
+ state: utils.replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.state, state)
172
+ };
173
+ };
174
+ const location = parse(this.history.location);
175
+ let { __tempLocation, __tempKey } = location.state;
176
+ if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
177
+ const parsedTempLocation = parse(__tempLocation);
178
+ parsedTempLocation.state.key = location.state.key;
179
+ delete parsedTempLocation.state.__tempLocation;
180
+ return {
181
+ ...parsedTempLocation,
182
+ maskedLocation: location
183
+ };
184
+ }
185
+ return location;
186
+ };
187
+ this.resolvePathWithBase = (from, path$1) => {
188
+ return path.resolvePath(this.basepath, from, path.cleanPath(path$1));
189
+ };
190
+ this.matchRoutes = (pathname, locationSearch, opts) => {
191
+ let routeParams = {};
192
+ let foundRoute = this.flatRoutes.find((route) => {
193
+ const matchedParams = path.matchPathname(
194
+ this.basepath,
195
+ path.trimPathRight(pathname),
196
+ {
197
+ to: route.fullPath,
198
+ caseSensitive: route.options.caseSensitive ?? this.options.caseSensitive,
199
+ fuzzy: true
200
+ }
201
+ );
202
+ if (matchedParams) {
203
+ routeParams = matchedParams;
204
+ return true;
205
+ }
206
+ return false;
207
+ });
208
+ let routeCursor = foundRoute || this.routesById["__root__"];
209
+ let matchedRoutes = [routeCursor];
210
+ if (
211
+ // If we found a route, and it's not an index route and we have left over path
212
+ (foundRoute ? foundRoute.path !== "/" && routeParams["**"] : (
213
+ // Or if we didn't find a route and we have left over path
214
+ path.trimPathRight(pathname)
215
+ )) && // And we have a 404 route configured
216
+ this.options.notFoundRoute
217
+ ) {
218
+ matchedRoutes.push(this.options.notFoundRoute);
219
+ }
220
+ while (routeCursor == null ? void 0 : routeCursor.parentRoute) {
221
+ routeCursor = routeCursor.parentRoute;
222
+ if (routeCursor)
223
+ matchedRoutes.unshift(routeCursor);
224
+ }
225
+ const parseErrors = matchedRoutes.map((route) => {
226
+ let parsedParamsError;
227
+ if (route.options.parseParams) {
228
+ try {
229
+ const parsedParams = route.options.parseParams(routeParams);
230
+ Object.assign(routeParams, parsedParams);
231
+ } catch (err) {
232
+ parsedParamsError = new PathParamError(err.message, {
233
+ cause: err
234
+ });
235
+ if (opts == null ? void 0 : opts.throwOnError) {
236
+ throw parsedParamsError;
237
+ }
238
+ return parsedParamsError;
239
+ }
240
+ }
241
+ return;
242
+ });
243
+ const matches = [];
244
+ matchedRoutes.forEach((route, index) => {
245
+ var _a, _b;
246
+ const parentMatch = matches[index - 1];
247
+ const [preMatchSearch, searchError] = (() => {
248
+ const parentSearch = (parentMatch == null ? void 0 : parentMatch.search) ?? locationSearch;
249
+ try {
250
+ const validator = typeof route.options.validateSearch === "object" ? route.options.validateSearch.parse : route.options.validateSearch;
251
+ let search = (validator == null ? void 0 : validator(parentSearch)) ?? {};
252
+ return [
253
+ {
254
+ ...parentSearch,
255
+ ...search
256
+ },
257
+ void 0
258
+ ];
259
+ } catch (err) {
260
+ const searchError2 = new SearchParamError(err.message, {
261
+ cause: err
262
+ });
263
+ if (opts == null ? void 0 : opts.throwOnError) {
264
+ throw searchError2;
265
+ }
266
+ return [parentSearch, searchError2];
267
+ }
268
+ })();
269
+ const loaderDeps = ((_b = (_a = route.options).loaderDeps) == null ? void 0 : _b.call(_a, {
270
+ search: preMatchSearch
271
+ })) ?? "";
272
+ const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : "";
273
+ const interpolatedPath = path.interpolatePath(route.fullPath, routeParams);
274
+ const matchId = path.interpolatePath(route.id, routeParams, true) + loaderDepsHash;
275
+ const existingMatch = RouterProvider.getRouteMatch(this.state, matchId);
276
+ const cause = this.state.matches.find((d) => d.id === matchId) ? "stay" : "enter";
277
+ const hasLoaders = !!(route.options.loader || componentTypes.some((d) => {
278
+ var _a2;
279
+ return (_a2 = route.options[d]) == null ? void 0 : _a2.preload;
280
+ }));
281
+ const match = existingMatch ? { ...existingMatch, cause } : {
282
+ id: matchId,
283
+ routeId: route.id,
284
+ params: routeParams,
285
+ pathname: path.joinPaths([this.basepath, interpolatedPath]),
286
+ updatedAt: Date.now(),
287
+ search: {},
288
+ searchError: void 0,
289
+ status: hasLoaders ? "pending" : "success",
290
+ showPending: false,
291
+ isFetching: false,
292
+ error: void 0,
293
+ paramsError: parseErrors[index],
294
+ loadPromise: Promise.resolve(),
295
+ routeContext: void 0,
296
+ context: void 0,
297
+ abortController: new AbortController(),
298
+ fetchCount: 0,
299
+ cause,
300
+ loaderDeps,
301
+ invalid: false,
302
+ preload: false
303
+ };
304
+ match.search = utils.replaceEqualDeep(match.search, preMatchSearch);
305
+ match.searchError = searchError;
306
+ matches.push(match);
307
+ });
308
+ return matches;
309
+ };
310
+ this.cancelMatch = (id) => {
311
+ var _a, _b;
312
+ (_b = (_a = RouterProvider.getRouteMatch(this.state, id)) == null ? void 0 : _a.abortController) == null ? void 0 : _b.abort();
313
+ };
314
+ this.cancelMatches = () => {
315
+ var _a;
316
+ (_a = this.state.pendingMatches) == null ? void 0 : _a.forEach((match) => {
317
+ this.cancelMatch(match.id);
318
+ });
319
+ };
320
+ this.buildLocation = (opts) => {
321
+ const build = (dest = {}, matches) => {
322
+ var _a, _b;
323
+ const relevantMatches = this.state.pendingMatches || this.state.matches;
324
+ const fromSearch = ((_a = relevantMatches[relevantMatches.length - 1]) == null ? void 0 : _a.search) || this.latestLocation.search;
325
+ let pathname = this.resolvePathWithBase(
326
+ dest.from ?? this.latestLocation.pathname,
327
+ `${dest.to ?? ""}`
328
+ );
329
+ const fromMatches = this.matchRoutes(
330
+ this.latestLocation.pathname,
331
+ fromSearch
332
+ );
333
+ const stayingMatches = matches == null ? void 0 : matches.filter(
334
+ (d) => fromMatches == null ? void 0 : fromMatches.find((e) => e.routeId === d.routeId)
335
+ );
336
+ const prevParams = { ...(_b = utils.last(fromMatches)) == null ? void 0 : _b.params };
337
+ let nextParams = (dest.params ?? true) === true ? prevParams : utils.functionalUpdate(dest.params, prevParams);
338
+ if (nextParams) {
339
+ matches == null ? void 0 : matches.map((d) => this.looseRoutesById[d.routeId].options.stringifyParams).filter(Boolean).forEach((fn) => {
340
+ nextParams = { ...nextParams, ...fn(nextParams) };
341
+ });
342
+ }
343
+ pathname = path.interpolatePath(pathname, nextParams ?? {});
344
+ const preSearchFilters = (stayingMatches == null ? void 0 : stayingMatches.map(
345
+ (match) => this.looseRoutesById[match.routeId].options.preSearchFilters ?? []
346
+ ).flat().filter(Boolean)) ?? [];
347
+ const postSearchFilters = (stayingMatches == null ? void 0 : stayingMatches.map(
348
+ (match) => this.looseRoutesById[match.routeId].options.postSearchFilters ?? []
349
+ ).flat().filter(Boolean)) ?? [];
350
+ const preFilteredSearch = (preSearchFilters == null ? void 0 : preSearchFilters.length) ? preSearchFilters == null ? void 0 : preSearchFilters.reduce(
351
+ (prev, next) => next(prev),
352
+ fromSearch
353
+ ) : fromSearch;
354
+ const destSearch = dest.search === true ? preFilteredSearch : dest.search ? utils.functionalUpdate(dest.search, preFilteredSearch) ?? {} : (preSearchFilters == null ? void 0 : preSearchFilters.length) ? preFilteredSearch : {};
355
+ const postFilteredSearch = (postSearchFilters == null ? void 0 : postSearchFilters.length) ? postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
356
+ const search = utils.replaceEqualDeep(fromSearch, postFilteredSearch);
357
+ const searchStr = this.options.stringifySearch(search);
358
+ const hash = dest.hash === true ? this.latestLocation.hash : dest.hash ? utils.functionalUpdate(dest.hash, this.latestLocation.hash) : void 0;
359
+ const hashStr = hash ? `#${hash}` : "";
360
+ let nextState = dest.state === true ? this.latestLocation.state : dest.state ? utils.functionalUpdate(dest.state, this.latestLocation.state) : this.latestLocation.state;
361
+ nextState = utils.replaceEqualDeep(this.latestLocation.state, nextState);
362
+ return {
363
+ pathname,
364
+ search,
365
+ searchStr,
366
+ state: nextState,
367
+ hash: hash ?? "",
368
+ href: `${pathname}${searchStr}${hashStr}`,
369
+ unmaskOnReload: dest.unmaskOnReload
370
+ };
371
+ };
372
+ const buildWithMatches = (dest = {}, maskedDest) => {
373
+ var _a;
374
+ let next = build(dest);
375
+ let maskedNext = maskedDest ? build(maskedDest) : void 0;
376
+ if (!maskedNext) {
377
+ let params = {};
378
+ let foundMask = (_a = this.options.routeMasks) == null ? void 0 : _a.find((d) => {
379
+ const match = path.matchPathname(this.basepath, next.pathname, {
380
+ to: d.from,
381
+ caseSensitive: false,
382
+ fuzzy: false
383
+ });
384
+ if (match) {
385
+ params = match;
386
+ return true;
387
+ }
388
+ return false;
389
+ });
390
+ if (foundMask) {
391
+ maskedDest = {
392
+ ...utils.pick(opts, ["from"]),
393
+ ...foundMask,
394
+ params
395
+ };
396
+ maskedNext = build(maskedDest);
397
+ }
398
+ }
399
+ const nextMatches = this.matchRoutes(next.pathname, next.search);
400
+ const maskedMatches = maskedNext ? this.matchRoutes(maskedNext.pathname, maskedNext.search) : void 0;
401
+ const maskedFinal = maskedNext ? build(maskedDest, maskedMatches) : void 0;
402
+ const final = build(dest, nextMatches);
403
+ if (maskedFinal) {
404
+ final.maskedLocation = maskedFinal;
405
+ }
406
+ return final;
407
+ };
408
+ if (opts.mask) {
409
+ return buildWithMatches(opts, {
410
+ ...utils.pick(opts, ["from"]),
411
+ ...opts.mask
412
+ });
413
+ }
414
+ return buildWithMatches(opts);
415
+ };
416
+ this.commitLocation = async ({
417
+ startTransition,
418
+ ...next
419
+ }) => {
420
+ if (this.navigateTimeout)
421
+ clearTimeout(this.navigateTimeout);
422
+ const isSameUrl = this.latestLocation.href === next.href;
423
+ if (!isSameUrl || !next.replace) {
424
+ let { maskedLocation, ...nextHistory } = next;
425
+ if (maskedLocation) {
426
+ nextHistory = {
427
+ ...maskedLocation,
428
+ state: {
429
+ ...maskedLocation.state,
430
+ __tempKey: void 0,
431
+ __tempLocation: {
432
+ ...nextHistory,
433
+ search: nextHistory.searchStr,
434
+ state: {
435
+ ...nextHistory.state,
436
+ __tempKey: void 0,
437
+ __tempLocation: void 0,
438
+ key: void 0
439
+ }
440
+ }
441
+ }
442
+ };
443
+ if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) {
444
+ nextHistory.state.__tempKey = this.tempLocationKey;
445
+ }
446
+ }
447
+ const apply = () => {
448
+ this.history[next.replace ? "replace" : "push"](
449
+ nextHistory.href,
450
+ nextHistory.state
451
+ );
452
+ };
453
+ if (startTransition ?? true) {
454
+ this.startReactTransition(apply);
455
+ } else {
456
+ apply();
457
+ }
458
+ }
459
+ this.resetNextScroll = next.resetScroll ?? true;
460
+ return this.latestLoadPromise;
461
+ };
462
+ this.buildAndCommitLocation = ({
463
+ replace,
464
+ resetScroll,
465
+ startTransition,
466
+ ...rest
467
+ } = {}) => {
468
+ const location = this.buildLocation(rest);
469
+ return this.commitLocation({
470
+ ...location,
471
+ startTransition,
472
+ replace,
473
+ resetScroll
474
+ });
475
+ };
476
+ this.navigate = ({ from, to, ...rest }) => {
477
+ const toString = String(to);
478
+ let isExternal;
479
+ try {
480
+ new URL(`${toString}`);
481
+ isExternal = true;
482
+ } catch (e) {
483
+ }
484
+ invariant(
485
+ !isExternal,
486
+ "Attempting to navigate to external url with this.navigate!"
487
+ );
488
+ return this.buildAndCommitLocation({
489
+ ...rest,
490
+ from,
491
+ to
492
+ // to: toString,
493
+ });
494
+ };
495
+ this.loadMatches = async ({
496
+ checkLatest,
497
+ matches,
498
+ preload
499
+ }) => {
500
+ var _a, _b;
501
+ let latestPromise;
502
+ let firstBadMatchIndex;
503
+ const updateMatch = (match) => {
504
+ var _a2;
505
+ const isPending = (_a2 = this.state.pendingMatches) == null ? void 0 : _a2.find(
506
+ (d) => d.id === match.id
507
+ );
508
+ const isMatched = this.state.matches.find((d) => d.id === match.id);
509
+ const matchesKey = isPending ? "pendingMatches" : isMatched ? "matches" : "cachedMatches";
510
+ this.__store.setState((s) => {
511
+ var _a3;
512
+ return {
513
+ ...s,
514
+ [matchesKey]: (_a3 = s[matchesKey]) == null ? void 0 : _a3.map(
515
+ (d) => d.id === match.id ? match : d
516
+ )
517
+ };
518
+ });
519
+ };
520
+ try {
521
+ for (let [index, match] of matches.entries()) {
522
+ const parentMatch = matches[index - 1];
523
+ const route = this.looseRoutesById[match.routeId];
524
+ const abortController = new AbortController();
525
+ const handleErrorAndRedirect = (err, code) => {
526
+ var _a2, _b2;
527
+ err.routerCode = code;
528
+ firstBadMatchIndex = firstBadMatchIndex ?? index;
529
+ if (redirects.isRedirect(err)) {
530
+ throw err;
531
+ }
532
+ try {
533
+ (_b2 = (_a2 = route.options).onError) == null ? void 0 : _b2.call(_a2, err);
534
+ } catch (errorHandlerErr) {
535
+ err = errorHandlerErr;
536
+ if (redirects.isRedirect(errorHandlerErr)) {
537
+ throw errorHandlerErr;
538
+ }
539
+ }
540
+ matches[index] = match = {
541
+ ...match,
542
+ error: err,
543
+ status: "error",
544
+ updatedAt: Date.now(),
545
+ abortController: new AbortController()
546
+ };
547
+ };
548
+ try {
549
+ if (match.paramsError) {
550
+ handleErrorAndRedirect(match.paramsError, "PARSE_PARAMS");
551
+ }
552
+ if (match.searchError) {
553
+ handleErrorAndRedirect(match.searchError, "VALIDATE_SEARCH");
554
+ }
555
+ const parentContext = (parentMatch == null ? void 0 : parentMatch.context) ?? this.options.context ?? {};
556
+ const pendingMs = route.options.pendingMs ?? this.options.defaultPendingMs;
557
+ const pendingPromise = typeof pendingMs === "number" && pendingMs <= 0 ? Promise.resolve() : new Promise((r) => setTimeout(r, pendingMs));
558
+ const beforeLoadContext = await ((_b = (_a = route.options).beforeLoad) == null ? void 0 : _b.call(_a, {
559
+ search: match.search,
560
+ abortController,
561
+ params: match.params,
562
+ preload: !!preload,
563
+ context: parentContext,
564
+ location: this.state.location,
565
+ // TOOD: just expose state and router, etc
566
+ navigate: (opts) => this.navigate({ ...opts, from: match.pathname }),
567
+ buildLocation: this.buildLocation,
568
+ cause: preload ? "preload" : match.cause
569
+ })) ?? {};
570
+ if (redirects.isRedirect(beforeLoadContext)) {
571
+ throw beforeLoadContext;
572
+ }
573
+ const context = {
574
+ ...parentContext,
575
+ ...beforeLoadContext
576
+ };
577
+ matches[index] = match = {
578
+ ...match,
579
+ routeContext: utils.replaceEqualDeep(
580
+ match.routeContext,
581
+ beforeLoadContext
582
+ ),
583
+ context: utils.replaceEqualDeep(match.context, context),
584
+ abortController,
585
+ pendingPromise
586
+ };
587
+ } catch (err) {
588
+ handleErrorAndRedirect(err, "BEFORE_LOAD");
589
+ break;
590
+ }
591
+ }
592
+ } catch (err) {
593
+ if (redirects.isRedirect(err)) {
594
+ if (!preload)
595
+ this.navigate(err);
596
+ return matches;
597
+ }
598
+ throw err;
599
+ }
600
+ const validResolvedMatches = matches.slice(0, firstBadMatchIndex);
601
+ const matchPromises = [];
602
+ validResolvedMatches.forEach((match, index) => {
603
+ matchPromises.push(
604
+ new Promise(async (resolve) => {
605
+ var _a2;
606
+ const parentMatchPromise = matchPromises[index - 1];
607
+ const route = this.looseRoutesById[match.routeId];
608
+ const handleErrorAndRedirect = (err) => {
609
+ if (redirects.isRedirect(err)) {
610
+ if (!preload) {
611
+ this.navigate(err);
612
+ }
613
+ return true;
614
+ }
615
+ return false;
616
+ };
617
+ let loadPromise;
618
+ matches[index] = match = {
619
+ ...match,
620
+ showPending: false
621
+ };
622
+ let didShowPending = false;
623
+ const pendingMs = route.options.pendingMs ?? this.options.defaultPendingMs;
624
+ const pendingMinMs = route.options.pendingMinMs ?? this.options.defaultPendingMinMs;
625
+ const shouldPending = !preload && typeof pendingMs === "number" && (route.options.pendingComponent ?? this.options.defaultPendingComponent);
626
+ const loaderContext = {
627
+ params: match.params,
628
+ deps: match.loaderDeps,
629
+ preload: !!preload,
630
+ parentMatchPromise,
631
+ abortController: match.abortController,
632
+ context: match.context,
633
+ location: this.state.location,
634
+ navigate: (opts) => this.navigate({ ...opts, from: match.pathname }),
635
+ cause: preload ? "preload" : match.cause
636
+ };
637
+ const fetch = async () => {
638
+ var _a3, _b2, _c, _d, _e;
639
+ if (match.isFetching) {
640
+ loadPromise = (_a3 = RouterProvider.getRouteMatch(this.state, match.id)) == null ? void 0 : _a3.loadPromise;
641
+ } else {
642
+ if (match.fetchCount && match.status === "success") {
643
+ resolve();
644
+ }
645
+ matches[index] = match = {
646
+ ...match,
647
+ isFetching: true,
648
+ fetchCount: match.fetchCount + 1
649
+ };
650
+ const componentsPromise = Promise.all(
651
+ componentTypes.map(async (type) => {
652
+ const component = route.options[type];
653
+ if (component == null ? void 0 : component.preload) {
654
+ await component.preload();
655
+ }
656
+ })
657
+ );
658
+ const loaderPromise = (_c = (_b2 = route.options).loader) == null ? void 0 : _c.call(_b2, loaderContext);
659
+ loadPromise = Promise.all([
660
+ componentsPromise,
661
+ loaderPromise
662
+ ]).then((d) => d[1]);
663
+ }
664
+ matches[index] = match = {
665
+ ...match,
666
+ loadPromise
667
+ };
668
+ updateMatch(match);
669
+ try {
670
+ const loaderData = await loadPromise;
671
+ if (latestPromise = checkLatest())
672
+ return await latestPromise;
673
+ if (redirects.isRedirect(loaderData)) {
674
+ if (handleErrorAndRedirect(loaderData))
675
+ return;
676
+ }
677
+ if (didShowPending && pendingMinMs) {
678
+ await new Promise((r) => setTimeout(r, pendingMinMs));
679
+ }
680
+ if (latestPromise = checkLatest())
681
+ return await latestPromise;
682
+ matches[index] = match = {
683
+ ...match,
684
+ error: void 0,
685
+ status: "success",
686
+ isFetching: false,
687
+ updatedAt: Date.now(),
688
+ loaderData,
689
+ loadPromise: void 0
690
+ };
691
+ } catch (error) {
692
+ if (latestPromise = checkLatest())
693
+ return await latestPromise;
694
+ if (handleErrorAndRedirect(error))
695
+ return;
696
+ try {
697
+ (_e = (_d = route.options).onError) == null ? void 0 : _e.call(_d, error);
698
+ } catch (onErrorError) {
699
+ error = onErrorError;
700
+ if (handleErrorAndRedirect(onErrorError))
701
+ return;
702
+ }
703
+ matches[index] = match = {
704
+ ...match,
705
+ error,
706
+ status: "error",
707
+ isFetching: false
708
+ };
709
+ }
710
+ updateMatch(match);
711
+ };
712
+ const age = Date.now() - match.updatedAt;
713
+ let staleAge = preload ? route.options.preloadStaleTime ?? this.options.defaultPreloadStaleTime ?? 3e4 : route.options.staleTime ?? this.options.defaultStaleTime ?? 0;
714
+ let shouldReload;
715
+ const shouldReloadOption = route.options.shouldReload;
716
+ shouldReload = typeof shouldReloadOption === "function" ? shouldReloadOption(loaderContext) : shouldReloadOption;
717
+ matches[index] = match = {
718
+ ...match,
719
+ preload: !!preload && !this.state.matches.find((d) => d.id === match.id)
720
+ };
721
+ if (match.status !== "success") {
722
+ if (shouldPending) {
723
+ (_a2 = match.pendingPromise) == null ? void 0 : _a2.then(async () => {
724
+ if (latestPromise = checkLatest())
725
+ return latestPromise;
726
+ didShowPending = true;
727
+ matches[index] = match = {
728
+ ...match,
729
+ showPending: true
730
+ };
731
+ updateMatch(match);
732
+ resolve();
733
+ });
734
+ }
735
+ await fetch();
736
+ } else if (match.invalid || (shouldReload ?? age > staleAge)) {
737
+ fetch();
738
+ }
739
+ resolve();
740
+ })
741
+ );
742
+ });
743
+ await Promise.all(matchPromises);
744
+ return matches;
745
+ };
746
+ this.invalidate = () => {
747
+ const invalidate = (d) => ({
748
+ ...d,
749
+ invalid: true
750
+ });
751
+ this.__store.setState((s) => {
752
+ var _a;
753
+ return {
754
+ ...s,
755
+ matches: s.matches.map(invalidate),
756
+ cachedMatches: s.cachedMatches.map(invalidate),
757
+ pendingMatches: (_a = s.pendingMatches) == null ? void 0 : _a.map(invalidate)
758
+ };
759
+ });
760
+ this.load();
761
+ };
762
+ this.load = async () => {
763
+ const promise = new Promise(async (resolve, reject) => {
764
+ const next = this.latestLocation;
765
+ const prevLocation = this.state.resolvedLocation;
766
+ const pathDidChange = prevLocation.href !== next.href;
767
+ let latestPromise;
768
+ this.cancelMatches();
769
+ this.emit({
770
+ type: "onBeforeLoad",
771
+ fromLocation: prevLocation,
772
+ toLocation: next,
773
+ pathChanged: pathDidChange
774
+ });
775
+ let pendingMatches;
776
+ const previousMatches = this.state.matches;
777
+ this.__store.batch(() => {
778
+ this.cleanCache();
779
+ pendingMatches = this.matchRoutes(next.pathname, next.search, {
780
+ debug: true
781
+ });
782
+ this.__store.setState((s) => ({
783
+ ...s,
784
+ isLoading: true,
785
+ location: next,
786
+ pendingMatches,
787
+ cachedMatches: s.cachedMatches.filter((d) => {
788
+ return !pendingMatches.find((e) => e.id === d.id);
789
+ })
790
+ }));
791
+ });
792
+ try {
793
+ try {
794
+ await this.loadMatches({
795
+ matches: pendingMatches,
796
+ checkLatest: () => this.checkLatest(promise)
797
+ });
798
+ } catch (err) {
799
+ }
800
+ if (latestPromise = this.checkLatest(promise)) {
801
+ return latestPromise;
802
+ }
803
+ const exitingMatches = previousMatches.filter(
804
+ (match) => !pendingMatches.find((d) => d.id === match.id)
805
+ );
806
+ const enteringMatches = pendingMatches.filter(
807
+ (match) => !previousMatches.find((d) => d.id === match.id)
808
+ );
809
+ const stayingMatches = previousMatches.filter(
810
+ (match) => pendingMatches.find((d) => d.id === match.id)
811
+ );
812
+ this.__store.batch(() => {
813
+ this.__store.setState((s) => ({
814
+ ...s,
815
+ isLoading: false,
816
+ matches: s.pendingMatches,
817
+ pendingMatches: void 0,
818
+ cachedMatches: [
819
+ ...s.cachedMatches,
820
+ ...exitingMatches.filter((d) => d.status !== "error")
821
+ ]
822
+ }));
823
+ this.cleanCache();
824
+ });
825
+ [
826
+ [exitingMatches, "onLeave"],
827
+ [enteringMatches, "onEnter"],
828
+ [stayingMatches, "onStay"]
829
+ ].forEach(([matches, hook]) => {
830
+ matches.forEach((match) => {
831
+ var _a, _b;
832
+ (_b = (_a = this.looseRoutesById[match.routeId].options)[hook]) == null ? void 0 : _b.call(_a, match);
833
+ });
834
+ });
835
+ this.emit({
836
+ type: "onLoad",
837
+ fromLocation: prevLocation,
838
+ toLocation: next,
839
+ pathChanged: pathDidChange
840
+ });
841
+ resolve();
842
+ } catch (err) {
843
+ if (latestPromise = this.checkLatest(promise)) {
844
+ return latestPromise;
845
+ }
846
+ reject(err);
847
+ }
848
+ });
849
+ this.latestLoadPromise = promise;
850
+ return this.latestLoadPromise;
851
+ };
852
+ this.cleanCache = () => {
853
+ this.__store.setState((s) => {
854
+ return {
855
+ ...s,
856
+ cachedMatches: s.cachedMatches.filter((d) => {
857
+ const route = this.looseRoutesById[d.routeId];
858
+ if (!route.options.loader) {
859
+ return false;
860
+ }
861
+ const gcTime = (d.preload ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime : route.options.gcTime ?? this.options.defaultGcTime) ?? 5 * 60 * 1e3;
862
+ return d.status !== "error" && Date.now() - d.updatedAt < gcTime;
863
+ })
864
+ };
865
+ });
866
+ };
867
+ this.preloadRoute = async (navigateOpts = this.state.location) => {
868
+ var _a;
869
+ let next = this.buildLocation(navigateOpts);
870
+ let matches = this.matchRoutes(next.pathname, next.search, {
871
+ throwOnError: true
872
+ });
873
+ const loadedMatchIds = Object.fromEntries(
874
+ (_a = [
875
+ ...this.state.matches,
876
+ ...this.state.pendingMatches ?? [],
877
+ ...this.state.cachedMatches
878
+ ]) == null ? void 0 : _a.map((d) => [d.id, true])
879
+ );
880
+ this.__store.batch(() => {
881
+ matches.forEach((match) => {
882
+ if (!loadedMatchIds[match.id]) {
883
+ this.__store.setState((s) => ({
884
+ ...s,
885
+ cachedMatches: [...s.cachedMatches, match]
886
+ }));
887
+ }
888
+ });
889
+ });
890
+ matches = await this.loadMatches({
891
+ matches,
892
+ preload: true,
893
+ checkLatest: () => void 0
894
+ });
895
+ return matches;
896
+ };
897
+ this.matchRoute = (location, opts) => {
898
+ location = {
899
+ ...location,
900
+ to: location.to ? this.resolvePathWithBase(location.from || "", location.to) : void 0
901
+ };
902
+ const next = this.buildLocation(location);
903
+ if ((opts == null ? void 0 : opts.pending) && this.state.status !== "pending") {
904
+ return false;
905
+ }
906
+ const baseLocation = (opts == null ? void 0 : opts.pending) ? this.latestLocation : this.state.resolvedLocation;
907
+ if (!baseLocation) {
908
+ return false;
909
+ }
910
+ const match = path.matchPathname(this.basepath, baseLocation.pathname, {
911
+ ...opts,
912
+ to: next.pathname
913
+ });
914
+ if (!match) {
915
+ return false;
916
+ }
917
+ if (match && ((opts == null ? void 0 : opts.includeSearch) ?? true)) {
918
+ return utils.deepEqual(baseLocation.search, next.search, true) ? match : false;
919
+ }
920
+ return match;
921
+ };
922
+ this.injectHtml = async (html) => {
923
+ this.injectedHtml.push(html);
924
+ };
925
+ this.dehydrateData = (key, getData) => {
926
+ if (typeof document === "undefined") {
927
+ const strKey = typeof key === "string" ? key : JSON.stringify(key);
928
+ this.injectHtml(async () => {
929
+ const id = `__TSR_DEHYDRATED__${strKey}`;
930
+ const data = typeof getData === "function" ? await getData() : getData;
931
+ return `<script id='${id}' suppressHydrationWarning>window["__TSR_DEHYDRATED__${utils.escapeJSON(
932
+ strKey
933
+ )}"] = ${JSON.stringify(data)}
934
+ ;(() => {
935
+ var el = document.getElementById('${id}')
936
+ el.parentElement.removeChild(el)
937
+ })()
938
+ <\/script>`;
939
+ });
940
+ return () => this.hydrateData(key);
941
+ }
942
+ return () => void 0;
943
+ };
944
+ this.hydrateData = (key) => {
945
+ if (typeof document !== "undefined") {
946
+ const strKey = typeof key === "string" ? key : JSON.stringify(key);
947
+ return window[`__TSR_DEHYDRATED__${strKey}`];
948
+ }
949
+ return void 0;
950
+ };
951
+ this.dehydrate = () => {
952
+ var _a;
953
+ const pickError = ((_a = this.options.errorSerializer) == null ? void 0 : _a.serialize) ?? defaultSerializeError;
954
+ return {
955
+ state: {
956
+ dehydratedMatches: this.state.matches.map((d) => ({
957
+ ...utils.pick(d, ["id", "status", "updatedAt", "loaderData"]),
958
+ // If an error occurs server-side during SSRing,
959
+ // send a small subset of the error to the client
960
+ error: d.error ? {
961
+ data: pickError(d.error),
962
+ __isServerError: true
963
+ } : void 0
964
+ }))
965
+ }
966
+ };
967
+ };
968
+ this.hydrate = async (__do_not_use_server_ctx) => {
969
+ var _a, _b;
970
+ let _ctx = __do_not_use_server_ctx;
971
+ if (typeof document !== "undefined") {
972
+ _ctx = window.__TSR_DEHYDRATED__;
973
+ }
974
+ invariant(
975
+ _ctx,
976
+ "Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?"
977
+ );
978
+ const ctx = _ctx;
979
+ this.dehydratedData = ctx.payload;
980
+ (_b = (_a = this.options).hydrate) == null ? void 0 : _b.call(_a, ctx.payload);
981
+ const dehydratedState = ctx.router.state;
982
+ let matches = this.matchRoutes(
983
+ this.state.location.pathname,
984
+ this.state.location.search
985
+ ).map((match) => {
986
+ const dehydratedMatch = dehydratedState.dehydratedMatches.find(
987
+ (d) => d.id === match.id
988
+ );
989
+ invariant(
990
+ dehydratedMatch,
991
+ `Could not find a client-side match for dehydrated match with id: ${match.id}!`
992
+ );
993
+ if (dehydratedMatch) {
994
+ return {
995
+ ...match,
996
+ ...dehydratedMatch
997
+ };
998
+ }
999
+ return match;
1000
+ });
1001
+ this.__store.setState((s) => {
1002
+ return {
1003
+ ...s,
1004
+ matches
1005
+ };
1006
+ });
1007
+ };
1008
+ this.update({
1009
+ defaultPreloadDelay: 50,
1010
+ defaultPendingMs: 1e3,
1011
+ defaultPendingMinMs: 500,
1012
+ context: void 0,
1013
+ ...options,
1014
+ stringifySearch: (options == null ? void 0 : options.stringifySearch) ?? searchParams.defaultStringifySearch,
1015
+ parseSearch: (options == null ? void 0 : options.parseSearch) ?? searchParams.defaultParseSearch
1016
+ });
1017
+ }
1018
+ get state() {
1019
+ return this.__store.state;
1020
+ }
1021
+ get looseRoutesById() {
1022
+ return this.routesById;
1023
+ }
1024
+ // resolveMatchPromise = (matchId: string, key: string, value: any) => {
1025
+ // state.matches
1026
+ // .find((d) => d.id === matchId)
1027
+ // ?.__promisesByKey[key]?.resolve(value)
1028
+ // }
1029
+ }
1030
+ function lazyFn(fn, key) {
1031
+ return async (...args) => {
1032
+ const imported = await fn();
1033
+ return imported[key || "default"](...args);
1034
+ };
1035
+ }
1036
+ class SearchParamError extends Error {
1037
+ }
1038
+ class PathParamError extends Error {
1039
+ }
1040
+ function getInitialRouterState(location) {
1041
+ return {
1042
+ isLoading: false,
1043
+ isTransitioning: false,
1044
+ status: "idle",
1045
+ resolvedLocation: { ...location },
1046
+ location,
1047
+ matches: [],
1048
+ pendingMatches: [],
1049
+ cachedMatches: [],
1050
+ lastUpdated: Date.now()
1051
+ };
1052
+ }
1053
+ function defaultSerializeError(err) {
1054
+ if (err instanceof Error)
1055
+ return {
1056
+ name: err.name,
1057
+ message: err.message
1058
+ };
1059
+ return {
1060
+ data: err
1061
+ };
1062
+ }
1063
+ exports.PathParamError = PathParamError;
1064
+ exports.Router = Router;
1065
+ exports.SearchParamError = SearchParamError;
1066
+ exports.componentTypes = componentTypes;
1067
+ exports.defaultSerializeError = defaultSerializeError;
1068
+ exports.getInitialRouterState = getInitialRouterState;
1069
+ exports.lazyFn = lazyFn;
1070
+ //# sourceMappingURL=router.cjs.map