@tanstack/react-router 0.0.1-beta.28 → 0.0.1-beta.281

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 (106) hide show
  1. package/LICENSE +21 -0
  2. package/build/cjs/CatchBoundary.js +128 -0
  3. package/build/cjs/CatchBoundary.js.map +1 -0
  4. package/build/cjs/Matches.js +233 -0
  5. package/build/cjs/Matches.js.map +1 -0
  6. package/build/cjs/RouterProvider.js +170 -0
  7. package/build/cjs/RouterProvider.js.map +1 -0
  8. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js +2 -22
  9. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js.map +1 -1
  10. package/build/cjs/awaited.js +43 -0
  11. package/build/cjs/awaited.js.map +1 -0
  12. package/build/cjs/defer.js +37 -0
  13. package/build/cjs/defer.js.map +1 -0
  14. package/build/cjs/fileRoute.js +27 -0
  15. package/build/cjs/fileRoute.js.map +1 -0
  16. package/build/cjs/index.js +130 -0
  17. package/build/cjs/index.js.map +1 -0
  18. package/build/cjs/lazyRouteComponent.js +54 -0
  19. package/build/cjs/lazyRouteComponent.js.map +1 -0
  20. package/build/cjs/link.js +223 -0
  21. package/build/cjs/link.js.map +1 -0
  22. package/build/cjs/path.js +214 -0
  23. package/build/cjs/path.js.map +1 -0
  24. package/build/cjs/qss.js +63 -0
  25. package/build/cjs/qss.js.map +1 -0
  26. package/build/cjs/redirects.js +28 -0
  27. package/build/cjs/redirects.js.map +1 -0
  28. package/build/cjs/route.js +191 -0
  29. package/build/cjs/route.js.map +1 -0
  30. package/build/cjs/router.js +1067 -0
  31. package/build/cjs/router.js.map +1 -0
  32. package/build/cjs/scroll-restoration.js +202 -0
  33. package/build/cjs/scroll-restoration.js.map +1 -0
  34. package/build/cjs/searchParams.js +81 -0
  35. package/build/cjs/searchParams.js.map +1 -0
  36. package/build/cjs/useBlocker.js +55 -0
  37. package/build/cjs/useBlocker.js.map +1 -0
  38. package/build/cjs/useNavigate.js +86 -0
  39. package/build/cjs/useNavigate.js.map +1 -0
  40. package/build/cjs/useParams.js +26 -0
  41. package/build/cjs/useParams.js.map +1 -0
  42. package/build/cjs/useSearch.js +25 -0
  43. package/build/cjs/useSearch.js.map +1 -0
  44. package/build/cjs/utils.js +239 -0
  45. package/build/cjs/utils.js.map +1 -0
  46. package/build/esm/index.js +2282 -2580
  47. package/build/esm/index.js.map +1 -1
  48. package/build/stats-html.html +3498 -2694
  49. package/build/stats-react.json +1204 -44
  50. package/build/types/CatchBoundary.d.ts +36 -0
  51. package/build/types/Matches.d.ts +63 -0
  52. package/build/types/RouterProvider.d.ts +35 -0
  53. package/build/types/awaited.d.ts +9 -0
  54. package/build/types/defer.d.ts +19 -0
  55. package/build/types/fileRoute.d.ts +38 -0
  56. package/build/types/history.d.ts +7 -0
  57. package/build/types/index.d.ts +27 -114
  58. package/build/types/lazyRouteComponent.d.ts +2 -0
  59. package/build/types/link.d.ts +91 -0
  60. package/build/types/location.d.ts +12 -0
  61. package/build/types/path.d.ts +17 -0
  62. package/build/types/qss.d.ts +2 -0
  63. package/build/types/redirects.d.ts +11 -0
  64. package/build/types/route.d.ts +283 -0
  65. package/build/types/routeInfo.d.ts +22 -0
  66. package/build/types/router.d.ts +185 -0
  67. package/build/types/scroll-restoration.d.ts +18 -0
  68. package/build/types/searchParams.d.ts +7 -0
  69. package/build/types/useBlocker.d.ts +9 -0
  70. package/build/types/useNavigate.d.ts +19 -0
  71. package/build/types/useParams.d.ts +7 -0
  72. package/build/types/useSearch.d.ts +7 -0
  73. package/build/types/utils.d.ts +66 -0
  74. package/build/umd/index.development.js +2873 -2545
  75. package/build/umd/index.development.js.map +1 -1
  76. package/build/umd/index.production.js +4 -4
  77. package/build/umd/index.production.js.map +1 -1
  78. package/package.json +11 -10
  79. package/src/CatchBoundary.tsx +101 -0
  80. package/src/Matches.tsx +422 -0
  81. package/src/RouterProvider.tsx +252 -0
  82. package/src/awaited.tsx +40 -0
  83. package/src/defer.ts +55 -0
  84. package/src/fileRoute.ts +152 -0
  85. package/src/history.ts +8 -0
  86. package/src/index.tsx +28 -761
  87. package/src/lazyRouteComponent.tsx +33 -0
  88. package/src/link.tsx +598 -0
  89. package/src/location.ts +13 -0
  90. package/src/path.ts +261 -0
  91. package/src/qss.ts +53 -0
  92. package/src/redirects.ts +39 -0
  93. package/src/route.ts +882 -0
  94. package/src/routeInfo.ts +70 -0
  95. package/src/router.ts +1651 -0
  96. package/src/scroll-restoration.tsx +230 -0
  97. package/src/searchParams.ts +79 -0
  98. package/src/useBlocker.tsx +27 -0
  99. package/src/useNavigate.tsx +111 -0
  100. package/src/useParams.tsx +25 -0
  101. package/src/useSearch.tsx +25 -0
  102. package/src/utils.ts +350 -0
  103. package/build/cjs/react-router/src/index.js +0 -508
  104. package/build/cjs/react-router/src/index.js.map +0 -1
  105. package/build/cjs/router-core/build/esm/index.js +0 -2530
  106. package/build/cjs/router-core/build/esm/index.js.map +0 -1
package/src/router.ts ADDED
@@ -0,0 +1,1651 @@
1
+ import {
2
+ HistoryLocation,
3
+ HistoryState,
4
+ RouterHistory,
5
+ createBrowserHistory,
6
+ createMemoryHistory,
7
+ } from '@tanstack/history'
8
+ import { Store } from '@tanstack/store'
9
+
10
+ //
11
+
12
+ import {
13
+ AnySearchSchema,
14
+ AnyRoute,
15
+ AnyContext,
16
+ AnyPathParams,
17
+ RouteMask,
18
+ Route,
19
+ LoaderFnContext,
20
+ } from './route'
21
+ import { FullSearchSchema, RoutesById, RoutesByPath } from './routeInfo'
22
+ import { defaultParseSearch, defaultStringifySearch } from './searchParams'
23
+ import {
24
+ PickAsRequired,
25
+ Updater,
26
+ NonNullableUpdater,
27
+ replaceEqualDeep,
28
+ deepEqual,
29
+ escapeJSON,
30
+ functionalUpdate,
31
+ last,
32
+ pick,
33
+ Timeout,
34
+ } from './utils'
35
+ import { RouteComponent } from './route'
36
+ import { AnyRouteMatch, RouteMatch } from './Matches'
37
+ import { ParsedLocation } from './location'
38
+ import { SearchSerializer, SearchParser } from './searchParams'
39
+ import {
40
+ BuildLocationFn,
41
+ CommitLocationOptions,
42
+ InjectedHtmlEntry,
43
+ MatchRouteFn,
44
+ NavigateFn,
45
+ getRouteMatch,
46
+ } from './RouterProvider'
47
+
48
+ import {
49
+ cleanPath,
50
+ interpolatePath,
51
+ joinPaths,
52
+ matchPathname,
53
+ parsePathname,
54
+ removeBasepath,
55
+ resolvePath,
56
+ trimPath,
57
+ trimPathLeft,
58
+ trimPathRight,
59
+ } from './path'
60
+ import invariant from 'tiny-invariant'
61
+ import { isRedirect } from './redirects'
62
+ import { ToOptions } from './link'
63
+ // import warning from 'tiny-warning'
64
+
65
+ //
66
+
67
+ declare global {
68
+ interface Window {
69
+ __TSR_DEHYDRATED__?: HydrationCtx
70
+ __TSR_ROUTER_CONTEXT__?: React.Context<Router<any>>
71
+ }
72
+ }
73
+
74
+ export interface Register {
75
+ // router: Router
76
+ }
77
+
78
+ export type AnyRouter = Router<AnyRoute, any>
79
+
80
+ export type RegisteredRouter = Register extends {
81
+ router: infer TRouter extends AnyRouter
82
+ }
83
+ ? TRouter
84
+ : AnyRouter
85
+
86
+ export type HydrationCtx = {
87
+ router: DehydratedRouter
88
+ payload: Record<string, any>
89
+ }
90
+
91
+ export type RouterContextOptions<TRouteTree extends AnyRoute> =
92
+ AnyContext extends TRouteTree['types']['routerContext']
93
+ ? {
94
+ context?: TRouteTree['types']['routerContext']
95
+ }
96
+ : {
97
+ context: TRouteTree['types']['routerContext']
98
+ }
99
+
100
+ export interface RouterOptions<
101
+ TRouteTree extends AnyRoute,
102
+ TDehydrated extends Record<string, any> = Record<string, any>,
103
+ > {
104
+ history?: RouterHistory
105
+ stringifySearch?: SearchSerializer
106
+ parseSearch?: SearchParser
107
+ defaultPreload?: false | 'intent'
108
+ defaultPreloadDelay?: number
109
+ defaultComponent?: RouteComponent
110
+ defaultErrorComponent?: RouteComponent
111
+ defaultPendingComponent?: RouteComponent
112
+ defaultPendingMs?: number
113
+ defaultPendingMinMs?: number
114
+ defaultStaleTime?: number
115
+ defaultPreloadStaleTime?: number
116
+ defaultPreloadGcTime?: number
117
+ defaultGcTime?: number
118
+ caseSensitive?: boolean
119
+ routeTree?: TRouteTree
120
+ basepath?: string
121
+ context?: TRouteTree['types']['routerContext']
122
+ dehydrate?: () => TDehydrated
123
+ hydrate?: (dehydrated: TDehydrated) => void
124
+ routeMasks?: RouteMask<TRouteTree>[]
125
+ unmaskOnReload?: boolean
126
+ Wrap?: (props: { children: any }) => JSX.Element
127
+ InnerWrap?: (props: { children: any }) => JSX.Element
128
+ notFoundRoute?: AnyRoute
129
+ }
130
+
131
+ export interface RouterState<TRouteTree extends AnyRoute = AnyRoute> {
132
+ status: 'pending' | 'idle'
133
+ isLoading: boolean
134
+ isTransitioning: boolean
135
+ matches: RouteMatch<TRouteTree>[]
136
+ pendingMatches?: RouteMatch<TRouteTree>[]
137
+ cachedMatches: RouteMatch<TRouteTree>[]
138
+ location: ParsedLocation<FullSearchSchema<TRouteTree>>
139
+ resolvedLocation: ParsedLocation<FullSearchSchema<TRouteTree>>
140
+ lastUpdated: number
141
+ }
142
+
143
+ export type ListenerFn<TEvent extends RouterEvent> = (event: TEvent) => void
144
+
145
+ export interface BuildNextOptions {
146
+ to?: string | number | null
147
+ params?: true | Updater<unknown>
148
+ search?: true | Updater<unknown>
149
+ hash?: true | Updater<string>
150
+ state?: true | NonNullableUpdater<HistoryState>
151
+ mask?: {
152
+ to?: string | number | null
153
+ params?: true | Updater<unknown>
154
+ search?: true | Updater<unknown>
155
+ hash?: true | Updater<string>
156
+ state?: true | NonNullableUpdater<HistoryState>
157
+ unmaskOnReload?: boolean
158
+ }
159
+ from?: string
160
+ }
161
+
162
+ export interface DehydratedRouterState {
163
+ dehydratedMatches: DehydratedRouteMatch[]
164
+ }
165
+
166
+ export type DehydratedRouteMatch = Pick<
167
+ RouteMatch,
168
+ 'id' | 'status' | 'updatedAt'
169
+ >
170
+
171
+ export interface DehydratedRouter {
172
+ state: DehydratedRouterState
173
+ }
174
+
175
+ export type RouterConstructorOptions<
176
+ TRouteTree extends AnyRoute,
177
+ TDehydrated extends Record<string, any>,
178
+ > = Omit<RouterOptions<TRouteTree, TDehydrated>, 'context'> &
179
+ RouterContextOptions<TRouteTree>
180
+
181
+ export const componentTypes = [
182
+ 'component',
183
+ 'errorComponent',
184
+ 'pendingComponent',
185
+ ] as const
186
+
187
+ export type RouterEvents = {
188
+ onBeforeLoad: {
189
+ type: 'onBeforeLoad'
190
+ fromLocation: ParsedLocation
191
+ toLocation: ParsedLocation
192
+ pathChanged: boolean
193
+ }
194
+ onLoad: {
195
+ type: 'onLoad'
196
+ fromLocation: ParsedLocation
197
+ toLocation: ParsedLocation
198
+ pathChanged: boolean
199
+ }
200
+ onResolved: {
201
+ type: 'onResolved'
202
+ fromLocation: ParsedLocation
203
+ toLocation: ParsedLocation
204
+ pathChanged: boolean
205
+ }
206
+ }
207
+
208
+ export type RouterEvent = RouterEvents[keyof RouterEvents]
209
+
210
+ export type RouterListener<TRouterEvent extends RouterEvent> = {
211
+ eventType: TRouterEvent['type']
212
+ fn: ListenerFn<TRouterEvent>
213
+ }
214
+
215
+ export class Router<
216
+ TRouteTree extends AnyRoute = AnyRoute,
217
+ TDehydrated extends Record<string, any> = Record<string, any>,
218
+ > {
219
+ // Option-independent properties
220
+ tempLocationKey: string | undefined = `${Math.round(
221
+ Math.random() * 10000000,
222
+ )}`
223
+ resetNextScroll: boolean = true
224
+ navigateTimeout: Timeout | null = null
225
+ latestLoadPromise: Promise<void> = Promise.resolve()
226
+ subscribers = new Set<RouterListener<RouterEvent>>()
227
+ injectedHtml: InjectedHtmlEntry[] = []
228
+ dehydratedData?: TDehydrated
229
+
230
+ // Must build in constructor
231
+ __store!: Store<RouterState<TRouteTree>>
232
+ options!: PickAsRequired<
233
+ RouterOptions<TRouteTree, TDehydrated>,
234
+ 'stringifySearch' | 'parseSearch' | 'context'
235
+ >
236
+ history!: RouterHistory
237
+ latestLocation!: ParsedLocation
238
+ basepath!: string
239
+ routeTree!: TRouteTree
240
+ routesById!: RoutesById<TRouteTree>
241
+ routesByPath!: RoutesByPath<TRouteTree>
242
+ flatRoutes!: AnyRoute[]
243
+
244
+ constructor(options: RouterConstructorOptions<TRouteTree, TDehydrated>) {
245
+ this.update({
246
+ defaultPreloadDelay: 50,
247
+ defaultPendingMs: 1000,
248
+ defaultPendingMinMs: 500,
249
+ context: undefined!,
250
+ ...options,
251
+ stringifySearch: options?.stringifySearch ?? defaultStringifySearch,
252
+ parseSearch: options?.parseSearch ?? defaultParseSearch,
253
+ })
254
+ }
255
+
256
+ // These are default implementations that can optionally be overridden
257
+ // by the router provider once rendered. We provide these so that the
258
+ // router can be used in a non-react environment if necessary
259
+ startReactTransition: (fn: () => void) => void = (fn) => fn()
260
+
261
+ update = (newOptions: RouterConstructorOptions<TRouteTree, TDehydrated>) => {
262
+ this.options = {
263
+ ...this.options,
264
+ ...newOptions,
265
+ }
266
+
267
+ this.basepath = `/${trimPath(newOptions.basepath ?? '') ?? ''}`
268
+
269
+ if (
270
+ !this.history ||
271
+ (this.options.history && this.options.history !== this.history)
272
+ ) {
273
+ this.history =
274
+ this.options.history ??
275
+ (typeof document !== 'undefined'
276
+ ? createBrowserHistory()
277
+ : createMemoryHistory())
278
+ this.latestLocation = this.parseLocation()
279
+ }
280
+
281
+ if (this.options.routeTree !== this.routeTree) {
282
+ this.routeTree = this.options.routeTree as TRouteTree
283
+ this.buildRouteTree()
284
+ }
285
+
286
+ if (!this.__store) {
287
+ this.__store = new Store(getInitialRouterState(this.latestLocation), {
288
+ onUpdate: () => {
289
+ this.__store.state = {
290
+ ...this.state,
291
+ status:
292
+ this.state.isTransitioning || this.state.isLoading
293
+ ? 'pending'
294
+ : 'idle',
295
+ }
296
+ },
297
+ })
298
+ }
299
+ }
300
+
301
+ get state() {
302
+ return this.__store.state
303
+ }
304
+
305
+ buildRouteTree = () => {
306
+ this.routesById = {} as RoutesById<TRouteTree>
307
+ this.routesByPath = {} as RoutesByPath<TRouteTree>
308
+
309
+ const notFoundRoute = this.options.notFoundRoute
310
+ if (notFoundRoute) {
311
+ notFoundRoute.init({ originalIndex: 99999999999 })
312
+ ;(this.routesById as any)[notFoundRoute.id] = notFoundRoute
313
+ }
314
+
315
+ const recurseRoutes = (childRoutes: AnyRoute[]) => {
316
+ childRoutes.forEach((childRoute, i) => {
317
+ childRoute.init({ originalIndex: i })
318
+
319
+ const existingRoute = (this.routesById as any)[childRoute.id]
320
+
321
+ invariant(
322
+ !existingRoute,
323
+ `Duplicate routes found with id: ${String(childRoute.id)}`,
324
+ )
325
+ ;(this.routesById as any)[childRoute.id] = childRoute
326
+
327
+ if (!childRoute.isRoot && childRoute.path) {
328
+ const trimmedFullPath = trimPathRight(childRoute.fullPath)
329
+ if (
330
+ !(this.routesByPath as any)[trimmedFullPath] ||
331
+ childRoute.fullPath.endsWith('/')
332
+ ) {
333
+ ;(this.routesByPath as any)[trimmedFullPath] = childRoute
334
+ }
335
+ }
336
+
337
+ const children = childRoute.children as Route[]
338
+
339
+ if (children?.length) {
340
+ recurseRoutes(children)
341
+ }
342
+ })
343
+ }
344
+
345
+ recurseRoutes([this.routeTree])
346
+
347
+ const scoredRoutes: {
348
+ child: AnyRoute
349
+ trimmed: string
350
+ parsed: ReturnType<typeof parsePathname>
351
+ index: number
352
+ scores: number[]
353
+ }[] = []
354
+
355
+ ;(Object.values(this.routesById) as AnyRoute[]).forEach((d, i) => {
356
+ if (d.isRoot || !d.path) {
357
+ return
358
+ }
359
+
360
+ const trimmed = trimPathLeft(d.fullPath)
361
+ const parsed = parsePathname(trimmed)
362
+
363
+ while (parsed.length > 1 && parsed[0]?.value === '/') {
364
+ parsed.shift()
365
+ }
366
+
367
+ const scores = parsed.map((d) => {
368
+ if (d.value === '/') {
369
+ return 0.75
370
+ }
371
+
372
+ if (d.type === 'param') {
373
+ return 0.5
374
+ }
375
+
376
+ if (d.type === 'wildcard') {
377
+ return 0.25
378
+ }
379
+
380
+ return 1
381
+ })
382
+
383
+ scoredRoutes.push({ child: d, trimmed, parsed, index: i, scores })
384
+ })
385
+
386
+ this.flatRoutes = scoredRoutes
387
+ .sort((a, b) => {
388
+ const minLength = Math.min(a.scores.length, b.scores.length)
389
+
390
+ // Sort by min available score
391
+ for (let i = 0; i < minLength; i++) {
392
+ if (a.scores[i] !== b.scores[i]) {
393
+ return b.scores[i]! - a.scores[i]!
394
+ }
395
+ }
396
+
397
+ // Sort by length of score
398
+ if (a.scores.length !== b.scores.length) {
399
+ return b.scores.length - a.scores.length
400
+ }
401
+
402
+ // Sort by min available parsed value
403
+ for (let i = 0; i < minLength; i++) {
404
+ if (a.parsed[i]!.value !== b.parsed[i]!.value) {
405
+ return a.parsed[i]!.value! > b.parsed[i]!.value! ? 1 : -1
406
+ }
407
+ }
408
+
409
+ // Sort by original index
410
+ return a.index - b.index
411
+ })
412
+ .map((d, i) => {
413
+ d.child.rank = i
414
+ return d.child
415
+ })
416
+ }
417
+
418
+ subscribe = <TType extends keyof RouterEvents>(
419
+ eventType: TType,
420
+ fn: ListenerFn<RouterEvents[TType]>,
421
+ ) => {
422
+ const listener: RouterListener<any> = {
423
+ eventType,
424
+ fn,
425
+ }
426
+
427
+ this.subscribers.add(listener)
428
+
429
+ return () => {
430
+ this.subscribers.delete(listener)
431
+ }
432
+ }
433
+
434
+ emit = (routerEvent: RouterEvent) => {
435
+ this.subscribers.forEach((listener) => {
436
+ if (listener.eventType === routerEvent.type) {
437
+ listener.fn(routerEvent)
438
+ }
439
+ })
440
+ }
441
+
442
+ checkLatest = (promise: Promise<void>): undefined | Promise<void> => {
443
+ return this.latestLoadPromise !== promise
444
+ ? this.latestLoadPromise
445
+ : undefined
446
+ }
447
+
448
+ parseLocation = (
449
+ previousLocation?: ParsedLocation,
450
+ ): ParsedLocation<FullSearchSchema<TRouteTree>> => {
451
+ const parse = ({
452
+ pathname,
453
+ search,
454
+ hash,
455
+ state,
456
+ }: HistoryLocation): ParsedLocation<FullSearchSchema<TRouteTree>> => {
457
+ const parsedSearch = this.options.parseSearch(search)
458
+
459
+ return {
460
+ pathname: pathname,
461
+ searchStr: search,
462
+ search: replaceEqualDeep(previousLocation?.search, parsedSearch) as any,
463
+ hash: hash.split('#').reverse()[0] ?? '',
464
+ href: `${pathname}${search}${hash}`,
465
+ state: replaceEqualDeep(previousLocation?.state, state) as HistoryState,
466
+ }
467
+ }
468
+
469
+ const location = parse(this.history.location)
470
+
471
+ let { __tempLocation, __tempKey } = location.state
472
+
473
+ if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
474
+ // Sync up the location keys
475
+ const parsedTempLocation = parse(__tempLocation) as any
476
+ parsedTempLocation.state.key = location.state.key
477
+
478
+ delete parsedTempLocation.state.__tempLocation
479
+
480
+ return {
481
+ ...parsedTempLocation,
482
+ maskedLocation: location,
483
+ }
484
+ }
485
+
486
+ return location
487
+ }
488
+
489
+ resolvePathWithBase = (from: string, path: string) => {
490
+ return resolvePath(this.basepath!, from, cleanPath(path))
491
+ }
492
+
493
+ get looseRoutesById() {
494
+ return this.routesById as Record<string, AnyRoute>
495
+ }
496
+
497
+ matchRoutes = <TRouteTree extends AnyRoute>(
498
+ pathname: string,
499
+ locationSearch: AnySearchSchema,
500
+ opts?: { throwOnError?: boolean; debug?: boolean },
501
+ ): RouteMatch<TRouteTree>[] => {
502
+ let routeParams: Record<string, string> = {}
503
+
504
+ let foundRoute = this.flatRoutes.find((route) => {
505
+ const matchedParams = matchPathname(
506
+ this.basepath,
507
+ trimPathRight(pathname),
508
+ {
509
+ to: route.fullPath,
510
+ caseSensitive:
511
+ route.options.caseSensitive ?? this.options.caseSensitive,
512
+ fuzzy: true,
513
+ },
514
+ )
515
+
516
+ if (matchedParams) {
517
+ routeParams = matchedParams
518
+ return true
519
+ }
520
+
521
+ return false
522
+ })
523
+
524
+ let routeCursor: AnyRoute =
525
+ foundRoute || (this.routesById as any)['__root__']
526
+
527
+ let matchedRoutes: AnyRoute[] = [routeCursor]
528
+
529
+ // Check to see if the route needs a 404 entry
530
+ if (
531
+ // If we found a route, and it's not an index route and we have left over path
532
+ (foundRoute
533
+ ? foundRoute.path !== '/' && routeParams['**']
534
+ : // Or if we didn't find a route and we have left over path
535
+ trimPathRight(pathname)) &&
536
+ // And we have a 404 route configured
537
+ this.options.notFoundRoute
538
+ ) {
539
+ matchedRoutes.push(this.options.notFoundRoute)
540
+ }
541
+
542
+ while (routeCursor?.parentRoute) {
543
+ routeCursor = routeCursor.parentRoute
544
+ if (routeCursor) matchedRoutes.unshift(routeCursor)
545
+ }
546
+
547
+ // Existing matches are matches that are already loaded along with
548
+ // pending matches that are still loading
549
+
550
+ const parseErrors = matchedRoutes.map((route) => {
551
+ let parsedParamsError
552
+
553
+ if (route.options.parseParams) {
554
+ try {
555
+ const parsedParams = route.options.parseParams(routeParams)
556
+ // Add the parsed params to the accumulated params bag
557
+ Object.assign(routeParams, parsedParams)
558
+ } catch (err: any) {
559
+ parsedParamsError = new PathParamError(err.message, {
560
+ cause: err,
561
+ })
562
+
563
+ if (opts?.throwOnError) {
564
+ throw parsedParamsError
565
+ }
566
+
567
+ return parsedParamsError
568
+ }
569
+ }
570
+
571
+ return
572
+ })
573
+
574
+ const matches: AnyRouteMatch[] = []
575
+
576
+ matchedRoutes.forEach((route, index) => {
577
+ // Take each matched route and resolve + validate its search params
578
+ // This has to happen serially because each route's search params
579
+ // can depend on the parent route's search params
580
+ // It must also happen before we create the match so that we can
581
+ // pass the search params to the route's potential key function
582
+ // which is used to uniquely identify the route match in state
583
+
584
+ const parentMatch = matches[index - 1]
585
+
586
+ const [preMatchSearch, searchError]: [Record<string, any>, any] = (() => {
587
+ // Validate the search params and stabilize them
588
+ const parentSearch = parentMatch?.search ?? locationSearch
589
+
590
+ try {
591
+ const validator =
592
+ typeof route.options.validateSearch === 'object'
593
+ ? route.options.validateSearch.parse
594
+ : route.options.validateSearch
595
+
596
+ let search = validator?.(parentSearch) ?? {}
597
+
598
+ return [
599
+ {
600
+ ...parentSearch,
601
+ ...search,
602
+ },
603
+ undefined,
604
+ ]
605
+ } catch (err: any) {
606
+ const searchError = new SearchParamError(err.message, {
607
+ cause: err,
608
+ })
609
+
610
+ if (opts?.throwOnError) {
611
+ throw searchError
612
+ }
613
+
614
+ return [parentSearch, searchError]
615
+ }
616
+ })()
617
+
618
+ // This is where we need to call route.options.loaderDeps() to get any additional
619
+ // deps that the route's loader function might need to run. We need to do this
620
+ // before we create the match so that we can pass the deps to the route's
621
+ // potential key function which is used to uniquely identify the route match in state
622
+
623
+ const loaderDeps =
624
+ route.options.loaderDeps?.({
625
+ search: preMatchSearch,
626
+ }) ?? ''
627
+
628
+ const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : ''
629
+
630
+ const interpolatedPath = interpolatePath(route.fullPath, routeParams)
631
+ const matchId =
632
+ interpolatePath(route.id, routeParams, true) + loaderDepsHash
633
+
634
+ // Waste not, want not. If we already have a match for this route,
635
+ // reuse it. This is important for layout routes, which might stick
636
+ // around between navigation actions that only change leaf routes.
637
+ const existingMatch = getRouteMatch(this.state, matchId)
638
+
639
+ const cause = this.state.matches.find((d) => d.id === matchId)
640
+ ? 'stay'
641
+ : 'enter'
642
+
643
+ // Create a fresh route match
644
+ const hasLoaders = !!(
645
+ route.options.loader ||
646
+ componentTypes.some((d) => (route.options[d] as any)?.preload)
647
+ )
648
+
649
+ const match: AnyRouteMatch = existingMatch
650
+ ? { ...existingMatch, cause }
651
+ : {
652
+ id: matchId,
653
+ routeId: route.id,
654
+ params: routeParams,
655
+ pathname: joinPaths([this.basepath, interpolatedPath]),
656
+ updatedAt: Date.now(),
657
+ search: {} as any,
658
+ searchError: undefined,
659
+ status: hasLoaders ? 'pending' : 'success',
660
+ showPending: false,
661
+ isFetching: false,
662
+ error: undefined,
663
+ paramsError: parseErrors[index],
664
+ loadPromise: Promise.resolve(),
665
+ routeContext: undefined!,
666
+ context: undefined!,
667
+ abortController: new AbortController(),
668
+ fetchCount: 0,
669
+ cause,
670
+ loaderDeps,
671
+ invalid: false,
672
+ }
673
+
674
+ // Regardless of whether we're reusing an existing match or creating
675
+ // a new one, we need to update the match's search params
676
+ match.search = replaceEqualDeep(match.search, preMatchSearch)
677
+ // And also update the searchError if there is one
678
+ match.searchError = searchError
679
+
680
+ matches.push(match)
681
+ })
682
+
683
+ return matches as any
684
+ }
685
+
686
+ cancelMatch = (id: string) => {
687
+ getRouteMatch(this.state, id)?.abortController?.abort()
688
+ }
689
+
690
+ cancelMatches = () => {
691
+ this.state.pendingMatches?.forEach((match) => {
692
+ this.cancelMatch(match.id)
693
+ })
694
+ }
695
+
696
+ buildLocation: BuildLocationFn<TRouteTree> = (opts) => {
697
+ const build = (
698
+ dest: BuildNextOptions & {
699
+ unmaskOnReload?: boolean
700
+ } = {},
701
+ matches?: AnyRouteMatch[],
702
+ ): ParsedLocation => {
703
+ const from = this.latestLocation
704
+ const fromSearch =
705
+ (this.state.pendingMatches || this.state.matches).at(-1)?.search ||
706
+ from.search
707
+ const fromPathname = dest.from ?? from.pathname
708
+
709
+ let pathname = this.resolvePathWithBase(fromPathname, `${dest.to ?? ''}`)
710
+
711
+ const fromMatches = this.matchRoutes(fromPathname, fromSearch)
712
+ const stayingMatches = matches?.filter(
713
+ (d) => fromMatches?.find((e) => e.routeId === d.routeId),
714
+ )
715
+
716
+ const prevParams = { ...last(fromMatches)?.params }
717
+
718
+ let nextParams =
719
+ (dest.params ?? true) === true
720
+ ? prevParams
721
+ : functionalUpdate(dest.params!, prevParams)
722
+
723
+ if (nextParams) {
724
+ matches
725
+ ?.map((d) => this.looseRoutesById[d.routeId]!.options.stringifyParams)
726
+ .filter(Boolean)
727
+ .forEach((fn) => {
728
+ nextParams = { ...nextParams!, ...fn!(nextParams!) }
729
+ })
730
+ }
731
+
732
+ pathname = interpolatePath(pathname, nextParams ?? {})
733
+
734
+ const preSearchFilters =
735
+ stayingMatches
736
+ ?.map(
737
+ (match) =>
738
+ this.looseRoutesById[match.routeId]!.options.preSearchFilters ??
739
+ [],
740
+ )
741
+ .flat()
742
+ .filter(Boolean) ?? []
743
+
744
+ const postSearchFilters =
745
+ stayingMatches
746
+ ?.map(
747
+ (match) =>
748
+ this.looseRoutesById[match.routeId]!.options.postSearchFilters ??
749
+ [],
750
+ )
751
+ .flat()
752
+ .filter(Boolean) ?? []
753
+
754
+ // Pre filters first
755
+ const preFilteredSearch = preSearchFilters?.length
756
+ ? preSearchFilters?.reduce(
757
+ (prev, next) => next(prev) as any,
758
+ fromSearch,
759
+ )
760
+ : fromSearch
761
+
762
+ // Then the link/navigate function
763
+ const destSearch =
764
+ dest.search === true
765
+ ? preFilteredSearch // Preserve resolvedFrom true
766
+ : dest.search
767
+ ? functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater
768
+ : preSearchFilters?.length
769
+ ? preFilteredSearch // Preserve resolvedFrom filters
770
+ : {}
771
+
772
+ // Then post filters
773
+ const postFilteredSearch = postSearchFilters?.length
774
+ ? postSearchFilters.reduce((prev, next) => next(prev), destSearch)
775
+ : destSearch
776
+
777
+ const search = replaceEqualDeep(fromSearch, postFilteredSearch)
778
+
779
+ const searchStr = this.options.stringifySearch(search)
780
+
781
+ const hash =
782
+ dest.hash === true
783
+ ? from.hash
784
+ : dest.hash
785
+ ? functionalUpdate(dest.hash!, from.hash)
786
+ : from.hash
787
+
788
+ const hashStr = hash ? `#${hash}` : ''
789
+
790
+ let nextState =
791
+ dest.state === true
792
+ ? from.state
793
+ : dest.state
794
+ ? functionalUpdate(dest.state, from.state)
795
+ : from.state
796
+
797
+ nextState = replaceEqualDeep(from.state, nextState)
798
+
799
+ return {
800
+ pathname,
801
+ search,
802
+ searchStr,
803
+ state: nextState as any,
804
+ hash,
805
+ href: `${pathname}${searchStr}${hashStr}`,
806
+ unmaskOnReload: dest.unmaskOnReload,
807
+ }
808
+ }
809
+
810
+ const buildWithMatches = (
811
+ dest: BuildNextOptions = {},
812
+ maskedDest?: BuildNextOptions,
813
+ ) => {
814
+ let next = build(dest)
815
+ let maskedNext = maskedDest ? build(maskedDest) : undefined
816
+
817
+ if (!maskedNext) {
818
+ let params = {}
819
+
820
+ let foundMask = this.options.routeMasks?.find((d) => {
821
+ const match = matchPathname(this.basepath, next.pathname, {
822
+ to: d.from,
823
+ caseSensitive: false,
824
+ fuzzy: false,
825
+ })
826
+
827
+ if (match) {
828
+ params = match
829
+ return true
830
+ }
831
+
832
+ return false
833
+ })
834
+
835
+ if (foundMask) {
836
+ foundMask = {
837
+ ...foundMask,
838
+ from: interpolatePath(foundMask.from, params) as any,
839
+ }
840
+ maskedDest = foundMask
841
+ maskedNext = build(maskedDest)
842
+ }
843
+ }
844
+
845
+ const nextMatches = this.matchRoutes(next.pathname, next.search)
846
+ const maskedMatches = maskedNext
847
+ ? this.matchRoutes(maskedNext.pathname, maskedNext.search)
848
+ : undefined
849
+ const maskedFinal = maskedNext
850
+ ? build(maskedDest, maskedMatches)
851
+ : undefined
852
+
853
+ const final = build(dest, nextMatches)
854
+
855
+ if (maskedFinal) {
856
+ final.maskedLocation = maskedFinal
857
+ }
858
+
859
+ return final
860
+ }
861
+
862
+ if (opts.mask) {
863
+ return buildWithMatches(opts, {
864
+ ...pick(opts, ['from']),
865
+ ...opts.mask,
866
+ })
867
+ }
868
+
869
+ return buildWithMatches(opts)
870
+ }
871
+
872
+ commitLocation = async ({
873
+ startTransition,
874
+ ...next
875
+ }: ParsedLocation & CommitLocationOptions) => {
876
+ if (this.navigateTimeout) clearTimeout(this.navigateTimeout)
877
+
878
+ const isSameUrl = this.latestLocation.href === next.href
879
+
880
+ // If the next urls are the same and we're not replacing,
881
+ // do nothing
882
+ if (!isSameUrl || !next.replace) {
883
+ let { maskedLocation, ...nextHistory } = next
884
+
885
+ if (maskedLocation) {
886
+ nextHistory = {
887
+ ...maskedLocation,
888
+ state: {
889
+ ...maskedLocation.state,
890
+ __tempKey: undefined,
891
+ __tempLocation: {
892
+ ...nextHistory,
893
+ search: nextHistory.searchStr,
894
+ state: {
895
+ ...nextHistory.state,
896
+ __tempKey: undefined!,
897
+ __tempLocation: undefined!,
898
+ key: undefined!,
899
+ },
900
+ },
901
+ },
902
+ }
903
+
904
+ if (
905
+ nextHistory.unmaskOnReload ??
906
+ this.options.unmaskOnReload ??
907
+ false
908
+ ) {
909
+ nextHistory.state.__tempKey = this.tempLocationKey
910
+ }
911
+ }
912
+
913
+ const apply = () => {
914
+ this.history[next.replace ? 'replace' : 'push'](
915
+ nextHistory.href,
916
+ nextHistory.state,
917
+ )
918
+ }
919
+
920
+ if (startTransition ?? true) {
921
+ this.startReactTransition(apply)
922
+ } else {
923
+ apply()
924
+ }
925
+ }
926
+
927
+ this.resetNextScroll = next.resetScroll ?? true
928
+
929
+ return this.latestLoadPromise
930
+ }
931
+
932
+ buildAndCommitLocation = ({
933
+ replace,
934
+ resetScroll,
935
+ startTransition,
936
+ ...rest
937
+ }: BuildNextOptions & CommitLocationOptions = {}) => {
938
+ const location = this.buildLocation(rest as any)
939
+ return this.commitLocation({
940
+ ...location,
941
+ startTransition,
942
+ replace,
943
+ resetScroll,
944
+ })
945
+ }
946
+
947
+ navigate: NavigateFn<TRouteTree> = ({ from, to = '', ...rest }) => {
948
+ // If this link simply reloads the current route,
949
+ // make sure it has a new key so it will trigger a data refresh
950
+
951
+ // If this `to` is a valid external URL, return
952
+ // null for LinkUtils
953
+ const toString = String(to)
954
+ const fromString = typeof from === 'undefined' ? from : String(from)
955
+ let isExternal
956
+
957
+ try {
958
+ new URL(`${toString}`)
959
+ isExternal = true
960
+ } catch (e) {}
961
+
962
+ invariant(
963
+ !isExternal,
964
+ 'Attempting to navigate to external url with this.navigate!',
965
+ )
966
+
967
+ return this.buildAndCommitLocation({
968
+ ...rest,
969
+ from: fromString,
970
+ to: toString,
971
+ })
972
+ }
973
+
974
+ loadMatches = async ({
975
+ checkLatest,
976
+ matches,
977
+ preload,
978
+ }: {
979
+ checkLatest: () => Promise<void> | undefined
980
+ matches: AnyRouteMatch[]
981
+ preload?: boolean
982
+ }): Promise<RouteMatch[]> => {
983
+ let latestPromise
984
+ let firstBadMatchIndex: number | undefined
985
+
986
+ const updateMatch = (match: AnyRouteMatch) => {
987
+ // const isPreload = this.state.cachedMatches.find((d) => d.id === match.id)
988
+ const isPending = this.state.pendingMatches?.find(
989
+ (d) => d.id === match.id,
990
+ )
991
+
992
+ const isMatched = this.state.matches.find((d) => d.id === match.id)
993
+
994
+ const matchesKey = isPending
995
+ ? 'pendingMatches'
996
+ : isMatched
997
+ ? 'matches'
998
+ : 'cachedMatches'
999
+
1000
+ this.__store.setState((s) => ({
1001
+ ...s,
1002
+ [matchesKey]: s[matchesKey]?.map((d) =>
1003
+ d.id === match.id ? match : d,
1004
+ ),
1005
+ }))
1006
+ }
1007
+
1008
+ // Check each match middleware to see if the route can be accessed
1009
+ try {
1010
+ for (let [index, match] of matches.entries()) {
1011
+ const parentMatch = matches[index - 1]
1012
+ const route = this.looseRoutesById[match.routeId]!
1013
+ const abortController = new AbortController()
1014
+
1015
+ const handleErrorAndRedirect = (err: any, code: string) => {
1016
+ err.routerCode = code
1017
+ firstBadMatchIndex = firstBadMatchIndex ?? index
1018
+
1019
+ if (isRedirect(err)) {
1020
+ throw err
1021
+ }
1022
+
1023
+ try {
1024
+ route.options.onError?.(err)
1025
+ } catch (errorHandlerErr) {
1026
+ err = errorHandlerErr
1027
+
1028
+ if (isRedirect(errorHandlerErr)) {
1029
+ throw errorHandlerErr
1030
+ }
1031
+ }
1032
+
1033
+ matches[index] = match = {
1034
+ ...match,
1035
+ error: err,
1036
+ status: 'error',
1037
+ updatedAt: Date.now(),
1038
+ abortController: new AbortController(),
1039
+ }
1040
+ }
1041
+
1042
+ try {
1043
+ if (match.paramsError) {
1044
+ handleErrorAndRedirect(match.paramsError, 'PARSE_PARAMS')
1045
+ }
1046
+
1047
+ if (match.searchError) {
1048
+ handleErrorAndRedirect(match.searchError, 'VALIDATE_SEARCH')
1049
+ }
1050
+
1051
+ const parentContext =
1052
+ parentMatch?.context ?? this.options.context ?? {}
1053
+
1054
+ const beforeLoadContext =
1055
+ (await route.options.beforeLoad?.({
1056
+ search: match.search,
1057
+ abortController,
1058
+ params: match.params,
1059
+ preload: !!preload,
1060
+ context: parentContext,
1061
+ location: this.state.location,
1062
+ // TOOD: just expose state and router, etc
1063
+ navigate: (opts) =>
1064
+ this.navigate({ ...opts, from: match.pathname } as any),
1065
+ buildLocation: this.buildLocation,
1066
+ cause: preload ? 'preload' : match.cause,
1067
+ })) ?? ({} as any)
1068
+
1069
+ if (isRedirect(beforeLoadContext)) {
1070
+ throw beforeLoadContext
1071
+ }
1072
+
1073
+ const context = {
1074
+ ...parentContext,
1075
+ ...beforeLoadContext,
1076
+ }
1077
+
1078
+ matches[index] = match = {
1079
+ ...match,
1080
+ routeContext: replaceEqualDeep(
1081
+ match.routeContext,
1082
+ beforeLoadContext,
1083
+ ),
1084
+ context: replaceEqualDeep(match.context, context),
1085
+ abortController,
1086
+ }
1087
+ } catch (err) {
1088
+ handleErrorAndRedirect(err, 'BEFORE_LOAD')
1089
+ break
1090
+ }
1091
+ }
1092
+ } catch (err) {
1093
+ if (isRedirect(err)) {
1094
+ if (!preload) this.navigate(err as any)
1095
+ return matches
1096
+ }
1097
+
1098
+ throw err
1099
+ }
1100
+
1101
+ const validResolvedMatches = matches.slice(0, firstBadMatchIndex)
1102
+ const matchPromises: Promise<any>[] = []
1103
+
1104
+ validResolvedMatches.forEach((match, index) => {
1105
+ matchPromises.push(
1106
+ new Promise<void>(async (resolve) => {
1107
+ const parentMatchPromise = matchPromises[index - 1]
1108
+ const route = this.looseRoutesById[match.routeId]!
1109
+
1110
+ const handleErrorAndRedirect = (err: any) => {
1111
+ if (isRedirect(err)) {
1112
+ if (!preload) {
1113
+ this.navigate(err as any)
1114
+ }
1115
+ return true
1116
+ }
1117
+ return false
1118
+ }
1119
+
1120
+ let loadPromise: Promise<void> | undefined
1121
+
1122
+ matches[index] = match = {
1123
+ ...match,
1124
+ showPending: false,
1125
+ }
1126
+
1127
+ let didShowPending = false
1128
+ const pendingMs =
1129
+ route.options.pendingMs ?? this.options.defaultPendingMs
1130
+ const pendingMinMs =
1131
+ route.options.pendingMinMs ?? this.options.defaultPendingMinMs
1132
+ const shouldPending =
1133
+ !preload &&
1134
+ pendingMs &&
1135
+ (route.options.pendingComponent ??
1136
+ this.options.defaultPendingComponent)
1137
+
1138
+ const loaderContext: LoaderFnContext = {
1139
+ params: match.params,
1140
+ deps: match.loaderDeps,
1141
+ preload: !!preload,
1142
+ parentMatchPromise,
1143
+ abortController: match.abortController,
1144
+ context: match.context,
1145
+ location: this.state.location,
1146
+ navigate: (opts) =>
1147
+ this.navigate({ ...opts, from: match.pathname } as any),
1148
+ cause: preload ? 'preload' : match.cause,
1149
+ }
1150
+
1151
+ const fetch = async () => {
1152
+ if (match.isFetching) {
1153
+ loadPromise = getRouteMatch(this.state, match.id)?.loadPromise
1154
+ } else {
1155
+ // If the user doesn't want the route to reload, just
1156
+ // resolve with the existing loader data
1157
+
1158
+ if (match.fetchCount && match.status === 'success') {
1159
+ resolve()
1160
+ }
1161
+
1162
+ // Otherwise, load the route
1163
+ matches[index] = match = {
1164
+ ...match,
1165
+ isFetching: true,
1166
+ fetchCount: match.fetchCount + 1,
1167
+ }
1168
+
1169
+ const componentsPromise = Promise.all(
1170
+ componentTypes.map(async (type) => {
1171
+ const component = route.options[type]
1172
+
1173
+ if ((component as any)?.preload) {
1174
+ await (component as any).preload()
1175
+ }
1176
+ }),
1177
+ )
1178
+
1179
+ const loaderPromise = route.options.loader?.(loaderContext)
1180
+
1181
+ loadPromise = Promise.all([
1182
+ componentsPromise,
1183
+ loaderPromise,
1184
+ ]).then((d) => d[1])
1185
+ }
1186
+
1187
+ matches[index] = match = {
1188
+ ...match,
1189
+ loadPromise,
1190
+ }
1191
+
1192
+ updateMatch(match)
1193
+
1194
+ try {
1195
+ const loaderData = await loadPromise
1196
+ if ((latestPromise = checkLatest())) return await latestPromise
1197
+
1198
+ if (isRedirect(loaderData)) {
1199
+ if (handleErrorAndRedirect(loaderData)) return
1200
+ }
1201
+
1202
+ if (didShowPending && pendingMinMs) {
1203
+ await new Promise((r) => setTimeout(r, pendingMinMs))
1204
+ }
1205
+
1206
+ if ((latestPromise = checkLatest())) return await latestPromise
1207
+
1208
+ matches[index] = match = {
1209
+ ...match,
1210
+ error: undefined,
1211
+ status: 'success',
1212
+ isFetching: false,
1213
+ updatedAt: Date.now(),
1214
+ loaderData,
1215
+ loadPromise: undefined,
1216
+ }
1217
+ } catch (error) {
1218
+ if ((latestPromise = checkLatest())) return await latestPromise
1219
+ if (handleErrorAndRedirect(error)) return
1220
+
1221
+ try {
1222
+ route.options.onError?.(error)
1223
+ } catch (onErrorError) {
1224
+ error = onErrorError
1225
+ if (handleErrorAndRedirect(onErrorError)) return
1226
+ }
1227
+
1228
+ matches[index] = match = {
1229
+ ...match,
1230
+ error,
1231
+ status: 'error',
1232
+ isFetching: false,
1233
+ }
1234
+ }
1235
+
1236
+ updateMatch(match)
1237
+ }
1238
+
1239
+ // This is where all of the stale-while-revalidate magic happens
1240
+ const age = Date.now() - match.updatedAt
1241
+
1242
+ let staleAge = preload
1243
+ ? route.options.preloadStaleTime ??
1244
+ this.options.defaultPreloadStaleTime ??
1245
+ 30_000 // 30 seconds for preloads by default
1246
+ : route.options.staleTime ?? this.options.defaultStaleTime ?? 0
1247
+
1248
+ // Default to reloading the route all the time
1249
+ let shouldReload
1250
+
1251
+ const shouldReloadOption = route.options.shouldReload
1252
+
1253
+ // Allow shouldReload to get the last say,
1254
+ // if provided.
1255
+ shouldReload =
1256
+ typeof shouldReloadOption === 'function'
1257
+ ? shouldReloadOption(loaderContext)
1258
+ : shouldReloadOption
1259
+
1260
+ if (match.status !== 'success') {
1261
+ // If we need to potentially show the pending component,
1262
+ // start a timer to show it after the pendingMs
1263
+ if (shouldPending) {
1264
+ new Promise((r) => setTimeout(r, pendingMs)).then(async () => {
1265
+ if ((latestPromise = checkLatest())) return latestPromise
1266
+
1267
+ didShowPending = true
1268
+ matches[index] = match = {
1269
+ ...match,
1270
+ showPending: true,
1271
+ }
1272
+
1273
+ updateMatch(match)
1274
+ resolve()
1275
+ })
1276
+ }
1277
+
1278
+ // Critical Fetching, we need to await
1279
+ await fetch()
1280
+ } else if (match.invalid || (shouldReload ?? age > staleAge)) {
1281
+ // Background Fetching, no need to wait
1282
+ fetch()
1283
+ }
1284
+
1285
+ resolve()
1286
+ }),
1287
+ )
1288
+ })
1289
+
1290
+ await Promise.all(matchPromises)
1291
+ return matches
1292
+ }
1293
+
1294
+ invalidate = () => {
1295
+ const invalidate = (d: any) => ({
1296
+ ...d,
1297
+ invalid: true,
1298
+ })
1299
+
1300
+ this.__store.setState((s) => ({
1301
+ ...s,
1302
+ matches: s.matches.map(invalidate),
1303
+ cachedMatches: s.cachedMatches.map(invalidate),
1304
+ pendingMatches: s.pendingMatches?.map(invalidate),
1305
+ }))
1306
+
1307
+ this.load()
1308
+ }
1309
+
1310
+ load = async (): Promise<void> => {
1311
+ const promise = new Promise<void>(async (resolve, reject) => {
1312
+ const next = this.latestLocation
1313
+ const prevLocation = this.state.resolvedLocation
1314
+ const pathDidChange = prevLocation!.href !== next.href
1315
+ let latestPromise: Promise<void> | undefined | null
1316
+
1317
+ // Cancel any pending matches
1318
+ this.cancelMatches()
1319
+
1320
+ this.emit({
1321
+ type: 'onBeforeLoad',
1322
+ fromLocation: prevLocation,
1323
+ toLocation: next,
1324
+ pathChanged: pathDidChange,
1325
+ })
1326
+
1327
+ let pendingMatches!: RouteMatch<any, any>[]
1328
+ const previousMatches = this.state.matches
1329
+
1330
+ this.__store.batch(() => {
1331
+ // This is where all of the garbage collection magic happens
1332
+ this.__store.setState((s) => {
1333
+ return {
1334
+ ...s,
1335
+ cachedMatches: s.cachedMatches.filter((d) => {
1336
+ const route = this.looseRoutesById[d.routeId]!
1337
+
1338
+ return (
1339
+ d.status !== 'error' &&
1340
+ Date.now() - d.updatedAt <
1341
+ (route.options.gcTime ??
1342
+ this.options.defaultGcTime ??
1343
+ 5 * 60 * 1000)
1344
+ )
1345
+ }),
1346
+ }
1347
+ })
1348
+
1349
+ // Match the routes
1350
+ pendingMatches = this.matchRoutes(next.pathname, next.search, {
1351
+ debug: true,
1352
+ })
1353
+
1354
+ // Ingest the new matches
1355
+ // If a cached moved to pendingMatches, remove it from cachedMatches
1356
+ this.__store.setState((s) => ({
1357
+ ...s,
1358
+ isLoading: true,
1359
+ location: next,
1360
+ pendingMatches,
1361
+ cachedMatches: s.cachedMatches.filter((d) => {
1362
+ return !pendingMatches.find((e) => e.id === d.id)
1363
+ }),
1364
+ }))
1365
+ })
1366
+
1367
+ try {
1368
+ try {
1369
+ // Load the matches
1370
+ await this.loadMatches({
1371
+ matches: pendingMatches,
1372
+ checkLatest: () => this.checkLatest(promise),
1373
+ })
1374
+ } catch (err) {
1375
+ // swallow this error, since we'll display the
1376
+ // errors on the route components
1377
+ }
1378
+
1379
+ // Only apply the latest transition
1380
+ if ((latestPromise = this.checkLatest(promise))) {
1381
+ return latestPromise
1382
+ }
1383
+
1384
+ const exitingMatches = previousMatches.filter(
1385
+ (match) => !pendingMatches.find((d) => d.id === match.id),
1386
+ )
1387
+ const enteringMatches = pendingMatches.filter(
1388
+ (match) => !previousMatches.find((d) => d.id === match.id),
1389
+ )
1390
+ const stayingMatches = previousMatches.filter((match) =>
1391
+ pendingMatches.find((d) => d.id === match.id),
1392
+ )
1393
+
1394
+ // Commit the pending matches. If a previous match was
1395
+ // removed, place it in the cachedMatches
1396
+ this.__store.setState((s) => ({
1397
+ ...s,
1398
+ isLoading: false,
1399
+ matches: pendingMatches,
1400
+ pendingMatches: undefined,
1401
+ cachedMatches: [
1402
+ ...s.cachedMatches,
1403
+ ...exitingMatches.filter((d) => d.status !== 'error'),
1404
+ ],
1405
+ }))
1406
+
1407
+ //
1408
+ ;(
1409
+ [
1410
+ [exitingMatches, 'onLeave'],
1411
+ [enteringMatches, 'onEnter'],
1412
+ [stayingMatches, 'onStay'],
1413
+ ] as const
1414
+ ).forEach(([matches, hook]) => {
1415
+ matches.forEach((match) => {
1416
+ this.looseRoutesById[match.routeId]!.options[hook]?.(match)
1417
+ })
1418
+ })
1419
+
1420
+ this.emit({
1421
+ type: 'onLoad',
1422
+ fromLocation: prevLocation,
1423
+ toLocation: next,
1424
+ pathChanged: pathDidChange,
1425
+ })
1426
+
1427
+ resolve()
1428
+ } catch (err) {
1429
+ // Only apply the latest transition
1430
+ if ((latestPromise = this.checkLatest(promise))) {
1431
+ return latestPromise
1432
+ }
1433
+
1434
+ reject(err)
1435
+ }
1436
+ })
1437
+
1438
+ this.latestLoadPromise = promise
1439
+
1440
+ return this.latestLoadPromise
1441
+ }
1442
+
1443
+ preloadRoute = async (
1444
+ navigateOpts: ToOptions<TRouteTree> = this.state.location as any,
1445
+ ) => {
1446
+ let next = this.buildLocation(navigateOpts as any)
1447
+
1448
+ let matches = this.matchRoutes(next.pathname, next.search, {
1449
+ throwOnError: true,
1450
+ })
1451
+
1452
+ const loadedMatchIds = Object.fromEntries(
1453
+ [
1454
+ ...this.state.matches,
1455
+ ...(this.state.pendingMatches ?? []),
1456
+ ...this.state.cachedMatches,
1457
+ ]?.map((d) => [d.id, true]),
1458
+ )
1459
+
1460
+ this.__store.batch(() => {
1461
+ matches.forEach((match) => {
1462
+ if (!loadedMatchIds[match.id]) {
1463
+ this.__store.setState((s) => ({
1464
+ ...s,
1465
+ cachedMatches: [...(s.cachedMatches as any), match],
1466
+ }))
1467
+ }
1468
+ })
1469
+ })
1470
+
1471
+ matches = await this.loadMatches({
1472
+ matches,
1473
+ preload: true,
1474
+ checkLatest: () => undefined,
1475
+ })
1476
+
1477
+ return matches
1478
+ }
1479
+
1480
+ matchRoute: MatchRouteFn<TRouteTree> = (location, opts) => {
1481
+ location = {
1482
+ ...location,
1483
+ to: location.to
1484
+ ? this.resolvePathWithBase((location.from || '') as string, location.to)
1485
+ : undefined,
1486
+ } as any
1487
+
1488
+ const next = this.buildLocation(location as any)
1489
+
1490
+ if (opts?.pending && this.state.status !== 'pending') {
1491
+ return false
1492
+ }
1493
+
1494
+ const baseLocation = opts?.pending
1495
+ ? this.latestLocation
1496
+ : this.state.resolvedLocation
1497
+
1498
+ if (!baseLocation) {
1499
+ return false
1500
+ }
1501
+
1502
+ const match = matchPathname(this.basepath, baseLocation.pathname, {
1503
+ ...opts,
1504
+ to: next.pathname,
1505
+ }) as any
1506
+
1507
+ if (!match) {
1508
+ return false
1509
+ }
1510
+
1511
+ if (match && (opts?.includeSearch ?? true)) {
1512
+ return deepEqual(baseLocation.search, next.search, true) ? match : false
1513
+ }
1514
+
1515
+ return match
1516
+ }
1517
+
1518
+ injectHtml = async (html: string | (() => Promise<string> | string)) => {
1519
+ this.injectedHtml.push(html)
1520
+ }
1521
+
1522
+ dehydrateData = <T>(key: any, getData: T | (() => Promise<T> | T)) => {
1523
+ if (typeof document === 'undefined') {
1524
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key)
1525
+
1526
+ this.injectHtml(async () => {
1527
+ const id = `__TSR_DEHYDRATED__${strKey}`
1528
+ const data =
1529
+ typeof getData === 'function' ? await (getData as any)() : getData
1530
+ return `<script id='${id}' suppressHydrationWarning>window["__TSR_DEHYDRATED__${escapeJSON(
1531
+ strKey,
1532
+ )}"] = ${JSON.stringify(data)}
1533
+ ;(() => {
1534
+ var el = document.getElementById('${id}')
1535
+ el.parentElement.removeChild(el)
1536
+ })()
1537
+ </script>`
1538
+ })
1539
+
1540
+ return () => this.hydrateData<T>(key)
1541
+ }
1542
+
1543
+ return () => undefined
1544
+ }
1545
+
1546
+ hydrateData = <T extends any = unknown>(key: any) => {
1547
+ if (typeof document !== 'undefined') {
1548
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key)
1549
+
1550
+ return window[`__TSR_DEHYDRATED__${strKey}` as any] as T
1551
+ }
1552
+
1553
+ return undefined
1554
+ }
1555
+
1556
+ dehydrate = (): DehydratedRouter => {
1557
+ return {
1558
+ state: {
1559
+ dehydratedMatches: this.state.matches.map((d) =>
1560
+ pick(d, ['id', 'status', 'updatedAt', 'loaderData']),
1561
+ ),
1562
+ },
1563
+ }
1564
+ }
1565
+
1566
+ hydrate = async (__do_not_use_server_ctx?: HydrationCtx) => {
1567
+ let _ctx = __do_not_use_server_ctx
1568
+ // Client hydrates from window
1569
+ if (typeof document !== 'undefined') {
1570
+ _ctx = window.__TSR_DEHYDRATED__
1571
+ }
1572
+
1573
+ invariant(
1574
+ _ctx,
1575
+ 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?',
1576
+ )
1577
+
1578
+ const ctx = _ctx
1579
+ this.dehydratedData = ctx.payload as any
1580
+ this.options.hydrate?.(ctx.payload as any)
1581
+ const dehydratedState = ctx.router.state
1582
+
1583
+ let matches = this.matchRoutes(
1584
+ this.state.location.pathname,
1585
+ this.state.location.search,
1586
+ ).map((match) => {
1587
+ const dehydratedMatch = dehydratedState.dehydratedMatches.find(
1588
+ (d) => d.id === match.id,
1589
+ )
1590
+
1591
+ invariant(
1592
+ dehydratedMatch,
1593
+ `Could not find a client-side match for dehydrated match with id: ${match.id}!`,
1594
+ )
1595
+
1596
+ if (dehydratedMatch) {
1597
+ return {
1598
+ ...match,
1599
+ ...dehydratedMatch,
1600
+ }
1601
+ }
1602
+ return match
1603
+ })
1604
+
1605
+ this.__store.setState((s) => {
1606
+ return {
1607
+ ...s,
1608
+ matches: matches as any,
1609
+ }
1610
+ })
1611
+ }
1612
+
1613
+ // resolveMatchPromise = (matchId: string, key: string, value: any) => {
1614
+ // state.matches
1615
+ // .find((d) => d.id === matchId)
1616
+ // ?.__promisesByKey[key]?.resolve(value)
1617
+ // }
1618
+ }
1619
+
1620
+ // A function that takes an import() argument which is a function and returns a new function that will
1621
+ // proxy arguments from the caller to the imported function, retaining all type
1622
+ // information along the way
1623
+ export function lazyFn<
1624
+ T extends Record<string, (...args: any[]) => any>,
1625
+ TKey extends keyof T = 'default',
1626
+ >(fn: () => Promise<T>, key?: TKey) {
1627
+ return async (...args: Parameters<T[TKey]>): Promise<ReturnType<T[TKey]>> => {
1628
+ const imported = await fn()
1629
+ return imported[key || 'default'](...args)
1630
+ }
1631
+ }
1632
+
1633
+ export class SearchParamError extends Error {}
1634
+
1635
+ export class PathParamError extends Error {}
1636
+
1637
+ export function getInitialRouterState(
1638
+ location: ParsedLocation,
1639
+ ): RouterState<any> {
1640
+ return {
1641
+ isLoading: false,
1642
+ isTransitioning: false,
1643
+ status: 'idle',
1644
+ resolvedLocation: { ...location },
1645
+ location,
1646
+ matches: [],
1647
+ pendingMatches: [],
1648
+ cachedMatches: [],
1649
+ lastUpdated: Date.now(),
1650
+ }
1651
+ }