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