@tanstack/react-router 0.0.1-beta.27 → 0.0.1-beta.270

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