@tanstack/react-router 1.7.1 → 1.8.1

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