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

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 +1049 -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 +2255 -2571
  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 +62 -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 +282 -0
  65. package/build/types/routeInfo.d.ts +22 -0
  66. package/build/types/router.d.ts +188 -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 +2858 -2548
  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 +421 -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 +872 -0
  94. package/src/routeInfo.ts +70 -0
  95. package/src/router.ts +1630 -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,1630 @@
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
+ }
672
+
673
+ // Regardless of whether we're reusing an existing match or creating
674
+ // a new one, we need to update the match's search params
675
+ match.search = replaceEqualDeep(match.search, preMatchSearch)
676
+ // And also update the searchError if there is one
677
+ match.searchError = searchError
678
+
679
+ matches.push(match)
680
+ })
681
+
682
+ return matches as any
683
+ }
684
+
685
+ cancelMatch = (id: string) => {
686
+ getRouteMatch(this.state, id)?.abortController?.abort()
687
+ }
688
+
689
+ cancelMatches = () => {
690
+ this.state.pendingMatches?.forEach((match) => {
691
+ this.cancelMatch(match.id)
692
+ })
693
+ }
694
+
695
+ buildLocation: BuildLocationFn<TRouteTree> = (opts) => {
696
+ const build = (
697
+ dest: BuildNextOptions & {
698
+ unmaskOnReload?: boolean
699
+ } = {},
700
+ matches?: AnyRouteMatch[],
701
+ ): ParsedLocation => {
702
+ const from = this.latestLocation
703
+ const fromSearch =
704
+ (this.state.pendingMatches || this.state.matches).at(-1)?.search ||
705
+ from.search
706
+ const fromPathname = dest.from ?? from.pathname
707
+
708
+ let pathname = this.resolvePathWithBase(fromPathname, `${dest.to ?? ''}`)
709
+
710
+ const fromMatches = this.matchRoutes(fromPathname, fromSearch)
711
+ const stayingMatches = matches?.filter(
712
+ (d) => fromMatches?.find((e) => e.routeId === d.routeId),
713
+ )
714
+
715
+ const prevParams = { ...last(fromMatches)?.params }
716
+
717
+ let nextParams =
718
+ (dest.params ?? true) === true
719
+ ? prevParams
720
+ : functionalUpdate(dest.params!, prevParams)
721
+
722
+ if (nextParams) {
723
+ matches
724
+ ?.map((d) => this.looseRoutesById[d.routeId]!.options.stringifyParams)
725
+ .filter(Boolean)
726
+ .forEach((fn) => {
727
+ nextParams = { ...nextParams!, ...fn!(nextParams!) }
728
+ })
729
+ }
730
+
731
+ pathname = interpolatePath(pathname, nextParams ?? {})
732
+
733
+ const preSearchFilters =
734
+ stayingMatches
735
+ ?.map(
736
+ (match) =>
737
+ this.looseRoutesById[match.routeId]!.options.preSearchFilters ??
738
+ [],
739
+ )
740
+ .flat()
741
+ .filter(Boolean) ?? []
742
+
743
+ const postSearchFilters =
744
+ stayingMatches
745
+ ?.map(
746
+ (match) =>
747
+ this.looseRoutesById[match.routeId]!.options.postSearchFilters ??
748
+ [],
749
+ )
750
+ .flat()
751
+ .filter(Boolean) ?? []
752
+
753
+ // Pre filters first
754
+ const preFilteredSearch = preSearchFilters?.length
755
+ ? preSearchFilters?.reduce(
756
+ (prev, next) => next(prev) as any,
757
+ fromSearch,
758
+ )
759
+ : fromSearch
760
+
761
+ // Then the link/navigate function
762
+ const destSearch =
763
+ dest.search === true
764
+ ? preFilteredSearch // Preserve resolvedFrom true
765
+ : dest.search
766
+ ? functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater
767
+ : preSearchFilters?.length
768
+ ? preFilteredSearch // Preserve resolvedFrom filters
769
+ : {}
770
+
771
+ // Then post filters
772
+ const postFilteredSearch = postSearchFilters?.length
773
+ ? postSearchFilters.reduce((prev, next) => next(prev), destSearch)
774
+ : destSearch
775
+
776
+ const search = replaceEqualDeep(fromSearch, postFilteredSearch)
777
+
778
+ const searchStr = this.options.stringifySearch(search)
779
+
780
+ const hash =
781
+ dest.hash === true
782
+ ? from.hash
783
+ : dest.hash
784
+ ? functionalUpdate(dest.hash!, from.hash)
785
+ : from.hash
786
+
787
+ const hashStr = hash ? `#${hash}` : ''
788
+
789
+ let nextState =
790
+ dest.state === true
791
+ ? from.state
792
+ : dest.state
793
+ ? functionalUpdate(dest.state, from.state)
794
+ : from.state
795
+
796
+ nextState = replaceEqualDeep(from.state, nextState)
797
+
798
+ return {
799
+ pathname,
800
+ search,
801
+ searchStr,
802
+ state: nextState as any,
803
+ hash,
804
+ href: `${pathname}${searchStr}${hashStr}`,
805
+ unmaskOnReload: dest.unmaskOnReload,
806
+ }
807
+ }
808
+
809
+ const buildWithMatches = (
810
+ dest: BuildNextOptions = {},
811
+ maskedDest?: BuildNextOptions,
812
+ ) => {
813
+ let next = build(dest)
814
+ let maskedNext = maskedDest ? build(maskedDest) : undefined
815
+
816
+ if (!maskedNext) {
817
+ let params = {}
818
+
819
+ let foundMask = this.options.routeMasks?.find((d) => {
820
+ const match = matchPathname(this.basepath, next.pathname, {
821
+ to: d.from,
822
+ caseSensitive: false,
823
+ fuzzy: false,
824
+ })
825
+
826
+ if (match) {
827
+ params = match
828
+ return true
829
+ }
830
+
831
+ return false
832
+ })
833
+
834
+ if (foundMask) {
835
+ foundMask = {
836
+ ...foundMask,
837
+ from: interpolatePath(foundMask.from, params) as any,
838
+ }
839
+ maskedDest = foundMask
840
+ maskedNext = build(maskedDest)
841
+ }
842
+ }
843
+
844
+ const nextMatches = this.matchRoutes(next.pathname, next.search)
845
+ const maskedMatches = maskedNext
846
+ ? this.matchRoutes(maskedNext.pathname, maskedNext.search)
847
+ : undefined
848
+ const maskedFinal = maskedNext
849
+ ? build(maskedDest, maskedMatches)
850
+ : undefined
851
+
852
+ const final = build(dest, nextMatches)
853
+
854
+ if (maskedFinal) {
855
+ final.maskedLocation = maskedFinal
856
+ }
857
+
858
+ return final
859
+ }
860
+
861
+ if (opts.mask) {
862
+ return buildWithMatches(opts, {
863
+ ...pick(opts, ['from']),
864
+ ...opts.mask,
865
+ })
866
+ }
867
+
868
+ return buildWithMatches(opts)
869
+ }
870
+
871
+ commitLocation = async ({
872
+ startTransition,
873
+ ...next
874
+ }: ParsedLocation & CommitLocationOptions) => {
875
+ if (this.navigateTimeout) clearTimeout(this.navigateTimeout)
876
+
877
+ const isSameUrl = this.latestLocation.href === next.href
878
+
879
+ // If the next urls are the same and we're not replacing,
880
+ // do nothing
881
+ if (!isSameUrl || !next.replace) {
882
+ let { maskedLocation, ...nextHistory } = next
883
+
884
+ if (maskedLocation) {
885
+ nextHistory = {
886
+ ...maskedLocation,
887
+ state: {
888
+ ...maskedLocation.state,
889
+ __tempKey: undefined,
890
+ __tempLocation: {
891
+ ...nextHistory,
892
+ search: nextHistory.searchStr,
893
+ state: {
894
+ ...nextHistory.state,
895
+ __tempKey: undefined!,
896
+ __tempLocation: undefined!,
897
+ key: undefined!,
898
+ },
899
+ },
900
+ },
901
+ }
902
+
903
+ if (
904
+ nextHistory.unmaskOnReload ??
905
+ this.options.unmaskOnReload ??
906
+ false
907
+ ) {
908
+ nextHistory.state.__tempKey = this.tempLocationKey
909
+ }
910
+ }
911
+
912
+ const apply = () => {
913
+ this.history[next.replace ? 'replace' : 'push'](
914
+ nextHistory.href,
915
+ nextHistory.state,
916
+ )
917
+ }
918
+
919
+ if (startTransition ?? true) {
920
+ this.startReactTransition(apply)
921
+ } else {
922
+ apply()
923
+ }
924
+ }
925
+
926
+ this.resetNextScroll = next.resetScroll ?? true
927
+
928
+ return this.latestLoadPromise
929
+ }
930
+
931
+ buildAndCommitLocation = ({
932
+ replace,
933
+ resetScroll,
934
+ startTransition,
935
+ ...rest
936
+ }: BuildNextOptions & CommitLocationOptions = {}) => {
937
+ const location = this.buildLocation(rest as any)
938
+ return this.commitLocation({
939
+ ...location,
940
+ startTransition,
941
+ replace,
942
+ resetScroll,
943
+ })
944
+ }
945
+
946
+ navigate: NavigateFn<TRouteTree> = ({ from, to = '', ...rest }) => {
947
+ // If this link simply reloads the current route,
948
+ // make sure it has a new key so it will trigger a data refresh
949
+
950
+ // If this `to` is a valid external URL, return
951
+ // null for LinkUtils
952
+ const toString = String(to)
953
+ const fromString = typeof from === 'undefined' ? from : String(from)
954
+ let isExternal
955
+
956
+ try {
957
+ new URL(`${toString}`)
958
+ isExternal = true
959
+ } catch (e) {}
960
+
961
+ invariant(
962
+ !isExternal,
963
+ 'Attempting to navigate to external url with this.navigate!',
964
+ )
965
+
966
+ return this.buildAndCommitLocation({
967
+ ...rest,
968
+ from: fromString,
969
+ to: toString,
970
+ })
971
+ }
972
+
973
+ loadMatches = async ({
974
+ checkLatest,
975
+ matches,
976
+ preload,
977
+ invalidate,
978
+ }: {
979
+ checkLatest: () => Promise<void> | undefined
980
+ matches: AnyRouteMatch[]
981
+ preload?: boolean
982
+ invalidate?: boolean
983
+ }): Promise<RouteMatch[]> => {
984
+ let latestPromise
985
+ let firstBadMatchIndex: number | undefined
986
+
987
+ const updateMatch = (match: AnyRouteMatch) => {
988
+ // const isPreload = this.state.cachedMatches.find((d) => d.id === match.id)
989
+ const isPending = this.state.pendingMatches?.find(
990
+ (d) => d.id === match.id,
991
+ )
992
+
993
+ const isMatched = this.state.matches.find((d) => d.id === match.id)
994
+
995
+ const matchesKey = isPending
996
+ ? 'pendingMatches'
997
+ : isMatched
998
+ ? 'matches'
999
+ : 'cachedMatches'
1000
+
1001
+ this.__store.setState((s) => ({
1002
+ ...s,
1003
+ [matchesKey]: s[matchesKey]?.map((d) =>
1004
+ d.id === match.id ? match : d,
1005
+ ),
1006
+ }))
1007
+ }
1008
+
1009
+ // Check each match middleware to see if the route can be accessed
1010
+ try {
1011
+ for (let [index, match] of matches.entries()) {
1012
+ const parentMatch = matches[index - 1]
1013
+ const route = this.looseRoutesById[match.routeId]!
1014
+ const abortController = new AbortController()
1015
+
1016
+ const handleErrorAndRedirect = (err: any, code: string) => {
1017
+ err.routerCode = code
1018
+ firstBadMatchIndex = firstBadMatchIndex ?? index
1019
+
1020
+ if (isRedirect(err)) {
1021
+ throw err
1022
+ }
1023
+
1024
+ try {
1025
+ route.options.onError?.(err)
1026
+ } catch (errorHandlerErr) {
1027
+ err = errorHandlerErr
1028
+
1029
+ if (isRedirect(errorHandlerErr)) {
1030
+ throw errorHandlerErr
1031
+ }
1032
+ }
1033
+
1034
+ matches[index] = match = {
1035
+ ...match,
1036
+ error: err,
1037
+ status: 'error',
1038
+ updatedAt: Date.now(),
1039
+ abortController: new AbortController(),
1040
+ }
1041
+ }
1042
+
1043
+ try {
1044
+ if (match.paramsError) {
1045
+ handleErrorAndRedirect(match.paramsError, 'PARSE_PARAMS')
1046
+ }
1047
+
1048
+ if (match.searchError) {
1049
+ handleErrorAndRedirect(match.searchError, 'VALIDATE_SEARCH')
1050
+ }
1051
+
1052
+ const parentContext =
1053
+ parentMatch?.context ?? this.options.context ?? {}
1054
+
1055
+ const beforeLoadContext =
1056
+ (await route.options.beforeLoad?.({
1057
+ search: match.search,
1058
+ abortController,
1059
+ params: match.params,
1060
+ preload: !!preload,
1061
+ context: parentContext,
1062
+ location: this.state.location,
1063
+ // TOOD: just expose state and router, etc
1064
+ navigate: (opts) =>
1065
+ this.navigate({ ...opts, from: match.pathname } as any),
1066
+ buildLocation: this.buildLocation,
1067
+ cause: preload ? 'preload' : match.cause,
1068
+ })) ?? ({} as any)
1069
+
1070
+ if (isRedirect(beforeLoadContext)) {
1071
+ throw beforeLoadContext
1072
+ }
1073
+
1074
+ const context = {
1075
+ ...parentContext,
1076
+ ...beforeLoadContext,
1077
+ }
1078
+
1079
+ matches[index] = match = {
1080
+ ...match,
1081
+ routeContext: replaceEqualDeep(
1082
+ match.routeContext,
1083
+ beforeLoadContext,
1084
+ ),
1085
+ context: replaceEqualDeep(match.context, context),
1086
+ abortController,
1087
+ }
1088
+ } catch (err) {
1089
+ handleErrorAndRedirect(err, 'BEFORE_LOAD')
1090
+ break
1091
+ }
1092
+ }
1093
+ } catch (err) {
1094
+ if (isRedirect(err)) {
1095
+ if (!preload) this.navigate(err as any)
1096
+ return matches
1097
+ }
1098
+
1099
+ throw err
1100
+ }
1101
+
1102
+ const validResolvedMatches = matches.slice(0, firstBadMatchIndex)
1103
+ const matchPromises: Promise<any>[] = []
1104
+
1105
+ validResolvedMatches.forEach((match, index) => {
1106
+ matchPromises.push(
1107
+ new Promise<void>(async (resolve) => {
1108
+ const parentMatchPromise = matchPromises[index - 1]
1109
+ const route = this.looseRoutesById[match.routeId]!
1110
+
1111
+ const handleErrorAndRedirect = (err: any) => {
1112
+ if (isRedirect(err)) {
1113
+ if (!preload) {
1114
+ this.navigate(err as any)
1115
+ }
1116
+ return true
1117
+ }
1118
+ return false
1119
+ }
1120
+
1121
+ let loadPromise: Promise<void> | undefined
1122
+
1123
+ matches[index] = match = {
1124
+ ...match,
1125
+ showPending: false,
1126
+ }
1127
+
1128
+ let didShowPending = false
1129
+ const pendingMs =
1130
+ route.options.pendingMs ?? this.options.defaultPendingMs
1131
+ const pendingMinMs =
1132
+ route.options.pendingMinMs ?? this.options.defaultPendingMinMs
1133
+ const shouldPending =
1134
+ !preload &&
1135
+ pendingMs &&
1136
+ (route.options.pendingComponent ??
1137
+ this.options.defaultPendingComponent)
1138
+
1139
+ const fetch = async () => {
1140
+ if (match.isFetching) {
1141
+ loadPromise = getRouteMatch(this.state, match.id)?.loadPromise
1142
+ } else {
1143
+ const loaderContext: LoaderFnContext = {
1144
+ params: match.params,
1145
+ deps: match.loaderDeps,
1146
+ preload: !!preload,
1147
+ parentMatchPromise,
1148
+ abortController: match.abortController,
1149
+ context: match.context,
1150
+ location: this.state.location,
1151
+ navigate: (opts) =>
1152
+ this.navigate({ ...opts, from: match.pathname } as any),
1153
+ cause: preload ? 'preload' : match.cause,
1154
+ }
1155
+
1156
+ if (match.fetchCount && match.status === 'success') {
1157
+ resolve()
1158
+ }
1159
+
1160
+ // Otherwise, load the route
1161
+ matches[index] = match = {
1162
+ ...match,
1163
+ isFetching: true,
1164
+ fetchCount: match.fetchCount + 1,
1165
+ }
1166
+
1167
+ const componentsPromise = Promise.all(
1168
+ componentTypes.map(async (type) => {
1169
+ const component = route.options[type]
1170
+
1171
+ if ((component as any)?.preload) {
1172
+ await (component as any).preload()
1173
+ }
1174
+ }),
1175
+ )
1176
+
1177
+ const loaderPromise = route.options.loader?.(loaderContext)
1178
+
1179
+ loadPromise = Promise.all([
1180
+ componentsPromise,
1181
+ loaderPromise,
1182
+ ]).then((d) => d[1])
1183
+ }
1184
+
1185
+ matches[index] = match = {
1186
+ ...match,
1187
+ loadPromise,
1188
+ }
1189
+
1190
+ updateMatch(match)
1191
+
1192
+ try {
1193
+ const loaderData = await loadPromise
1194
+ if ((latestPromise = checkLatest())) return await latestPromise
1195
+
1196
+ if (isRedirect(loaderData)) {
1197
+ if (handleErrorAndRedirect(loaderData)) return
1198
+ }
1199
+
1200
+ if (didShowPending && pendingMinMs) {
1201
+ await new Promise((r) => setTimeout(r, pendingMinMs))
1202
+ }
1203
+
1204
+ if ((latestPromise = checkLatest())) return await latestPromise
1205
+
1206
+ matches[index] = match = {
1207
+ ...match,
1208
+ error: undefined,
1209
+ status: 'success',
1210
+ isFetching: false,
1211
+ updatedAt: Date.now(),
1212
+ loaderData,
1213
+ loadPromise: undefined,
1214
+ }
1215
+ } catch (error) {
1216
+ if ((latestPromise = checkLatest())) return await latestPromise
1217
+ if (handleErrorAndRedirect(error)) return
1218
+
1219
+ try {
1220
+ route.options.onError?.(error)
1221
+ } catch (onErrorError) {
1222
+ error = onErrorError
1223
+ if (handleErrorAndRedirect(onErrorError)) return
1224
+ }
1225
+
1226
+ matches[index] = match = {
1227
+ ...match,
1228
+ error,
1229
+ status: 'error',
1230
+ isFetching: false,
1231
+ }
1232
+ }
1233
+
1234
+ updateMatch(match)
1235
+ }
1236
+
1237
+ // This is where all of the stale-while-revalidate magic happens
1238
+ const age = Date.now() - match.updatedAt
1239
+
1240
+ let staleAge = preload
1241
+ ? route.options.preloadStaleTime ??
1242
+ this.options.defaultPreloadStaleTime ??
1243
+ 30_000 // 30 seconds for preloads by default
1244
+ : route.options.staleTime ?? this.options.defaultStaleTime ?? 0
1245
+
1246
+ if (match.status === 'success') {
1247
+ // Background Fetching, no need to wait
1248
+ if (age > staleAge) {
1249
+ fetch()
1250
+ }
1251
+ } else {
1252
+ // Critical Fetching, we need to await
1253
+
1254
+ // If we need to potentially show the pending component,
1255
+ // start a timer to show it after the pendingMs
1256
+ if (shouldPending) {
1257
+ new Promise((r) => setTimeout(r, pendingMs)).then(async () => {
1258
+ if ((latestPromise = checkLatest())) return latestPromise
1259
+
1260
+ didShowPending = true
1261
+ matches[index] = match = {
1262
+ ...match,
1263
+ showPending: true,
1264
+ }
1265
+
1266
+ updateMatch(match)
1267
+ resolve()
1268
+ })
1269
+ }
1270
+
1271
+ await fetch()
1272
+ }
1273
+
1274
+ resolve()
1275
+ }),
1276
+ )
1277
+ })
1278
+
1279
+ await Promise.all(matchPromises)
1280
+ return matches
1281
+ }
1282
+
1283
+ invalidate = () =>
1284
+ this.load({
1285
+ invalidate: true,
1286
+ })
1287
+
1288
+ load = async (opts?: { invalidate?: boolean }): Promise<void> => {
1289
+ const promise = new Promise<void>(async (resolve, reject) => {
1290
+ const next = this.latestLocation
1291
+ const prevLocation = this.state.resolvedLocation
1292
+ const pathDidChange = prevLocation!.href !== next.href
1293
+ let latestPromise: Promise<void> | undefined | null
1294
+
1295
+ // Cancel any pending matches
1296
+ this.cancelMatches()
1297
+
1298
+ this.emit({
1299
+ type: 'onBeforeLoad',
1300
+ fromLocation: prevLocation,
1301
+ toLocation: next,
1302
+ pathChanged: pathDidChange,
1303
+ })
1304
+
1305
+ let pendingMatches!: RouteMatch<any, any>[]
1306
+ const previousMatches = this.state.matches
1307
+
1308
+ this.__store.batch(() => {
1309
+ // This is where all of the garbage collection magic happens
1310
+ this.__store.setState((s) => {
1311
+ return {
1312
+ ...s,
1313
+ cachedMatches: s.cachedMatches.filter((d) => {
1314
+ const route = this.looseRoutesById[d.routeId]!
1315
+
1316
+ return (
1317
+ d.status !== 'error' &&
1318
+ Date.now() - d.updatedAt <
1319
+ (route.options.gcTime ??
1320
+ this.options.defaultGcTime ??
1321
+ 5 * 60 * 1000)
1322
+ )
1323
+ }),
1324
+ }
1325
+ })
1326
+
1327
+ // Match the routes
1328
+ pendingMatches = this.matchRoutes(next.pathname, next.search, {
1329
+ debug: true,
1330
+ })
1331
+
1332
+ // Ingest the new matches
1333
+ // If a cached moved to pendingMatches, remove it from cachedMatches
1334
+ this.__store.setState((s) => ({
1335
+ ...s,
1336
+ isLoading: true,
1337
+ location: next,
1338
+ pendingMatches,
1339
+ cachedMatches: s.cachedMatches.filter((d) => {
1340
+ return !pendingMatches.find((e) => e.id === d.id)
1341
+ }),
1342
+ }))
1343
+ })
1344
+
1345
+ try {
1346
+ try {
1347
+ // Load the matches
1348
+ await this.loadMatches({
1349
+ matches: pendingMatches,
1350
+ checkLatest: () => this.checkLatest(promise),
1351
+ invalidate: opts?.invalidate,
1352
+ })
1353
+ } catch (err) {
1354
+ // swallow this error, since we'll display the
1355
+ // errors on the route components
1356
+ }
1357
+
1358
+ // Only apply the latest transition
1359
+ if ((latestPromise = this.checkLatest(promise))) {
1360
+ return latestPromise
1361
+ }
1362
+
1363
+ const exitingMatches = previousMatches.filter(
1364
+ (match) => !pendingMatches.find((d) => d.id === match.id),
1365
+ )
1366
+ const enteringMatches = pendingMatches.filter(
1367
+ (match) => !previousMatches.find((d) => d.id === match.id),
1368
+ )
1369
+ const stayingMatches = previousMatches.filter((match) =>
1370
+ pendingMatches.find((d) => d.id === match.id),
1371
+ )
1372
+
1373
+ // Commit the pending matches. If a previous match was
1374
+ // removed, place it in the cachedMatches
1375
+ this.__store.setState((s) => ({
1376
+ ...s,
1377
+ isLoading: false,
1378
+ matches: pendingMatches,
1379
+ pendingMatches: undefined,
1380
+ cachedMatches: [
1381
+ ...s.cachedMatches,
1382
+ ...exitingMatches.filter((d) => d.status !== 'error'),
1383
+ ],
1384
+ }))
1385
+
1386
+ //
1387
+ ;(
1388
+ [
1389
+ [exitingMatches, 'onLeave'],
1390
+ [enteringMatches, 'onEnter'],
1391
+ [stayingMatches, 'onStay'],
1392
+ ] as const
1393
+ ).forEach(([matches, hook]) => {
1394
+ matches.forEach((match) => {
1395
+ this.looseRoutesById[match.routeId]!.options[hook]?.(match)
1396
+ })
1397
+ })
1398
+
1399
+ this.emit({
1400
+ type: 'onLoad',
1401
+ fromLocation: prevLocation,
1402
+ toLocation: next,
1403
+ pathChanged: pathDidChange,
1404
+ })
1405
+
1406
+ resolve()
1407
+ } catch (err) {
1408
+ // Only apply the latest transition
1409
+ if ((latestPromise = this.checkLatest(promise))) {
1410
+ return latestPromise
1411
+ }
1412
+
1413
+ reject(err)
1414
+ }
1415
+ })
1416
+
1417
+ this.latestLoadPromise = promise
1418
+
1419
+ return this.latestLoadPromise
1420
+ }
1421
+
1422
+ preloadRoute = async (
1423
+ navigateOpts: ToOptions<TRouteTree> = this.state.location as any,
1424
+ ) => {
1425
+ let next = this.buildLocation(navigateOpts as any)
1426
+
1427
+ let matches = this.matchRoutes(next.pathname, next.search, {
1428
+ throwOnError: true,
1429
+ })
1430
+
1431
+ const loadedMatchIds = Object.fromEntries(
1432
+ [
1433
+ ...this.state.matches,
1434
+ ...(this.state.pendingMatches ?? []),
1435
+ ...this.state.cachedMatches,
1436
+ ]?.map((d) => [d.id, true]),
1437
+ )
1438
+
1439
+ this.__store.batch(() => {
1440
+ matches.forEach((match) => {
1441
+ if (!loadedMatchIds[match.id]) {
1442
+ this.__store.setState((s) => ({
1443
+ ...s,
1444
+ cachedMatches: [...(s.cachedMatches as any), match],
1445
+ }))
1446
+ }
1447
+ })
1448
+ })
1449
+
1450
+ matches = await this.loadMatches({
1451
+ matches,
1452
+ preload: true,
1453
+ checkLatest: () => undefined,
1454
+ })
1455
+
1456
+ return matches
1457
+ }
1458
+
1459
+ matchRoute: MatchRouteFn<TRouteTree> = (location, opts) => {
1460
+ location = {
1461
+ ...location,
1462
+ to: location.to
1463
+ ? this.resolvePathWithBase((location.from || '') as string, location.to)
1464
+ : undefined,
1465
+ } as any
1466
+
1467
+ const next = this.buildLocation(location as any)
1468
+
1469
+ if (opts?.pending && this.state.status !== 'pending') {
1470
+ return false
1471
+ }
1472
+
1473
+ const baseLocation = opts?.pending
1474
+ ? this.latestLocation
1475
+ : this.state.resolvedLocation
1476
+
1477
+ if (!baseLocation) {
1478
+ return false
1479
+ }
1480
+
1481
+ const match = matchPathname(this.basepath, baseLocation.pathname, {
1482
+ ...opts,
1483
+ to: next.pathname,
1484
+ }) as any
1485
+
1486
+ if (!match) {
1487
+ return false
1488
+ }
1489
+
1490
+ if (match && (opts?.includeSearch ?? true)) {
1491
+ return deepEqual(baseLocation.search, next.search, true) ? match : false
1492
+ }
1493
+
1494
+ return match
1495
+ }
1496
+
1497
+ injectHtml = async (html: string | (() => Promise<string> | string)) => {
1498
+ this.injectedHtml.push(html)
1499
+ }
1500
+
1501
+ dehydrateData = <T>(key: any, getData: T | (() => Promise<T> | T)) => {
1502
+ if (typeof document === 'undefined') {
1503
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key)
1504
+
1505
+ this.injectHtml(async () => {
1506
+ const id = `__TSR_DEHYDRATED__${strKey}`
1507
+ const data =
1508
+ typeof getData === 'function' ? await (getData as any)() : getData
1509
+ return `<script id='${id}' suppressHydrationWarning>window["__TSR_DEHYDRATED__${escapeJSON(
1510
+ strKey,
1511
+ )}"] = ${JSON.stringify(data)}
1512
+ ;(() => {
1513
+ var el = document.getElementById('${id}')
1514
+ el.parentElement.removeChild(el)
1515
+ })()
1516
+ </script>`
1517
+ })
1518
+
1519
+ return () => this.hydrateData<T>(key)
1520
+ }
1521
+
1522
+ return () => undefined
1523
+ }
1524
+
1525
+ hydrateData = <T extends any = unknown>(key: any) => {
1526
+ if (typeof document !== 'undefined') {
1527
+ const strKey = typeof key === 'string' ? key : JSON.stringify(key)
1528
+
1529
+ return window[`__TSR_DEHYDRATED__${strKey}` as any] as T
1530
+ }
1531
+
1532
+ return undefined
1533
+ }
1534
+
1535
+ dehydrate = (): DehydratedRouter => {
1536
+ return {
1537
+ state: {
1538
+ dehydratedMatches: this.state.matches.map((d) =>
1539
+ pick(d, ['id', 'status', 'updatedAt', 'loaderData']),
1540
+ ),
1541
+ },
1542
+ }
1543
+ }
1544
+
1545
+ hydrate = async (__do_not_use_server_ctx?: HydrationCtx) => {
1546
+ let _ctx = __do_not_use_server_ctx
1547
+ // Client hydrates from window
1548
+ if (typeof document !== 'undefined') {
1549
+ _ctx = window.__TSR_DEHYDRATED__
1550
+ }
1551
+
1552
+ invariant(
1553
+ _ctx,
1554
+ 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?',
1555
+ )
1556
+
1557
+ const ctx = _ctx
1558
+ this.dehydratedData = ctx.payload as any
1559
+ this.options.hydrate?.(ctx.payload as any)
1560
+ const dehydratedState = ctx.router.state
1561
+
1562
+ let matches = this.matchRoutes(
1563
+ this.state.location.pathname,
1564
+ this.state.location.search,
1565
+ ).map((match) => {
1566
+ const dehydratedMatch = dehydratedState.dehydratedMatches.find(
1567
+ (d) => d.id === match.id,
1568
+ )
1569
+
1570
+ invariant(
1571
+ dehydratedMatch,
1572
+ `Could not find a client-side match for dehydrated match with id: ${match.id}!`,
1573
+ )
1574
+
1575
+ if (dehydratedMatch) {
1576
+ return {
1577
+ ...match,
1578
+ ...dehydratedMatch,
1579
+ }
1580
+ }
1581
+ return match
1582
+ })
1583
+
1584
+ this.__store.setState((s) => {
1585
+ return {
1586
+ ...s,
1587
+ matches: matches as any,
1588
+ }
1589
+ })
1590
+ }
1591
+
1592
+ // resolveMatchPromise = (matchId: string, key: string, value: any) => {
1593
+ // state.matches
1594
+ // .find((d) => d.id === matchId)
1595
+ // ?.__promisesByKey[key]?.resolve(value)
1596
+ // }
1597
+ }
1598
+
1599
+ // A function that takes an import() argument which is a function and returns a new function that will
1600
+ // proxy arguments from the caller to the imported function, retaining all type
1601
+ // information along the way
1602
+ export function lazyFn<
1603
+ T extends Record<string, (...args: any[]) => any>,
1604
+ TKey extends keyof T = 'default',
1605
+ >(fn: () => Promise<T>, key?: TKey) {
1606
+ return async (...args: Parameters<T[TKey]>): Promise<ReturnType<T[TKey]>> => {
1607
+ const imported = await fn()
1608
+ return imported[key || 'default'](...args)
1609
+ }
1610
+ }
1611
+
1612
+ export class SearchParamError extends Error {}
1613
+
1614
+ export class PathParamError extends Error {}
1615
+
1616
+ export function getInitialRouterState(
1617
+ location: ParsedLocation,
1618
+ ): RouterState<any> {
1619
+ return {
1620
+ isLoading: false,
1621
+ isTransitioning: false,
1622
+ status: 'idle',
1623
+ resolvedLocation: { ...location },
1624
+ location,
1625
+ matches: [],
1626
+ pendingMatches: [],
1627
+ cachedMatches: [],
1628
+ lastUpdated: Date.now(),
1629
+ }
1630
+ }