@tanstack/router-core 0.0.1-beta.13 → 0.0.1-beta.145

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