@tanstack/router-core 0.0.1-beta.16 → 0.0.1-beta.161

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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/build/cjs/fileRoute.js +29 -0
  3. package/build/cjs/fileRoute.js.map +1 -0
  4. package/build/cjs/history.js +226 -0
  5. package/build/cjs/history.js.map +1 -0
  6. package/build/cjs/index.js +78 -0
  7. package/build/cjs/{packages/router-core/src/index.js.map → index.js.map} +1 -1
  8. package/build/cjs/{packages/router-core/src/path.js → path.js} +45 -56
  9. package/build/cjs/path.js.map +1 -0
  10. package/build/cjs/{packages/router-core/src/qss.js → qss.js} +10 -16
  11. package/build/cjs/qss.js.map +1 -0
  12. package/build/cjs/route.js +101 -0
  13. package/build/cjs/route.js.map +1 -0
  14. package/build/cjs/router.js +1134 -0
  15. package/build/cjs/router.js.map +1 -0
  16. package/build/cjs/{packages/router-core/src/searchParams.js → searchParams.js} +34 -19
  17. package/build/cjs/searchParams.js.map +1 -0
  18. package/build/cjs/{packages/router-core/src/utils.js → utils.js} +54 -64
  19. package/build/cjs/utils.js.map +1 -0
  20. package/build/esm/index.js +1439 -2091
  21. package/build/esm/index.js.map +1 -1
  22. package/build/stats-html.html +59 -49
  23. package/build/stats-react.json +203 -234
  24. package/build/types/index.d.ts +573 -431
  25. package/build/umd/index.development.js +1673 -2221
  26. package/build/umd/index.development.js.map +1 -1
  27. package/build/umd/index.production.js +13 -2
  28. package/build/umd/index.production.js.map +1 -1
  29. package/package.json +11 -7
  30. package/src/fileRoute.ts +162 -0
  31. package/src/history.ts +292 -0
  32. package/src/index.ts +3 -10
  33. package/src/link.ts +121 -118
  34. package/src/path.ts +37 -17
  35. package/src/qss.ts +1 -2
  36. package/src/route.ts +874 -218
  37. package/src/routeInfo.ts +47 -211
  38. package/src/router.ts +1511 -1024
  39. package/src/searchParams.ts +33 -9
  40. package/src/utils.ts +80 -49
  41. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js +0 -33
  42. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js.map +0 -1
  43. package/build/cjs/node_modules/@babel/runtime/helpers/esm/extends.js +0 -33
  44. package/build/cjs/node_modules/@babel/runtime/helpers/esm/extends.js.map +0 -1
  45. package/build/cjs/node_modules/history/index.js +0 -815
  46. package/build/cjs/node_modules/history/index.js.map +0 -1
  47. package/build/cjs/node_modules/tiny-invariant/dist/esm/tiny-invariant.js +0 -30
  48. package/build/cjs/node_modules/tiny-invariant/dist/esm/tiny-invariant.js.map +0 -1
  49. package/build/cjs/packages/router-core/src/index.js +0 -58
  50. package/build/cjs/packages/router-core/src/path.js.map +0 -1
  51. package/build/cjs/packages/router-core/src/qss.js.map +0 -1
  52. package/build/cjs/packages/router-core/src/route.js +0 -147
  53. package/build/cjs/packages/router-core/src/route.js.map +0 -1
  54. package/build/cjs/packages/router-core/src/routeConfig.js +0 -69
  55. package/build/cjs/packages/router-core/src/routeConfig.js.map +0 -1
  56. package/build/cjs/packages/router-core/src/routeMatch.js +0 -231
  57. package/build/cjs/packages/router-core/src/routeMatch.js.map +0 -1
  58. package/build/cjs/packages/router-core/src/router.js +0 -833
  59. package/build/cjs/packages/router-core/src/router.js.map +0 -1
  60. package/build/cjs/packages/router-core/src/searchParams.js.map +0 -1
  61. package/build/cjs/packages/router-core/src/utils.js.map +0 -1
  62. package/src/frameworks.ts +0 -11
  63. package/src/routeConfig.ts +0 -514
  64. package/src/routeMatch.ts +0 -319
@@ -0,0 +1,1134 @@
1
+ /**
2
+ * @tanstack/router-core/src/index.ts
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
+ Object.defineProperty(exports, '__esModule', { value: true });
14
+
15
+ var reactStore = require('@tanstack/react-store');
16
+ var invariant = require('tiny-invariant');
17
+ var path = require('./path.js');
18
+ var searchParams = require('./searchParams.js');
19
+ var utils = require('./utils.js');
20
+ var history = require('./history.js');
21
+
22
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
23
+
24
+ var invariant__default = /*#__PURE__*/_interopDefaultLegacy(invariant);
25
+
26
+ //
27
+
28
+ const componentTypes = ['component', 'errorComponent', 'pendingComponent'];
29
+ class Router {
30
+ #unsubHistory;
31
+ constructor(options) {
32
+ this.options = {
33
+ defaultPreloadDelay: 50,
34
+ context: undefined,
35
+ ...options,
36
+ stringifySearch: options?.stringifySearch ?? searchParams.defaultStringifySearch,
37
+ parseSearch: options?.parseSearch ?? searchParams.defaultParseSearch
38
+ // fetchServerDataFn: options?.fetchServerDataFn ?? defaultFetchServerDataFn,
39
+ };
40
+
41
+ this.__store = new reactStore.Store(getInitialRouterState(), {
42
+ onUpdate: () => {
43
+ const prev = this.state;
44
+ const next = this.__store.state;
45
+ const matchesByIdChanged = prev.matchesById !== next.matchesById;
46
+ let matchesChanged;
47
+ let pendingMatchesChanged;
48
+ if (!matchesByIdChanged) {
49
+ matchesChanged = prev.matchIds.length !== next.matchIds.length || prev.matchIds.some((d, i) => d !== next.matchIds[i]);
50
+ pendingMatchesChanged = prev.pendingMatchIds.length !== next.pendingMatchIds.length || prev.pendingMatchIds.some((d, i) => d !== next.pendingMatchIds[i]);
51
+ }
52
+ if (matchesByIdChanged || matchesChanged) {
53
+ next.matches = next.matchIds.map(id => {
54
+ return next.matchesById[id];
55
+ });
56
+ }
57
+ if (matchesByIdChanged || pendingMatchesChanged) {
58
+ next.pendingMatches = next.pendingMatchIds.map(id => {
59
+ return next.matchesById[id];
60
+ });
61
+ }
62
+ next.isFetching = [...next.matches, ...next.pendingMatches].some(d => d.isFetching);
63
+ this.state = next;
64
+ },
65
+ defaultPriority: 'low'
66
+ });
67
+ this.state = this.__store.state;
68
+ this.update(options);
69
+ const next = this.buildNext({
70
+ hash: true,
71
+ fromCurrent: true,
72
+ search: true,
73
+ state: true
74
+ });
75
+ if (this.state.location.href !== next.href) {
76
+ this.#commitLocation({
77
+ ...next,
78
+ replace: true
79
+ });
80
+ }
81
+ }
82
+ reset = () => {
83
+ this.__store.setState(s => Object.assign(s, getInitialRouterState()));
84
+ };
85
+ mount = () => {
86
+ // If the router matches are empty, start loading the matches
87
+ // if (!this.state.matches.length) {
88
+ this.safeLoad();
89
+ // }
90
+ };
91
+
92
+ update = opts => {
93
+ this.options = {
94
+ ...this.options,
95
+ ...opts,
96
+ context: {
97
+ ...this.options.context,
98
+ ...opts?.context
99
+ }
100
+ };
101
+ if (!this.history || this.options.history && this.options.history !== this.history) {
102
+ if (this.#unsubHistory) {
103
+ this.#unsubHistory();
104
+ }
105
+ this.history = this.options.history ?? (isServer ? history.createMemoryHistory() : history.createBrowserHistory());
106
+ const parsedLocation = this.#parseLocation();
107
+ this.__store.setState(s => ({
108
+ ...s,
109
+ resolvedLocation: parsedLocation,
110
+ location: parsedLocation
111
+ }));
112
+ this.#unsubHistory = this.history.listen(() => {
113
+ this.safeLoad({
114
+ next: this.#parseLocation(this.state.location)
115
+ });
116
+ });
117
+ }
118
+ const {
119
+ basepath,
120
+ routeTree
121
+ } = this.options;
122
+ this.basepath = `/${path.trimPath(basepath ?? '') ?? ''}`;
123
+ if (routeTree && routeTree !== this.routeTree) {
124
+ this.#buildRouteTree(routeTree);
125
+ }
126
+ return this;
127
+ };
128
+ buildNext = opts => {
129
+ const next = this.#buildLocation(opts);
130
+ const __matches = this.matchRoutes(next.pathname, next.search);
131
+ return this.#buildLocation({
132
+ ...opts,
133
+ __matches
134
+ });
135
+ };
136
+ cancelMatches = () => {
137
+ this.state.matches.forEach(match => {
138
+ this.cancelMatch(match.id);
139
+ });
140
+ };
141
+ cancelMatch = id => {
142
+ this.getRouteMatch(id)?.abortController?.abort();
143
+ };
144
+ safeLoad = async opts => {
145
+ try {
146
+ return this.load(opts);
147
+ } catch (err) {
148
+ // Don't do anything
149
+ }
150
+ };
151
+ latestLoadPromise = Promise.resolve();
152
+ load = async opts => {
153
+ const promise = new Promise(async (resolve, reject) => {
154
+ let latestPromise;
155
+ const checkLatest = () => {
156
+ return this.latestLoadPromise !== promise ? this.latestLoadPromise : undefined;
157
+ };
158
+
159
+ // Cancel any pending matches
160
+ // this.cancelMatches()
161
+
162
+ let pendingMatches;
163
+ this.__store.batch(() => {
164
+ if (opts?.next) {
165
+ // Ingest the new location
166
+ this.__store.setState(s => ({
167
+ ...s,
168
+ location: opts.next
169
+ }));
170
+ }
171
+
172
+ // Match the routes
173
+ pendingMatches = this.matchRoutes(this.state.location.pathname, this.state.location.search, {
174
+ throwOnError: opts?.throwOnError,
175
+ debug: true
176
+ });
177
+ this.__store.setState(s => ({
178
+ ...s,
179
+ status: 'pending',
180
+ pendingMatchIds: pendingMatches.map(d => d.id),
181
+ matchesById: this.#mergeMatches(s.matchesById, pendingMatches)
182
+ }));
183
+ });
184
+ try {
185
+ // Load the matches
186
+ try {
187
+ await this.loadMatches(pendingMatches);
188
+ } catch (err) {
189
+ // swallow this error, since we'll display the
190
+ // errors on the route components
191
+ }
192
+
193
+ // Only apply the latest transition
194
+ if (latestPromise = checkLatest()) {
195
+ return latestPromise;
196
+ }
197
+ const prevLocation = this.state.resolvedLocation;
198
+ this.__store.setState(s => ({
199
+ ...s,
200
+ status: 'idle',
201
+ resolvedLocation: s.location,
202
+ matchIds: s.pendingMatchIds,
203
+ pendingMatchIds: []
204
+ }));
205
+ if (prevLocation.href !== this.state.location.href) {
206
+ this.options.onRouteChange?.();
207
+ }
208
+ resolve();
209
+ } catch (err) {
210
+ // Only apply the latest transition
211
+ if (latestPromise = checkLatest()) {
212
+ return latestPromise;
213
+ }
214
+ reject(err);
215
+ }
216
+ });
217
+ this.latestLoadPromise = promise;
218
+ return this.latestLoadPromise;
219
+ };
220
+ #mergeMatches = (prevMatchesById, nextMatches) => {
221
+ const nextMatchesById = {
222
+ ...prevMatchesById
223
+ };
224
+ let hadNew = false;
225
+ nextMatches.forEach(match => {
226
+ if (!nextMatchesById[match.id]) {
227
+ hadNew = true;
228
+ nextMatchesById[match.id] = match;
229
+ }
230
+ });
231
+ if (!hadNew) {
232
+ return prevMatchesById;
233
+ }
234
+ return nextMatchesById;
235
+ };
236
+ getRoute = id => {
237
+ const route = this.routesById[id];
238
+ invariant__default["default"](route, `Route with id "${id}" not found`);
239
+ return route;
240
+ };
241
+ preloadRoute = async (navigateOpts = this.state.location) => {
242
+ const next = this.buildNext(navigateOpts);
243
+ const matches = this.matchRoutes(next.pathname, next.search, {
244
+ throwOnError: true
245
+ });
246
+ this.__store.setState(s => {
247
+ return {
248
+ ...s,
249
+ matchesById: this.#mergeMatches(s.matchesById, matches)
250
+ };
251
+ });
252
+ await this.loadMatches(matches, {
253
+ preload: true,
254
+ maxAge: navigateOpts.maxAge
255
+ });
256
+ return matches;
257
+ };
258
+ cleanMatches = () => {
259
+ const now = Date.now();
260
+ const outdatedMatchIds = Object.values(this.state.matchesById).filter(match => {
261
+ const route = this.getRoute(match.routeId);
262
+ return !this.state.matchIds.includes(match.id) && !this.state.pendingMatchIds.includes(match.id) && match.preloadInvalidAt < now && (route.options.gcMaxAge ? match.updatedAt + route.options.gcMaxAge < now : true);
263
+ }).map(d => d.id);
264
+ if (outdatedMatchIds.length) {
265
+ this.__store.setState(s => {
266
+ const matchesById = {
267
+ ...s.matchesById
268
+ };
269
+ outdatedMatchIds.forEach(id => {
270
+ delete matchesById[id];
271
+ });
272
+ return {
273
+ ...s,
274
+ matchesById
275
+ };
276
+ });
277
+ }
278
+ };
279
+ matchRoutes = (pathname, locationSearch, opts) => {
280
+ let routeParams = {};
281
+ let foundRoute = this.flatRoutes.find(route => {
282
+ const matchedParams = path.matchPathname(this.basepath, path.trimPathRight(pathname), {
283
+ to: route.fullPath,
284
+ caseSensitive: route.options.caseSensitive ?? this.options.caseSensitive
285
+ });
286
+ if (matchedParams) {
287
+ routeParams = matchedParams;
288
+ return true;
289
+ }
290
+ return false;
291
+ });
292
+ let routeCursor = foundRoute || this.routesById['__root__'];
293
+ let matchedRoutes = [routeCursor];
294
+ // let includingLayouts = true
295
+ while (routeCursor?.parentRoute) {
296
+ routeCursor = routeCursor.parentRoute;
297
+ if (routeCursor) matchedRoutes.unshift(routeCursor);
298
+ }
299
+
300
+ // Existing matches are matches that are already loaded along with
301
+ // pending matches that are still loading
302
+
303
+ const parseErrors = matchedRoutes.map(route => {
304
+ let parsedParamsError;
305
+ if (route.options.parseParams) {
306
+ try {
307
+ const parsedParams = route.options.parseParams(routeParams);
308
+ // Add the parsed params to the accumulated params bag
309
+ Object.assign(routeParams, parsedParams);
310
+ } catch (err) {
311
+ parsedParamsError = new PathParamError(err.message, {
312
+ cause: err
313
+ });
314
+ if (opts?.throwOnError) {
315
+ throw parsedParamsError;
316
+ }
317
+ return parsedParamsError;
318
+ }
319
+ }
320
+ return;
321
+ });
322
+ const matches = matchedRoutes.map((route, index) => {
323
+ const interpolatedPath = path.interpolatePath(route.path, routeParams);
324
+ const key = route.options.key ? route.options.key({
325
+ params: routeParams,
326
+ search: locationSearch
327
+ }) ?? '' : '';
328
+ const stringifiedKey = key ? JSON.stringify(key) : '';
329
+ const matchId = path.interpolatePath(route.id, routeParams, true) + stringifiedKey;
330
+
331
+ // Waste not, want not. If we already have a match for this route,
332
+ // reuse it. This is important for layout routes, which might stick
333
+ // around between navigation actions that only change leaf routes.
334
+ const existingMatch = this.getRouteMatch(matchId);
335
+ if (existingMatch) {
336
+ return {
337
+ ...existingMatch
338
+ };
339
+ }
340
+
341
+ // Create a fresh route match
342
+ const hasLoaders = !!(route.options.loader || componentTypes.some(d => route.options[d]?.preload));
343
+ const routeMatch = {
344
+ id: matchId,
345
+ key: stringifiedKey,
346
+ routeId: route.id,
347
+ params: routeParams,
348
+ pathname: path.joinPaths([this.basepath, interpolatedPath]),
349
+ updatedAt: Date.now(),
350
+ invalidAt: Infinity,
351
+ preloadInvalidAt: Infinity,
352
+ routeSearch: {},
353
+ search: {},
354
+ status: hasLoaders ? 'pending' : 'success',
355
+ isFetching: false,
356
+ invalid: false,
357
+ error: undefined,
358
+ paramsError: parseErrors[index],
359
+ searchError: undefined,
360
+ loaderData: undefined,
361
+ loadPromise: Promise.resolve(),
362
+ routeContext: undefined,
363
+ context: undefined,
364
+ abortController: new AbortController(),
365
+ fetchedAt: 0
366
+ };
367
+ return routeMatch;
368
+ });
369
+
370
+ // Take each match and resolve its search params and context
371
+ // This has to happen after the matches are created or found
372
+ // so that we can use the parent match's search params and context
373
+ matches.forEach((match, i) => {
374
+ const parentMatch = matches[i - 1];
375
+ const route = this.getRoute(match.routeId);
376
+ const searchInfo = (() => {
377
+ // Validate the search params and stabilize them
378
+ const parentSearchInfo = {
379
+ search: parentMatch?.search ?? locationSearch,
380
+ routeSearch: parentMatch?.routeSearch ?? locationSearch
381
+ };
382
+ try {
383
+ const validator = typeof route.options.validateSearch === 'object' ? route.options.validateSearch.parse : route.options.validateSearch;
384
+ const routeSearch = validator?.(parentSearchInfo.search) ?? {};
385
+ const search = {
386
+ ...parentSearchInfo.search,
387
+ ...routeSearch
388
+ };
389
+ return {
390
+ routeSearch: utils.replaceEqualDeep(match.routeSearch, routeSearch),
391
+ search: utils.replaceEqualDeep(match.search, search)
392
+ };
393
+ } catch (err) {
394
+ match.searchError = new SearchParamError(err.message, {
395
+ cause: err
396
+ });
397
+ if (opts?.throwOnError) {
398
+ throw match.searchError;
399
+ }
400
+ return parentSearchInfo;
401
+ }
402
+ })();
403
+ Object.assign(match, {
404
+ ...searchInfo
405
+ });
406
+ const contextInfo = (() => {
407
+ try {
408
+ const routeContext = route.options.getContext?.({
409
+ parentContext: parentMatch?.routeContext ?? {},
410
+ context: parentMatch?.context ?? this?.options.context ?? {},
411
+ params: match.params,
412
+ search: match.search
413
+ }) || {};
414
+ const context = {
415
+ ...(parentMatch?.context ?? this?.options.context),
416
+ ...routeContext
417
+ };
418
+ return {
419
+ context,
420
+ routeContext
421
+ };
422
+ } catch (err) {
423
+ route.options.onError?.(err);
424
+ throw err;
425
+ }
426
+ })();
427
+ Object.assign(match, {
428
+ ...contextInfo
429
+ });
430
+ });
431
+ return matches;
432
+ };
433
+ loadMatches = async (resolvedMatches, opts) => {
434
+ this.cleanMatches();
435
+ if (!opts?.preload) {
436
+ resolvedMatches.forEach(match => {
437
+ // Update each match with its latest route data
438
+ this.setRouteMatch(match.id, s => ({
439
+ ...s,
440
+ routeSearch: match.routeSearch,
441
+ search: match.search,
442
+ routeContext: match.routeContext,
443
+ context: match.context,
444
+ error: match.error,
445
+ paramsError: match.paramsError,
446
+ searchError: match.searchError,
447
+ params: match.params
448
+ }));
449
+ });
450
+ }
451
+ let firstBadMatchIndex;
452
+
453
+ // Check each match middleware to see if the route can be accessed
454
+ try {
455
+ for (const [index, match] of resolvedMatches.entries()) {
456
+ const route = this.getRoute(match.routeId);
457
+ const handleError = (err, handler) => {
458
+ firstBadMatchIndex = firstBadMatchIndex ?? index;
459
+ handler = handler || route.options.onError;
460
+ if (isRedirect(err)) {
461
+ throw err;
462
+ }
463
+ try {
464
+ handler?.(err);
465
+ } catch (errorHandlerErr) {
466
+ err = errorHandlerErr;
467
+ if (isRedirect(errorHandlerErr)) {
468
+ throw errorHandlerErr;
469
+ }
470
+ }
471
+ this.setRouteMatch(match.id, s => ({
472
+ ...s,
473
+ error: err,
474
+ status: 'error',
475
+ updatedAt: Date.now()
476
+ }));
477
+ };
478
+ if (match.paramsError) {
479
+ handleError(match.paramsError, route.options.onParseParamsError);
480
+ }
481
+ if (match.searchError) {
482
+ handleError(match.searchError, route.options.onValidateSearchError);
483
+ }
484
+ let didError = false;
485
+ try {
486
+ await route.options.beforeLoad?.({
487
+ ...match,
488
+ preload: !!opts?.preload
489
+ });
490
+ } catch (err) {
491
+ handleError(err, route.options.onBeforeLoadError);
492
+ didError = true;
493
+ }
494
+
495
+ // If we errored, do not run the next matches' middleware
496
+ if (didError) {
497
+ break;
498
+ }
499
+ }
500
+ } catch (err) {
501
+ if (!opts?.preload) {
502
+ this.navigate(err);
503
+ }
504
+ throw err;
505
+ }
506
+ const validResolvedMatches = resolvedMatches.slice(0, firstBadMatchIndex);
507
+ const matchPromises = [];
508
+ validResolvedMatches.forEach((match, index) => {
509
+ matchPromises.push((async () => {
510
+ const parentMatchPromise = matchPromises[index - 1];
511
+ const route = this.getRoute(match.routeId);
512
+ if (match.isFetching || match.status === 'success' && !this.getIsInvalid({
513
+ matchId: match.id,
514
+ preload: opts?.preload
515
+ })) {
516
+ return this.getRouteMatch(match.id)?.loadPromise;
517
+ }
518
+ const fetchedAt = Date.now();
519
+ const checkLatest = () => {
520
+ const latest = this.getRouteMatch(match.id);
521
+ return latest && latest.fetchedAt !== fetchedAt ? latest.loadPromise : undefined;
522
+ };
523
+ const handleIfRedirect = err => {
524
+ if (isRedirect(err)) {
525
+ if (!opts?.preload) {
526
+ this.navigate(err);
527
+ }
528
+ return true;
529
+ }
530
+ return false;
531
+ };
532
+ const load = async () => {
533
+ let latestPromise;
534
+ try {
535
+ const componentsPromise = Promise.all(componentTypes.map(async type => {
536
+ const component = route.options[type];
537
+ if (component?.preload) {
538
+ await component.preload();
539
+ }
540
+ }));
541
+ const loaderPromise = route.options.loader?.({
542
+ ...match,
543
+ preload: !!opts?.preload,
544
+ parentMatchPromise
545
+ });
546
+ const [_, loader] = await Promise.all([componentsPromise, loaderPromise]);
547
+ if (latestPromise = checkLatest()) return await latestPromise;
548
+ this.setRouteMatchData(match.id, () => loader, opts);
549
+ } catch (loaderError) {
550
+ let latestError = loaderError;
551
+ if (latestPromise = checkLatest()) return await latestPromise;
552
+ if (handleIfRedirect(loaderError)) return;
553
+ if (route.options.onLoadError) {
554
+ try {
555
+ route.options.onLoadError(loaderError);
556
+ } catch (onLoadError) {
557
+ latestError = onLoadError;
558
+ if (handleIfRedirect(onLoadError)) return;
559
+ }
560
+ }
561
+ if ((!route.options.onLoadError || latestError !== loaderError) && route.options.onError) {
562
+ try {
563
+ route.options.onError(latestError);
564
+ } catch (onErrorError) {
565
+ if (handleIfRedirect(onErrorError)) return;
566
+ }
567
+ }
568
+ this.setRouteMatch(match.id, s => ({
569
+ ...s,
570
+ error: loaderError,
571
+ status: 'error',
572
+ isFetching: false,
573
+ updatedAt: Date.now()
574
+ }));
575
+ }
576
+ };
577
+ let loadPromise;
578
+ this.__store.batch(() => {
579
+ this.setRouteMatch(match.id, s => ({
580
+ ...s,
581
+ // status: s.status !== 'success' ? 'pending' : s.status,
582
+ isFetching: true,
583
+ fetchedAt,
584
+ invalid: false
585
+ }));
586
+ loadPromise = load();
587
+ this.setRouteMatch(match.id, s => ({
588
+ ...s,
589
+ loadPromise
590
+ }));
591
+ });
592
+ await loadPromise;
593
+ })());
594
+ });
595
+ await Promise.all(matchPromises);
596
+ };
597
+ reload = () => {
598
+ return this.navigate({
599
+ fromCurrent: true,
600
+ replace: true,
601
+ search: true
602
+ });
603
+ };
604
+ resolvePath = (from, path$1) => {
605
+ return path.resolvePath(this.basepath, from, path.cleanPath(path$1));
606
+ };
607
+ navigate = async ({
608
+ from,
609
+ to = '',
610
+ search,
611
+ hash,
612
+ replace,
613
+ params
614
+ }) => {
615
+ // If this link simply reloads the current route,
616
+ // make sure it has a new key so it will trigger a data refresh
617
+
618
+ // If this `to` is a valid external URL, return
619
+ // null for LinkUtils
620
+ const toString = String(to);
621
+ const fromString = typeof from === 'undefined' ? from : String(from);
622
+ let isExternal;
623
+ try {
624
+ new URL(`${toString}`);
625
+ isExternal = true;
626
+ } catch (e) {}
627
+ invariant__default["default"](!isExternal, 'Attempting to navigate to external url with this.navigate!');
628
+ return this.#commitLocation({
629
+ from: fromString,
630
+ to: toString,
631
+ search,
632
+ hash,
633
+ replace,
634
+ params
635
+ });
636
+ };
637
+ matchRoute = (location, opts) => {
638
+ location = {
639
+ ...location,
640
+ to: location.to ? this.resolvePath(location.from ?? '', location.to) : undefined
641
+ };
642
+ const next = this.buildNext(location);
643
+ if (opts?.pending && this.state.status !== 'pending') {
644
+ return false;
645
+ }
646
+ const baseLocation = opts?.pending ? this.state.location : this.state.resolvedLocation;
647
+ if (!baseLocation) {
648
+ return false;
649
+ }
650
+ const match = path.matchPathname(this.basepath, baseLocation.pathname, {
651
+ ...opts,
652
+ to: next.pathname
653
+ });
654
+ if (!match) {
655
+ return false;
656
+ }
657
+ if (opts?.includeSearch ?? true) {
658
+ return utils.partialDeepEqual(baseLocation.search, next.search) ? match : false;
659
+ }
660
+ return match;
661
+ };
662
+ buildLink = ({
663
+ from,
664
+ to = '.',
665
+ search,
666
+ params,
667
+ hash,
668
+ target,
669
+ replace,
670
+ activeOptions,
671
+ preload,
672
+ preloadDelay: userPreloadDelay,
673
+ disabled,
674
+ state
675
+ }) => {
676
+ // If this link simply reloads the current route,
677
+ // make sure it has a new key so it will trigger a data refresh
678
+
679
+ // If this `to` is a valid external URL, return
680
+ // null for LinkUtils
681
+
682
+ try {
683
+ new URL(`${to}`);
684
+ return {
685
+ type: 'external',
686
+ href: to
687
+ };
688
+ } catch (e) {}
689
+ const nextOpts = {
690
+ from,
691
+ to,
692
+ search,
693
+ params,
694
+ hash,
695
+ replace,
696
+ state
697
+ };
698
+ const next = this.buildNext(nextOpts);
699
+ preload = preload ?? this.options.defaultPreload;
700
+ const preloadDelay = userPreloadDelay ?? this.options.defaultPreloadDelay ?? 0;
701
+
702
+ // Compare path/hash for matches
703
+ const currentPathSplit = this.state.location.pathname.split('/');
704
+ const nextPathSplit = next.pathname.split('/');
705
+ const pathIsFuzzyEqual = nextPathSplit.every((d, i) => d === currentPathSplit[i]);
706
+ // Combine the matches based on user options
707
+ const pathTest = activeOptions?.exact ? this.state.location.pathname === next.pathname : pathIsFuzzyEqual;
708
+ const hashTest = activeOptions?.includeHash ? this.state.location.hash === next.hash : true;
709
+ const searchTest = activeOptions?.includeSearch ?? true ? utils.partialDeepEqual(this.state.location.search, next.search) : true;
710
+
711
+ // The final "active" test
712
+ const isActive = pathTest && hashTest && searchTest;
713
+
714
+ // The click handler
715
+ const handleClick = e => {
716
+ if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!target || target === '_self') && e.button === 0) {
717
+ e.preventDefault();
718
+
719
+ // All is well? Navigate!
720
+ this.#commitLocation(nextOpts);
721
+ }
722
+ };
723
+
724
+ // The click handler
725
+ const handleFocus = e => {
726
+ if (preload) {
727
+ this.preloadRoute(nextOpts).catch(err => {
728
+ console.warn(err);
729
+ console.warn('Error preloading route! ☝️');
730
+ });
731
+ }
732
+ };
733
+ const handleTouchStart = e => {
734
+ this.preloadRoute(nextOpts).catch(err => {
735
+ console.warn(err);
736
+ console.warn('Error preloading route! ☝️');
737
+ });
738
+ };
739
+ const handleEnter = e => {
740
+ const target = e.target || {};
741
+ if (preload) {
742
+ if (target.preloadTimeout) {
743
+ return;
744
+ }
745
+ target.preloadTimeout = setTimeout(() => {
746
+ target.preloadTimeout = null;
747
+ this.preloadRoute(nextOpts).catch(err => {
748
+ console.warn(err);
749
+ console.warn('Error preloading route! ☝️');
750
+ });
751
+ }, preloadDelay);
752
+ }
753
+ };
754
+ const handleLeave = e => {
755
+ const target = e.target || {};
756
+ if (target.preloadTimeout) {
757
+ clearTimeout(target.preloadTimeout);
758
+ target.preloadTimeout = null;
759
+ }
760
+ };
761
+ return {
762
+ type: 'internal',
763
+ next,
764
+ handleFocus,
765
+ handleClick,
766
+ handleEnter,
767
+ handleLeave,
768
+ handleTouchStart,
769
+ isActive,
770
+ disabled
771
+ };
772
+ };
773
+ dehydrate = () => {
774
+ return {
775
+ state: utils.pick(this.state, ['location', 'status', 'lastUpdated'])
776
+ };
777
+ };
778
+ hydrate = async __do_not_use_server_ctx => {
779
+ let _ctx = __do_not_use_server_ctx;
780
+ // Client hydrates from window
781
+ if (typeof document !== 'undefined') {
782
+ _ctx = window.__TSR_DEHYDRATED__;
783
+ }
784
+ invariant__default["default"](_ctx, 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?');
785
+ const ctx = _ctx;
786
+ this.dehydratedData = ctx.payload;
787
+ this.options.hydrate?.(ctx.payload);
788
+ const routerState = ctx.router.state;
789
+ this.__store.setState(s => {
790
+ return {
791
+ ...s,
792
+ ...routerState,
793
+ resolvedLocation: routerState.location
794
+ };
795
+ });
796
+ await this.load();
797
+ return;
798
+ };
799
+ injectedHtml = [];
800
+ injectHtml = async html => {
801
+ this.injectedHtml.push(html);
802
+ };
803
+ dehydrateData = (key, getData) => {
804
+ if (typeof document === 'undefined') {
805
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key);
806
+ this.injectHtml(async () => {
807
+ const id = `__TSR_DEHYDRATED__${strKey}`;
808
+ const data = typeof getData === 'function' ? await getData() : getData;
809
+ return `<script id='${id}' suppressHydrationWarning>window["__TSR_DEHYDRATED__${escapeJSON(strKey)}"] = ${JSON.stringify(data)}
810
+ ;(() => {
811
+ var el = document.getElementById('${id}')
812
+ el.parentElement.removeChild(el)
813
+ })()
814
+ </script>`;
815
+ });
816
+ return () => this.hydrateData(key);
817
+ }
818
+ return () => undefined;
819
+ };
820
+ hydrateData = key => {
821
+ if (typeof document !== 'undefined') {
822
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key);
823
+ return window[`__TSR_DEHYDRATED__${strKey}`];
824
+ }
825
+ return undefined;
826
+ };
827
+
828
+ // resolveMatchPromise = (matchId: string, key: string, value: any) => {
829
+ // this.state.matches
830
+ // .find((d) => d.id === matchId)
831
+ // ?.__promisesByKey[key]?.resolve(value)
832
+ // }
833
+
834
+ #buildRouteTree = routeTree => {
835
+ this.routeTree = routeTree;
836
+ this.routesById = {};
837
+ this.routesByPath = {};
838
+ this.flatRoutes = [];
839
+ const recurseRoutes = routes => {
840
+ routes.forEach((route, i) => {
841
+ route.init({
842
+ originalIndex: i,
843
+ router: this
844
+ });
845
+ const existingRoute = this.routesById[route.id];
846
+ invariant__default["default"](!existingRoute, `Duplicate routes found with id: ${String(route.id)}`);
847
+ this.routesById[route.id] = route;
848
+ if (!route.isRoot && route.path) {
849
+ const trimmedFullPath = path.trimPathRight(route.fullPath);
850
+ if (!this.routesByPath[trimmedFullPath] || route.fullPath.endsWith('/')) {
851
+ this.routesByPath[trimmedFullPath] = route;
852
+ }
853
+ }
854
+ const children = route.children;
855
+ if (children?.length) {
856
+ recurseRoutes(children);
857
+ }
858
+ });
859
+ };
860
+ recurseRoutes([routeTree]);
861
+ this.flatRoutes = Object.values(this.routesByPath).map((d, i) => {
862
+ const trimmed = path.trimPath(d.fullPath);
863
+ const parsed = path.parsePathname(trimmed);
864
+ while (parsed.length > 1 && parsed[0]?.value === '/') {
865
+ parsed.shift();
866
+ }
867
+ const score = parsed.map(d => {
868
+ if (d.type === 'param') {
869
+ return 0.5;
870
+ }
871
+ if (d.type === 'wildcard') {
872
+ return 0.25;
873
+ }
874
+ return 1;
875
+ });
876
+ return {
877
+ child: d,
878
+ trimmed,
879
+ parsed,
880
+ index: i,
881
+ score
882
+ };
883
+ }).sort((a, b) => {
884
+ let isIndex = a.trimmed === '/' ? 1 : b.trimmed === '/' ? -1 : 0;
885
+ if (isIndex !== 0) return isIndex;
886
+ const length = Math.min(a.score.length, b.score.length);
887
+
888
+ // Sort by length of score
889
+ if (a.score.length !== b.score.length) {
890
+ return b.score.length - a.score.length;
891
+ }
892
+
893
+ // Sort by min available score
894
+ for (let i = 0; i < length; i++) {
895
+ if (a.score[i] !== b.score[i]) {
896
+ return b.score[i] - a.score[i];
897
+ }
898
+ }
899
+
900
+ // Sort by min available parsed value
901
+ for (let i = 0; i < length; i++) {
902
+ if (a.parsed[i].value !== b.parsed[i].value) {
903
+ return a.parsed[i].value > b.parsed[i].value ? 1 : -1;
904
+ }
905
+ }
906
+
907
+ // Sort by length of trimmed full path
908
+ if (a.trimmed !== b.trimmed) {
909
+ return a.trimmed > b.trimmed ? 1 : -1;
910
+ }
911
+
912
+ // Sort by original index
913
+ return a.index - b.index;
914
+ }).map((d, i) => {
915
+ d.child.rank = i;
916
+ return d.child;
917
+ });
918
+ };
919
+ #parseLocation = previousLocation => {
920
+ let {
921
+ pathname,
922
+ search,
923
+ hash,
924
+ state
925
+ } = this.history.location;
926
+ const parsedSearch = this.options.parseSearch(search);
927
+ return {
928
+ pathname: pathname,
929
+ searchStr: search,
930
+ search: utils.replaceEqualDeep(previousLocation?.search, parsedSearch),
931
+ hash: hash.split('#').reverse()[0] ?? '',
932
+ href: `${pathname}${search}${hash}`,
933
+ state: state,
934
+ key: state?.key || '__init__'
935
+ };
936
+ };
937
+ #buildLocation = (dest = {}) => {
938
+ dest.fromCurrent = dest.fromCurrent ?? dest.to === '';
939
+ const fromPathname = dest.fromCurrent ? this.state.location.pathname : dest.from ?? this.state.location.pathname;
940
+ let pathname = path.resolvePath(this.basepath ?? '/', fromPathname, `${dest.to ?? ''}`);
941
+ const fromMatches = this.matchRoutes(this.state.location.pathname, this.state.location.search);
942
+ const prevParams = {
943
+ ...utils.last(fromMatches)?.params
944
+ };
945
+ let nextParams = (dest.params ?? true) === true ? prevParams : utils.functionalUpdate(dest.params, prevParams);
946
+ if (nextParams) {
947
+ dest.__matches?.map(d => this.getRoute(d.routeId).options.stringifyParams).filter(Boolean).forEach(fn => {
948
+ nextParams = {
949
+ ...nextParams,
950
+ ...fn(nextParams)
951
+ };
952
+ });
953
+ }
954
+ pathname = path.interpolatePath(pathname, nextParams ?? {});
955
+ const preSearchFilters = dest.__matches?.map(match => this.getRoute(match.routeId).options.preSearchFilters ?? []).flat().filter(Boolean) ?? [];
956
+ const postSearchFilters = dest.__matches?.map(match => this.getRoute(match.routeId).options.postSearchFilters ?? []).flat().filter(Boolean) ?? [];
957
+
958
+ // Pre filters first
959
+ const preFilteredSearch = preSearchFilters?.length ? preSearchFilters?.reduce((prev, next) => next(prev), this.state.location.search) : this.state.location.search;
960
+
961
+ // Then the link/navigate function
962
+ const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
963
+ : dest.search ? utils.functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater
964
+ : preSearchFilters?.length ? preFilteredSearch // Preserve resolvedFrom filters
965
+ : {};
966
+
967
+ // Then post filters
968
+ const postFilteredSearch = postSearchFilters?.length ? postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
969
+ const search = utils.replaceEqualDeep(this.state.location.search, postFilteredSearch);
970
+ const searchStr = this.options.stringifySearch(search);
971
+ const hash = dest.hash === true ? this.state.location.hash : utils.functionalUpdate(dest.hash, this.state.location.hash);
972
+ const hashStr = hash ? `#${hash}` : '';
973
+ const nextState = dest.state === true ? this.state.location.state : utils.functionalUpdate(dest.state, this.state.location.state);
974
+ return {
975
+ pathname,
976
+ search,
977
+ searchStr,
978
+ state: nextState,
979
+ hash,
980
+ href: this.history.createHref(`${pathname}${searchStr}${hashStr}`),
981
+ key: dest.key
982
+ };
983
+ };
984
+ #commitLocation = async location => {
985
+ const next = this.buildNext(location);
986
+ const id = '' + Date.now() + Math.random();
987
+ if (this.navigateTimeout) clearTimeout(this.navigateTimeout);
988
+ let nextAction = 'replace';
989
+ if (!location.replace) {
990
+ nextAction = 'push';
991
+ }
992
+ const isSameUrl = this.state.location.href === next.href;
993
+ if (isSameUrl && !next.key) {
994
+ nextAction = 'replace';
995
+ }
996
+ const href = `${next.pathname}${next.searchStr}${next.hash ? `#${next.hash}` : ''}`;
997
+ this.history[nextAction === 'push' ? 'push' : 'replace'](href, {
998
+ id,
999
+ ...next.state
1000
+ });
1001
+ return this.latestLoadPromise;
1002
+ };
1003
+ getRouteMatch = id => {
1004
+ return this.state.matchesById[id];
1005
+ };
1006
+ setRouteMatch = (id, updater) => {
1007
+ this.__store.setState(prev => {
1008
+ if (!prev.matchesById[id]) {
1009
+ console.warn(`No match found with id: ${id}`);
1010
+ }
1011
+ return {
1012
+ ...prev,
1013
+ matchesById: {
1014
+ ...prev.matchesById,
1015
+ [id]: updater(prev.matchesById[id])
1016
+ }
1017
+ };
1018
+ });
1019
+ };
1020
+ setRouteMatchData = (id, updater, opts) => {
1021
+ const match = this.getRouteMatch(id);
1022
+ if (!match) return;
1023
+ const route = this.getRoute(match.routeId);
1024
+ const updatedAt = opts?.updatedAt ?? Date.now();
1025
+ const preloadInvalidAt = updatedAt + (opts?.maxAge ?? route.options.preloadMaxAge ?? this.options.defaultPreloadMaxAge ?? 5000);
1026
+ const invalidAt = updatedAt + (opts?.maxAge ?? route.options.maxAge ?? this.options.defaultMaxAge ?? Infinity);
1027
+ this.setRouteMatch(id, s => ({
1028
+ ...s,
1029
+ error: undefined,
1030
+ status: 'success',
1031
+ isFetching: false,
1032
+ updatedAt: Date.now(),
1033
+ loaderData: utils.functionalUpdate(updater, s.loaderData),
1034
+ preloadInvalidAt,
1035
+ invalidAt
1036
+ }));
1037
+ if (this.state.matches.find(d => d.id === id)) ;
1038
+ };
1039
+ invalidate = async opts => {
1040
+ if (opts?.matchId) {
1041
+ this.setRouteMatch(opts.matchId, s => ({
1042
+ ...s,
1043
+ invalid: true
1044
+ }));
1045
+ const matchIndex = this.state.matches.findIndex(d => d.id === opts.matchId);
1046
+ const childMatch = this.state.matches[matchIndex + 1];
1047
+ if (childMatch) {
1048
+ return this.invalidate({
1049
+ matchId: childMatch.id,
1050
+ reload: false
1051
+ });
1052
+ }
1053
+ } else {
1054
+ this.__store.batch(() => {
1055
+ Object.values(this.state.matchesById).forEach(match => {
1056
+ this.setRouteMatch(match.id, s => ({
1057
+ ...s,
1058
+ invalid: true
1059
+ }));
1060
+ });
1061
+ });
1062
+ }
1063
+ if (opts?.reload ?? true) {
1064
+ return this.reload();
1065
+ }
1066
+ };
1067
+ getIsInvalid = opts => {
1068
+ if (!opts?.matchId) {
1069
+ return !!this.state.matches.find(d => this.getIsInvalid({
1070
+ matchId: d.id,
1071
+ preload: opts?.preload
1072
+ }));
1073
+ }
1074
+ const match = this.getRouteMatch(opts?.matchId);
1075
+ if (!match) {
1076
+ return false;
1077
+ }
1078
+ const now = Date.now();
1079
+ return match.invalid || (opts?.preload ? match.preloadInvalidAt : match.invalidAt) < now;
1080
+ };
1081
+ }
1082
+
1083
+ // Detect if we're in the DOM
1084
+ const isServer = typeof window === 'undefined' || !window.document.createElement;
1085
+ function getInitialRouterState() {
1086
+ return {
1087
+ status: 'idle',
1088
+ isFetching: false,
1089
+ resolvedLocation: null,
1090
+ location: null,
1091
+ matchesById: {},
1092
+ matchIds: [],
1093
+ pendingMatchIds: [],
1094
+ matches: [],
1095
+ pendingMatches: [],
1096
+ lastUpdated: Date.now()
1097
+ };
1098
+ }
1099
+ function isCtrlEvent(e) {
1100
+ return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
1101
+ }
1102
+ function redirect(opts) {
1103
+ opts.isRedirect = true;
1104
+ return opts;
1105
+ }
1106
+ function isRedirect(obj) {
1107
+ return !!obj?.isRedirect;
1108
+ }
1109
+ class SearchParamError extends Error {}
1110
+ class PathParamError extends Error {}
1111
+ function escapeJSON(jsonString) {
1112
+ return jsonString.replace(/\\/g, '\\\\') // Escape backslashes
1113
+ .replace(/'/g, "\\'") // Escape single quotes
1114
+ .replace(/"/g, '\\"'); // Escape double quotes
1115
+ }
1116
+
1117
+ // A function that takes an import() argument which is a function and returns a new function that will
1118
+ // proxy arguments from the caller to the imported function, retaining all type
1119
+ // information along the way
1120
+ function lazyFn(fn, key) {
1121
+ return async (...args) => {
1122
+ const imported = await fn();
1123
+ return imported[key || 'default'](...args);
1124
+ };
1125
+ }
1126
+
1127
+ exports.PathParamError = PathParamError;
1128
+ exports.Router = Router;
1129
+ exports.SearchParamError = SearchParamError;
1130
+ exports.componentTypes = componentTypes;
1131
+ exports.isRedirect = isRedirect;
1132
+ exports.lazyFn = lazyFn;
1133
+ exports.redirect = redirect;
1134
+ //# sourceMappingURL=router.js.map