@tanstack/router-core 0.0.1-beta.5 → 0.0.1-beta.50

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 (71) hide show
  1. package/LICENSE +21 -0
  2. package/build/cjs/actions.js +94 -0
  3. package/build/cjs/actions.js.map +1 -0
  4. package/build/cjs/history.js +163 -0
  5. package/build/cjs/history.js.map +1 -0
  6. package/build/cjs/{packages/router-core/src/index.js → index.js} +26 -11
  7. package/build/cjs/{packages/router-core/src/index.js.map → index.js.map} +1 -1
  8. package/build/cjs/interop.js +175 -0
  9. package/build/cjs/interop.js.map +1 -0
  10. package/build/cjs/{packages/router-core/src/path.js → path.js} +23 -48
  11. package/build/cjs/path.js.map +1 -0
  12. package/build/cjs/{packages/router-core/src/qss.js → qss.js} +8 -13
  13. package/build/cjs/qss.js.map +1 -0
  14. package/build/cjs/route.js +33 -0
  15. package/build/cjs/route.js.map +1 -0
  16. package/build/cjs/{packages/router-core/src/routeConfig.js → routeConfig.js} +13 -18
  17. package/build/cjs/routeConfig.js.map +1 -0
  18. package/build/cjs/routeMatch.js +237 -0
  19. package/build/cjs/routeMatch.js.map +1 -0
  20. package/build/cjs/router.js +821 -0
  21. package/build/cjs/router.js.map +1 -0
  22. package/build/cjs/{packages/router-core/src/searchParams.js → searchParams.js} +10 -12
  23. package/build/cjs/searchParams.js.map +1 -0
  24. package/build/cjs/store.js +54 -0
  25. package/build/cjs/store.js.map +1 -0
  26. package/build/cjs/utils.js +47 -0
  27. package/build/cjs/utils.js.map +1 -0
  28. package/build/esm/index.js +1384 -2059
  29. package/build/esm/index.js.map +1 -1
  30. package/build/stats-html.html +59 -49
  31. package/build/stats-react.json +248 -193
  32. package/build/types/index.d.ts +385 -317
  33. package/build/umd/index.development.js +1486 -2142
  34. package/build/umd/index.development.js.map +1 -1
  35. package/build/umd/index.production.js +1 -1
  36. package/build/umd/index.production.js.map +1 -1
  37. package/package.json +6 -4
  38. package/src/actions.ts +157 -0
  39. package/src/frameworks.ts +2 -2
  40. package/src/history.ts +199 -0
  41. package/src/index.ts +4 -7
  42. package/src/interop.ts +169 -0
  43. package/src/link.ts +87 -44
  44. package/src/path.ts +12 -8
  45. package/src/route.ts +36 -229
  46. package/src/routeConfig.ts +99 -102
  47. package/src/routeInfo.ts +28 -25
  48. package/src/routeMatch.ts +294 -322
  49. package/src/router.ts +1047 -884
  50. package/src/store.ts +52 -0
  51. package/src/utils.ts +14 -72
  52. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js +0 -33
  53. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js.map +0 -1
  54. package/build/cjs/node_modules/@babel/runtime/helpers/esm/extends.js +0 -33
  55. package/build/cjs/node_modules/@babel/runtime/helpers/esm/extends.js.map +0 -1
  56. package/build/cjs/node_modules/history/index.js +0 -815
  57. package/build/cjs/node_modules/history/index.js.map +0 -1
  58. package/build/cjs/node_modules/tiny-invariant/dist/esm/tiny-invariant.js +0 -30
  59. package/build/cjs/node_modules/tiny-invariant/dist/esm/tiny-invariant.js.map +0 -1
  60. package/build/cjs/packages/router-core/src/path.js.map +0 -1
  61. package/build/cjs/packages/router-core/src/qss.js.map +0 -1
  62. package/build/cjs/packages/router-core/src/route.js +0 -161
  63. package/build/cjs/packages/router-core/src/route.js.map +0 -1
  64. package/build/cjs/packages/router-core/src/routeConfig.js.map +0 -1
  65. package/build/cjs/packages/router-core/src/routeMatch.js +0 -266
  66. package/build/cjs/packages/router-core/src/routeMatch.js.map +0 -1
  67. package/build/cjs/packages/router-core/src/router.js +0 -797
  68. package/build/cjs/packages/router-core/src/router.js.map +0 -1
  69. package/build/cjs/packages/router-core/src/searchParams.js.map +0 -1
  70. package/build/cjs/packages/router-core/src/utils.js +0 -118
  71. package/build/cjs/packages/router-core/src/utils.js.map +0 -1
@@ -0,0 +1,821 @@
1
+ /**
2
+ * router-core
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 invariant = require('tiny-invariant');
16
+ var path = require('./path.js');
17
+ var route = require('./route.js');
18
+ var routeMatch = require('./routeMatch.js');
19
+ var searchParams = require('./searchParams.js');
20
+ var store = require('./store.js');
21
+ var utils = require('./utils.js');
22
+ var interop = require('./interop.js');
23
+ var history = require('./history.js');
24
+
25
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
26
+
27
+ var invariant__default = /*#__PURE__*/_interopDefaultLegacy(invariant);
28
+
29
+ const defaultFetchServerDataFn = async ({
30
+ router,
31
+ routeMatch
32
+ }) => {
33
+ const next = router.buildNext({
34
+ to: '.',
35
+ search: d => ({
36
+ ...(d ?? {}),
37
+ __data: {
38
+ matchId: routeMatch.id
39
+ }
40
+ })
41
+ });
42
+ const res = await fetch(next.href, {
43
+ method: 'GET',
44
+ signal: routeMatch.abortController.signal
45
+ });
46
+ if (res.ok) {
47
+ return res.json();
48
+ }
49
+ throw new Error('Failed to fetch match data');
50
+ };
51
+ class Router {
52
+ // __location: Location<TAllRouteInfo['fullSearchSchema']>
53
+
54
+ startedLoadingAt = Date.now();
55
+ resolveNavigation = () => {};
56
+ constructor(options) {
57
+ this.options = {
58
+ defaultLoaderGcMaxAge: 5 * 60 * 1000,
59
+ defaultLoaderMaxAge: 0,
60
+ defaultPreloadMaxAge: 2000,
61
+ defaultPreloadDelay: 50,
62
+ context: undefined,
63
+ ...options,
64
+ stringifySearch: options?.stringifySearch ?? searchParams.defaultStringifySearch,
65
+ parseSearch: options?.parseSearch ?? searchParams.defaultParseSearch,
66
+ fetchServerDataFn: options?.fetchServerDataFn ?? defaultFetchServerDataFn
67
+ };
68
+ this.history = this.options?.history ?? history.createBrowserHistory();
69
+ this.store = store.createStore(getInitialRouterState());
70
+ this.basepath = '';
71
+ this.update(options);
72
+
73
+ // Allow frameworks to hook into the router creation
74
+ this.options.createRouter?.(this);
75
+ }
76
+ reset = () => {
77
+ this.store.setState(s => Object.assign(s, getInitialRouterState()));
78
+ };
79
+ mount = () => {
80
+ // Mount only does anything on the client
81
+ if (!isServer) {
82
+ // If the router matches are empty, load the matches
83
+ if (!this.store.state.currentMatches.length) {
84
+ this.load();
85
+ }
86
+ const unsubHistory = this.history.listen(() => {
87
+ this.load(this.#parseLocation(this.store.state.latestLocation));
88
+ });
89
+ const visibilityChangeEvent = 'visibilitychange';
90
+ const focusEvent = 'focus';
91
+
92
+ // addEventListener does not exist in React Native, but window does
93
+ // In the future, we might need to invert control here for more adapters
94
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
95
+ if (window.addEventListener) {
96
+ // Listen to visibilitychange and focus
97
+ window.addEventListener(visibilityChangeEvent, this.#onFocus, false);
98
+ window.addEventListener(focusEvent, this.#onFocus, false);
99
+ }
100
+ return () => {
101
+ unsubHistory();
102
+ if (window.removeEventListener) {
103
+ // Be sure to unsubscribe if a new handler is set
104
+
105
+ window.removeEventListener(visibilityChangeEvent, this.#onFocus);
106
+ window.removeEventListener(focusEvent, this.#onFocus);
107
+ }
108
+ };
109
+ }
110
+ return () => {};
111
+ };
112
+ update = opts => {
113
+ if (!this.store.state.latestLocation) {
114
+ this.store.setState(s => {
115
+ s.latestLocation = this.#parseLocation();
116
+ s.currentLocation = s.latestLocation;
117
+ });
118
+ }
119
+ Object.assign(this.options, opts);
120
+ const {
121
+ basepath,
122
+ routeConfig
123
+ } = this.options;
124
+ this.basepath = `/${path.trimPath(basepath ?? '') ?? ''}`;
125
+ if (routeConfig) {
126
+ this.routesById = {};
127
+ this.routeTree = this.#buildRouteTree(routeConfig);
128
+ }
129
+ return this;
130
+ };
131
+ buildNext = opts => {
132
+ const next = this.#buildLocation(opts);
133
+ const matches = this.matchRoutes(next.pathname);
134
+ const __preSearchFilters = matches.map(match => match.route.options.preSearchFilters ?? []).flat().filter(Boolean);
135
+ const __postSearchFilters = matches.map(match => match.route.options.postSearchFilters ?? []).flat().filter(Boolean);
136
+ return this.#buildLocation({
137
+ ...opts,
138
+ __preSearchFilters,
139
+ __postSearchFilters
140
+ });
141
+ };
142
+ cancelMatches = () => {
143
+ [...this.store.state.currentMatches, ...(this.store.state.pendingMatches || [])].forEach(match => {
144
+ match.cancel();
145
+ });
146
+ };
147
+ load = async next => {
148
+ let now = Date.now();
149
+ const startedAt = now;
150
+ this.startedLoadingAt = startedAt;
151
+
152
+ // Cancel any pending matches
153
+ this.cancelMatches();
154
+ let matches;
155
+ store.batch(() => {
156
+ if (next) {
157
+ // Ingest the new location
158
+ this.store.setState(s => {
159
+ s.latestLocation = next;
160
+ });
161
+ }
162
+
163
+ // Match the routes
164
+ matches = this.matchRoutes(this.store.state.latestLocation.pathname, {
165
+ strictParseParams: true
166
+ });
167
+ this.store.setState(s => {
168
+ s.status = 'loading';
169
+ s.pendingMatches = matches;
170
+ s.pendingLocation = this.store.state.latestLocation;
171
+ });
172
+ });
173
+
174
+ // Load the matches
175
+ try {
176
+ await this.loadMatches(matches);
177
+ } catch (err) {
178
+ console.warn(err);
179
+ invariant__default["default"](false, 'Matches failed to load due to error above ☝️. Navigation cancelled!');
180
+ }
181
+ if (this.startedLoadingAt !== startedAt) {
182
+ // Ignore side-effects of outdated side-effects
183
+ return this.navigationPromise;
184
+ }
185
+ const previousMatches = this.store.state.currentMatches;
186
+ const exiting = [],
187
+ staying = [];
188
+ previousMatches.forEach(d => {
189
+ if (matches.find(dd => dd.id === d.id)) {
190
+ staying.push(d);
191
+ } else {
192
+ exiting.push(d);
193
+ }
194
+ });
195
+ const entering = matches.filter(d => {
196
+ return !previousMatches.find(dd => dd.id === d.id);
197
+ });
198
+ now = Date.now();
199
+ exiting.forEach(d => {
200
+ d.__onExit?.({
201
+ params: d.params,
202
+ search: d.store.state.routeSearch
203
+ });
204
+
205
+ // Clear non-loading error states when match leaves
206
+ if (d.store.state.status === 'error' && !d.store.state.isFetching) {
207
+ d.store.setState(s => {
208
+ s.status = 'idle';
209
+ s.error = undefined;
210
+ });
211
+ }
212
+ const gc = Math.max(d.route.options.loaderGcMaxAge ?? this.options.defaultLoaderGcMaxAge ?? 0, d.route.options.loaderMaxAge ?? this.options.defaultLoaderMaxAge ?? 0);
213
+ if (gc > 0) {
214
+ this.store.setState(s => {
215
+ s.matchCache[d.id] = {
216
+ gc: gc == Infinity ? Number.MAX_SAFE_INTEGER : now + gc,
217
+ match: d
218
+ };
219
+ });
220
+ }
221
+ });
222
+ staying.forEach(d => {
223
+ d.route.options.onTransition?.({
224
+ params: d.params,
225
+ search: d.store.state.routeSearch
226
+ });
227
+ });
228
+ entering.forEach(d => {
229
+ d.__onExit = d.route.options.onLoaded?.({
230
+ params: d.params,
231
+ search: d.store.state.search
232
+ });
233
+ delete this.store.state.matchCache[d.id];
234
+ });
235
+ this.store.setState(s => {
236
+ Object.assign(s, {
237
+ status: 'idle',
238
+ currentLocation: this.store.state.latestLocation,
239
+ currentMatches: matches,
240
+ pendingLocation: undefined,
241
+ pendingMatches: undefined
242
+ });
243
+ });
244
+ this.options.onRouteChange?.();
245
+ this.resolveNavigation();
246
+ };
247
+ cleanMatchCache = () => {
248
+ const now = Date.now();
249
+ this.store.setState(s => {
250
+ Object.keys(s.matchCache).forEach(matchId => {
251
+ const entry = s.matchCache[matchId];
252
+
253
+ // Don't remove loading matches
254
+ if (entry.match.store.state.status === 'loading') {
255
+ return;
256
+ }
257
+
258
+ // Do not remove successful matches that are still valid
259
+ if (entry.gc > 0 && entry.gc > now) {
260
+ return;
261
+ }
262
+
263
+ // Everything else gets removed
264
+ delete s.matchCache[matchId];
265
+ });
266
+ });
267
+ };
268
+ getRoute = id => {
269
+ const route = this.routesById[id];
270
+ invariant__default["default"](route, `Route with id "${id}" not found`);
271
+ return route;
272
+ };
273
+ loadRoute = async (navigateOpts = this.store.state.latestLocation) => {
274
+ const next = this.buildNext(navigateOpts);
275
+ const matches = this.matchRoutes(next.pathname, {
276
+ strictParseParams: true
277
+ });
278
+ await this.loadMatches(matches);
279
+ return matches;
280
+ };
281
+ preloadRoute = async (navigateOpts = this.store.state.latestLocation, loaderOpts) => {
282
+ const next = this.buildNext(navigateOpts);
283
+ const matches = this.matchRoutes(next.pathname, {
284
+ strictParseParams: true
285
+ });
286
+ await this.loadMatches(matches, {
287
+ preload: true,
288
+ maxAge: loaderOpts.maxAge ?? this.options.defaultPreloadMaxAge ?? this.options.defaultLoaderMaxAge ?? 0,
289
+ gcMaxAge: loaderOpts.gcMaxAge ?? this.options.defaultPreloadGcMaxAge ?? this.options.defaultLoaderGcMaxAge ?? 0
290
+ });
291
+ return matches;
292
+ };
293
+ matchRoutes = (pathname, opts) => {
294
+ const matches = [];
295
+ if (!this.routeTree) {
296
+ return matches;
297
+ }
298
+ const existingMatches = [...this.store.state.currentMatches, ...(this.store.state.pendingMatches ?? [])];
299
+ const recurse = async routes => {
300
+ const parentMatch = utils.last(matches);
301
+ let params = parentMatch?.params ?? {};
302
+ const filteredRoutes = this.options.filterRoutes?.(routes) ?? routes;
303
+ let foundRoutes = [];
304
+ const findMatchInRoutes = (parentRoutes, routes) => {
305
+ routes.some(route => {
306
+ if (!route.path && route.childRoutes?.length) {
307
+ return findMatchInRoutes([...foundRoutes, route], route.childRoutes);
308
+ }
309
+ const fuzzy = !!(route.path !== '/' || route.childRoutes?.length);
310
+ const matchParams = path.matchPathname(this.basepath, pathname, {
311
+ to: route.fullPath,
312
+ fuzzy,
313
+ caseSensitive: route.options.caseSensitive ?? this.options.caseSensitive
314
+ });
315
+ if (matchParams) {
316
+ let parsedParams;
317
+ try {
318
+ parsedParams = route.options.parseParams?.(matchParams) ?? matchParams;
319
+ } catch (err) {
320
+ if (opts?.strictParseParams) {
321
+ throw err;
322
+ }
323
+ }
324
+ params = {
325
+ ...params,
326
+ ...parsedParams
327
+ };
328
+ }
329
+ if (!!matchParams) {
330
+ foundRoutes = [...parentRoutes, route];
331
+ }
332
+ return !!foundRoutes.length;
333
+ });
334
+ return !!foundRoutes.length;
335
+ };
336
+ findMatchInRoutes([], filteredRoutes);
337
+ if (!foundRoutes.length) {
338
+ return;
339
+ }
340
+ foundRoutes.forEach(foundRoute => {
341
+ const interpolatedPath = path.interpolatePath(foundRoute.path, params);
342
+ const matchId = path.interpolatePath(foundRoute.id, params, true);
343
+ const match = existingMatches.find(d => d.id === matchId) || this.store.state.matchCache[matchId]?.match || new routeMatch.RouteMatch(this, foundRoute, {
344
+ matchId,
345
+ params,
346
+ pathname: path.joinPaths([this.basepath, interpolatedPath])
347
+ });
348
+ matches.push(match);
349
+ });
350
+ const foundRoute = utils.last(foundRoutes);
351
+ if (foundRoute.childRoutes?.length) {
352
+ recurse(foundRoute.childRoutes);
353
+ }
354
+ };
355
+ recurse([this.routeTree]);
356
+ linkMatches(matches);
357
+ return matches;
358
+ };
359
+ loadMatches = async (resolvedMatches, loaderOpts) => {
360
+ this.cleanMatchCache();
361
+ resolvedMatches.forEach(async match => {
362
+ // Validate the match (loads search params etc)
363
+ match.__validate();
364
+ });
365
+
366
+ // Check each match middleware to see if the route can be accessed
367
+ await Promise.all(resolvedMatches.map(async match => {
368
+ try {
369
+ await match.route.options.beforeLoad?.({
370
+ router: this,
371
+ match
372
+ });
373
+ } catch (err) {
374
+ if (!loaderOpts?.preload) {
375
+ match.route.options.onLoadError?.(err);
376
+ }
377
+ throw err;
378
+ }
379
+ }));
380
+ const matchPromises = resolvedMatches.map(async (match, index) => {
381
+ const prevMatch = resolvedMatches[1];
382
+ const search = match.store.state.search;
383
+ if (search.__data?.matchId && search.__data.matchId !== match.id) {
384
+ return;
385
+ }
386
+ match.load(loaderOpts);
387
+ if (match.store.state.status !== 'success' && match.__loadPromise) {
388
+ // Wait for the first sign of activity from the match
389
+ await match.__loadPromise;
390
+ }
391
+ if (prevMatch) {
392
+ await prevMatch.__loadPromise;
393
+ }
394
+ });
395
+ await Promise.all(matchPromises);
396
+ };
397
+ loadMatchData = async routeMatch => {
398
+ if (isServer || !this.options.useServerData) {
399
+ return (await routeMatch.route.options.loader?.({
400
+ // parentLoaderPromise: routeMatch.parentMatch.dataPromise,
401
+ params: routeMatch.params,
402
+ search: routeMatch.store.state.routeSearch,
403
+ signal: routeMatch.abortController.signal
404
+ })) || {};
405
+ } else {
406
+ // Refresh:
407
+ // '/dashboard'
408
+ // '/dashboard/invoices/'
409
+ // '/dashboard/invoices/123'
410
+
411
+ // New:
412
+ // '/dashboard/invoices/456'
413
+
414
+ // TODO: batch requests when possible
415
+
416
+ return this.options.fetchServerDataFn({
417
+ router: this,
418
+ routeMatch
419
+ });
420
+ }
421
+ };
422
+ invalidateRoute = async opts => {
423
+ const next = this.buildNext(opts);
424
+ const unloadedMatchIds = this.matchRoutes(next.pathname).map(d => d.id);
425
+ await Promise.allSettled([...this.store.state.currentMatches, ...(this.store.state.pendingMatches ?? [])].map(async match => {
426
+ if (unloadedMatchIds.includes(match.id)) {
427
+ return match.invalidate();
428
+ }
429
+ }));
430
+ };
431
+ reload = () => {
432
+ this.navigate({
433
+ fromCurrent: true,
434
+ replace: true,
435
+ search: true
436
+ });
437
+ };
438
+ resolvePath = (from, path$1) => {
439
+ return path.resolvePath(this.basepath, from, path.cleanPath(path$1));
440
+ };
441
+ navigate = async ({
442
+ from,
443
+ to = '.',
444
+ search,
445
+ hash,
446
+ replace,
447
+ params
448
+ }) => {
449
+ // If this link simply reloads the current route,
450
+ // make sure it has a new key so it will trigger a data refresh
451
+
452
+ // If this `to` is a valid external URL, return
453
+ // null for LinkUtils
454
+ const toString = String(to);
455
+ const fromString = String(from);
456
+ let isExternal;
457
+ try {
458
+ new URL(`${toString}`);
459
+ isExternal = true;
460
+ } catch (e) {}
461
+ invariant__default["default"](!isExternal, 'Attempting to navigate to external url with this.navigate!');
462
+ return this.#commitLocation({
463
+ from: fromString,
464
+ to: toString,
465
+ search,
466
+ hash,
467
+ replace,
468
+ params
469
+ });
470
+ };
471
+ matchRoute = (location, opts) => {
472
+ location = {
473
+ ...location,
474
+ to: location.to ? this.resolvePath(location.from ?? '', location.to) : undefined
475
+ };
476
+ const next = this.buildNext(location);
477
+ if (opts?.pending) {
478
+ if (!this.store.state.pendingLocation) {
479
+ return false;
480
+ }
481
+ return path.matchPathname(this.basepath, this.store.state.pendingLocation.pathname, {
482
+ ...opts,
483
+ to: next.pathname
484
+ });
485
+ }
486
+ return path.matchPathname(this.basepath, this.store.state.currentLocation.pathname, {
487
+ ...opts,
488
+ to: next.pathname
489
+ });
490
+ };
491
+ buildLink = ({
492
+ from,
493
+ to = '.',
494
+ search,
495
+ params,
496
+ hash,
497
+ target,
498
+ replace,
499
+ activeOptions,
500
+ preload,
501
+ preloadMaxAge: userPreloadMaxAge,
502
+ preloadGcMaxAge: userPreloadGcMaxAge,
503
+ preloadDelay: userPreloadDelay,
504
+ disabled
505
+ }) => {
506
+ // If this link simply reloads the current route,
507
+ // make sure it has a new key so it will trigger a data refresh
508
+
509
+ // If this `to` is a valid external URL, return
510
+ // null for LinkUtils
511
+
512
+ try {
513
+ new URL(`${to}`);
514
+ return {
515
+ type: 'external',
516
+ href: to
517
+ };
518
+ } catch (e) {}
519
+ const nextOpts = {
520
+ from,
521
+ to,
522
+ search,
523
+ params,
524
+ hash,
525
+ replace
526
+ };
527
+ const next = this.buildNext(nextOpts);
528
+ preload = preload ?? this.options.defaultPreload;
529
+ const preloadDelay = userPreloadDelay ?? this.options.defaultPreloadDelay ?? 0;
530
+
531
+ // Compare path/hash for matches
532
+ const pathIsEqual = this.store.state.currentLocation.pathname === next.pathname;
533
+ const currentPathSplit = this.store.state.currentLocation.pathname.split('/');
534
+ const nextPathSplit = next.pathname.split('/');
535
+ const pathIsFuzzyEqual = nextPathSplit.every((d, i) => d === currentPathSplit[i]);
536
+ const hashIsEqual = this.store.state.currentLocation.hash === next.hash;
537
+ // Combine the matches based on user options
538
+ const pathTest = activeOptions?.exact ? pathIsEqual : pathIsFuzzyEqual;
539
+ const hashTest = activeOptions?.includeHash ? hashIsEqual : true;
540
+
541
+ // The final "active" test
542
+ const isActive = pathTest && hashTest;
543
+
544
+ // The click handler
545
+ const handleClick = e => {
546
+ if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!target || target === '_self') && e.button === 0) {
547
+ e.preventDefault();
548
+ if (pathIsEqual && !search && !hash) {
549
+ this.invalidateRoute(nextOpts);
550
+ }
551
+
552
+ // All is well? Navigate!
553
+ this.#commitLocation(nextOpts);
554
+ }
555
+ };
556
+
557
+ // The click handler
558
+ const handleFocus = e => {
559
+ if (preload) {
560
+ this.preloadRoute(nextOpts, {
561
+ maxAge: userPreloadMaxAge,
562
+ gcMaxAge: userPreloadGcMaxAge
563
+ }).catch(err => {
564
+ console.warn(err);
565
+ console.warn('Error preloading route! ☝️');
566
+ });
567
+ }
568
+ };
569
+ const handleEnter = e => {
570
+ const target = e.target || {};
571
+ if (preload) {
572
+ if (target.preloadTimeout) {
573
+ return;
574
+ }
575
+ target.preloadTimeout = setTimeout(() => {
576
+ target.preloadTimeout = null;
577
+ this.preloadRoute(nextOpts, {
578
+ maxAge: userPreloadMaxAge,
579
+ gcMaxAge: userPreloadGcMaxAge
580
+ }).catch(err => {
581
+ console.warn(err);
582
+ console.warn('Error preloading route! ☝️');
583
+ });
584
+ }, preloadDelay);
585
+ }
586
+ };
587
+ const handleLeave = e => {
588
+ const target = e.target || {};
589
+ if (target.preloadTimeout) {
590
+ clearTimeout(target.preloadTimeout);
591
+ target.preloadTimeout = null;
592
+ }
593
+ };
594
+ return {
595
+ type: 'internal',
596
+ next,
597
+ handleFocus,
598
+ handleClick,
599
+ handleEnter,
600
+ handleLeave,
601
+ isActive,
602
+ disabled
603
+ };
604
+ };
605
+ dehydrate = () => {
606
+ return {
607
+ state: {
608
+ ...utils.pick(this.store.state, ['latestLocation', 'currentLocation', 'status', 'lastUpdated']),
609
+ currentMatches: this.store.state.currentMatches.map(match => ({
610
+ matchId: match.id,
611
+ state: {
612
+ ...utils.pick(match.store.state, ['status', 'routeLoaderData', 'invalidAt', 'invalid'])
613
+ }
614
+ }))
615
+ },
616
+ context: this.options.context
617
+ };
618
+ };
619
+ hydrate = dehydratedRouter => {
620
+ this.store.setState(s => {
621
+ // Update the context TODO: make this part of state?
622
+ this.options.context = dehydratedRouter.context;
623
+
624
+ // Match the routes
625
+ const currentMatches = this.matchRoutes(dehydratedRouter.state.latestLocation.pathname, {
626
+ strictParseParams: true
627
+ });
628
+ currentMatches.forEach((match, index) => {
629
+ const dehydratedMatch = dehydratedRouter.state.currentMatches[index];
630
+ invariant__default["default"](dehydratedMatch && dehydratedMatch.matchId === match.id, 'Oh no! There was a hydration mismatch when attempting to rethis.store the state of the router! 😬');
631
+ Object.assign(match, dehydratedMatch);
632
+ });
633
+ currentMatches.forEach(match => match.__validate());
634
+ Object.assign(s, {
635
+ ...dehydratedRouter.state,
636
+ currentMatches
637
+ });
638
+ });
639
+ };
640
+ getLoader = opts => {
641
+ const id = opts.from || '/';
642
+ const route = this.getRoute(id);
643
+ if (!route) return undefined;
644
+ let loader = this.store.state.loaders[id] || (() => {
645
+ this.store.setState(s => {
646
+ s.loaders[id] = {
647
+ pending: [],
648
+ fetch: async loaderContext => {
649
+ if (!route) {
650
+ return;
651
+ }
652
+ const loaderState = {
653
+ loadedAt: Date.now(),
654
+ loaderContext
655
+ };
656
+ this.store.setState(s => {
657
+ s.loaders[id].current = loaderState;
658
+ s.loaders[id].latest = loaderState;
659
+ s.loaders[id].pending.push(loaderState);
660
+ });
661
+ try {
662
+ return await route.options.loader?.(loaderContext);
663
+ } finally {
664
+ this.store.setState(s => {
665
+ s.loaders[id].pending = s.loaders[id].pending.filter(d => d !== loaderState);
666
+ });
667
+ }
668
+ }
669
+ };
670
+ });
671
+ return this.store.state.loaders[id];
672
+ })();
673
+ return loader;
674
+ };
675
+ #buildRouteTree = rootRouteConfig => {
676
+ const recurseRoutes = (routeConfigs, parent) => {
677
+ return routeConfigs.map((routeConfig, i) => {
678
+ const routeOptions = routeConfig.options;
679
+ const route$1 = new route.Route(routeConfig, routeOptions, i, parent, this);
680
+ const existingRoute = this.routesById[route$1.id];
681
+ if (existingRoute) {
682
+ if (process.env.NODE_ENV !== 'production') {
683
+ console.warn(`Duplicate routes found with id: ${String(route$1.id)}`, this.routesById, route$1);
684
+ }
685
+ throw new Error();
686
+ }
687
+ this.routesById[route$1.id] = route$1;
688
+ const children = routeConfig.children;
689
+ route$1.childRoutes = children.length ? recurseRoutes(children, route$1) : undefined;
690
+ return route$1;
691
+ });
692
+ };
693
+ const routes = recurseRoutes([rootRouteConfig]);
694
+ return routes[0];
695
+ };
696
+ #parseLocation = previousLocation => {
697
+ let {
698
+ pathname,
699
+ search,
700
+ hash,
701
+ state
702
+ } = this.history.location;
703
+ const parsedSearch = this.options.parseSearch(search);
704
+ return {
705
+ pathname: pathname,
706
+ searchStr: search,
707
+ search: interop.replaceEqualDeep(previousLocation?.search, parsedSearch),
708
+ hash: hash.split('#').reverse()[0] ?? '',
709
+ href: `${pathname}${search}${hash}`,
710
+ state: state,
711
+ key: state?.key || '__init__'
712
+ };
713
+ };
714
+ #onFocus = () => {
715
+ this.load();
716
+ };
717
+ #buildLocation = (dest = {}) => {
718
+ const fromPathname = dest.fromCurrent ? this.store.state.latestLocation.pathname : dest.from ?? this.store.state.latestLocation.pathname;
719
+ let pathname = path.resolvePath(this.basepath ?? '/', fromPathname, `${dest.to ?? '.'}`);
720
+ const fromMatches = this.matchRoutes(this.store.state.latestLocation.pathname, {
721
+ strictParseParams: true
722
+ });
723
+ const toMatches = this.matchRoutes(pathname);
724
+ const prevParams = {
725
+ ...utils.last(fromMatches)?.params
726
+ };
727
+ let nextParams = (dest.params ?? true) === true ? prevParams : utils.functionalUpdate(dest.params, prevParams);
728
+ if (nextParams) {
729
+ toMatches.map(d => d.route.options.stringifyParams).filter(Boolean).forEach(fn => {
730
+ Object.assign({}, nextParams, fn(nextParams));
731
+ });
732
+ }
733
+ pathname = path.interpolatePath(pathname, nextParams ?? {});
734
+
735
+ // Pre filters first
736
+ const preFilteredSearch = dest.__preSearchFilters?.length ? dest.__preSearchFilters?.reduce((prev, next) => next(prev), this.store.state.latestLocation.search) : this.store.state.latestLocation.search;
737
+
738
+ // Then the link/navigate function
739
+ const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
740
+ : dest.search ? utils.functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater
741
+ : dest.__preSearchFilters?.length ? preFilteredSearch // Preserve resolvedFrom filters
742
+ : {};
743
+
744
+ // Then post filters
745
+ const postFilteredSearch = dest.__postSearchFilters?.length ? dest.__postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
746
+ const search = interop.replaceEqualDeep(this.store.state.latestLocation.search, postFilteredSearch);
747
+ const searchStr = this.options.stringifySearch(search);
748
+ let hash = dest.hash === true ? this.store.state.latestLocation.hash : utils.functionalUpdate(dest.hash, this.store.state.latestLocation.hash);
749
+ hash = hash ? `#${hash}` : '';
750
+ return {
751
+ pathname,
752
+ search,
753
+ searchStr,
754
+ state: this.store.state.latestLocation.state,
755
+ hash,
756
+ href: `${pathname}${searchStr}${hash}`,
757
+ key: dest.key
758
+ };
759
+ };
760
+ #commitLocation = location => {
761
+ const next = this.buildNext(location);
762
+ const id = '' + Date.now() + Math.random();
763
+ if (this.navigateTimeout) clearTimeout(this.navigateTimeout);
764
+ let nextAction = 'replace';
765
+ if (!location.replace) {
766
+ nextAction = 'push';
767
+ }
768
+ const isSameUrl = this.store.state.latestLocation.href === next.href;
769
+ if (isSameUrl && !next.key) {
770
+ nextAction = 'replace';
771
+ }
772
+ const href = `${next.pathname}${next.searchStr}${next.hash ? `#${next.hash}` : ''}`;
773
+ this.history[nextAction === 'push' ? 'push' : 'replace'](href, {
774
+ id,
775
+ ...next.state
776
+ });
777
+ this.load(this.#parseLocation(this.store.state.latestLocation));
778
+ return this.navigationPromise = new Promise(resolve => {
779
+ const previousNavigationResolve = this.resolveNavigation;
780
+ this.resolveNavigation = () => {
781
+ previousNavigationResolve();
782
+ resolve();
783
+ };
784
+ });
785
+ };
786
+ }
787
+
788
+ // Detect if we're in the DOM
789
+ const isServer = typeof window === 'undefined' || !window.document.createElement;
790
+ function getInitialRouterState() {
791
+ return {
792
+ status: 'idle',
793
+ latestLocation: null,
794
+ currentLocation: null,
795
+ currentMatches: [],
796
+ loaders: {},
797
+ lastUpdated: Date.now(),
798
+ matchCache: {},
799
+ get isFetching() {
800
+ return this.status === 'loading' || this.currentMatches.some(d => d.store.state.isFetching);
801
+ },
802
+ get isPreloading() {
803
+ return Object.values(this.matchCache).some(d => d.match.store.state.isFetching && !this.currentMatches.find(dd => dd.id === d.match.id));
804
+ }
805
+ };
806
+ }
807
+ function isCtrlEvent(e) {
808
+ return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
809
+ }
810
+ function linkMatches(matches) {
811
+ matches.forEach((match, index) => {
812
+ const parent = matches[index - 1];
813
+ if (parent) {
814
+ match.__setParentMatch(parent);
815
+ }
816
+ });
817
+ }
818
+
819
+ exports.Router = Router;
820
+ exports.defaultFetchServerDataFn = defaultFetchServerDataFn;
821
+ //# sourceMappingURL=router.js.map