-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathload-matches.ts
More file actions
1282 lines (1129 loc) · 37 KB
/
load-matches.ts
File metadata and controls
1282 lines (1129 loc) · 37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { isServer } from '@tanstack/router-core/isServer'
import { invariant } from './invariant'
import { createControlledPromise, isPromise } from './utils'
import { isNotFound } from './not-found'
import { rootRouteId } from './root'
import { isRedirect } from './redirect'
import type { NotFoundError } from './not-found'
import type { ParsedLocation } from './location'
import type {
AnyRoute,
BeforeLoadContextOptions,
LoaderFnContext,
SsrContextOptions,
} from './route'
import type { AnyRouteMatch, MakeRouteMatch } from './Matches'
import type { AnyRouter, SSROption, UpdateMatchFn } from './router'
/**
* An object of this shape is created when calling `loadMatches`.
* It contains everything we need for all other functions in this file
* to work. (It's basically the function's argument, plus a few mutable states)
*/
type InnerLoadContext = {
/** the calling router instance */
router: AnyRouter
location: ParsedLocation
/** mutable state, scoped to a `loadMatches` call */
firstBadMatchIndex?: number
/** mutable state, scoped to a `loadMatches` call */
rendered?: boolean
serialError?: unknown
updateMatch: UpdateMatchFn
matches: Array<AnyRouteMatch>
preload?: boolean
forceStaleReload?: boolean
onReady?: () => Promise<void>
sync?: boolean
}
const triggerOnReady = (inner: InnerLoadContext): void | Promise<void> => {
if (!inner.rendered) {
inner.rendered = true
return inner.onReady?.()
}
}
const hasForcePendingActiveMatch = (router: AnyRouter): boolean => {
return router.stores.matchesId.state.some((matchId) => {
return router.stores.activeMatchStoresById.get(matchId)?.state._forcePending
})
}
const resolvePreload = (inner: InnerLoadContext, matchId: string): boolean => {
return !!(
inner.preload && !inner.router.stores.activeMatchStoresById.has(matchId)
)
}
/**
* Builds the accumulated context from router options and all matches up to (and optionally including) the given index.
* Merges __routeContext and __beforeLoadContext from each match.
*/
const buildMatchContext = (
inner: InnerLoadContext,
index: number,
includeCurrentMatch: boolean = true,
): Record<string, unknown> => {
const context: Record<string, unknown> = {
...(inner.router.options.context ?? {}),
}
const end = includeCurrentMatch ? index : index - 1
for (let i = 0; i <= end; i++) {
const innerMatch = inner.matches[i]
if (!innerMatch) continue
const m = inner.router.getMatch(innerMatch.id)
if (!m) continue
Object.assign(context, m.__routeContext, m.__beforeLoadContext)
}
return context
}
const getNotFoundBoundaryIndex = (
inner: InnerLoadContext,
err: NotFoundError,
): number | undefined => {
if (!inner.matches.length) {
return undefined
}
const requestedRouteId = err.routeId
const matchedRootIndex = inner.matches.findIndex(
(m) => m.routeId === inner.router.routeTree.id,
)
const rootIndex = matchedRootIndex >= 0 ? matchedRootIndex : 0
let startIndex = requestedRouteId
? inner.matches.findIndex((match) => match.routeId === requestedRouteId)
: (inner.firstBadMatchIndex ?? inner.matches.length - 1)
if (startIndex < 0) {
startIndex = rootIndex
}
for (let i = startIndex; i >= 0; i--) {
const match = inner.matches[i]!
const route = inner.router.looseRoutesById[match.routeId]!
if (route.options.notFoundComponent) {
return i
}
}
// If no boundary component is found, preserve explicit routeId targeting behavior,
// otherwise default to root for untargeted notFounds.
return requestedRouteId ? startIndex : rootIndex
}
const handleRedirectAndNotFound = (
inner: InnerLoadContext,
match: AnyRouteMatch | undefined,
err: unknown,
): void => {
if (!isRedirect(err) && !isNotFound(err)) return
if (isRedirect(err) && err.redirectHandled && !err.options.reloadDocument) {
throw err
}
// in case of a redirecting match during preload, the match does not exist
if (match) {
match._nonReactive.beforeLoadPromise?.resolve()
match._nonReactive.loaderPromise?.resolve()
match._nonReactive.beforeLoadPromise = undefined
match._nonReactive.loaderPromise = undefined
match._nonReactive.error = err
inner.updateMatch(match.id, (prev) => ({
...prev,
status: isRedirect(err)
? 'redirected'
: prev.status === 'pending'
? 'success'
: prev.status,
context: buildMatchContext(inner, match.index),
isFetching: false,
error: err,
}))
if (isNotFound(err) && !err.routeId) {
// Stamp the throwing match's routeId so that the finalization step in
// loadMatches knows where the notFound originated. The actual boundary
// resolution (walking up to the nearest notFoundComponent) is deferred to
// the finalization step, where firstBadMatchIndex is stable and
// headMaxIndex can be capped correctly.
err.routeId = match.routeId
}
match._nonReactive.loadPromise?.resolve()
}
if (isRedirect(err)) {
inner.rendered = true
err.options._fromLocation = inner.location
err.redirectHandled = true
err = inner.router.resolveRedirect(err)
}
throw err
}
const shouldSkipLoader = (
inner: InnerLoadContext,
matchId: string,
): boolean => {
const match = inner.router.getMatch(matchId)
if (!match) {
return true
}
// upon hydration, we skip the loader if the match has been dehydrated on the server
if (!(isServer ?? inner.router.isServer) && match._nonReactive.dehydrated) {
return true
}
if ((isServer ?? inner.router.isServer) && match.ssr === false) {
return true
}
return false
}
const syncMatchContext = (
inner: InnerLoadContext,
matchId: string,
index: number,
): void => {
const nextContext = buildMatchContext(inner, index)
inner.updateMatch(matchId, (prev) => {
return {
...prev,
context: nextContext,
}
})
}
const handleSerialError = (
inner: InnerLoadContext,
index: number,
err: any,
routerCode: string,
): void => {
const { id: matchId, routeId } = inner.matches[index]!
const route = inner.router.looseRoutesById[routeId]!
// Much like suspense, we use a promise here to know if
// we've been outdated by a new loadMatches call and
// should abort the current async operation
if (err instanceof Promise) {
throw err
}
err.routerCode = routerCode
inner.firstBadMatchIndex ??= index
handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err)
try {
route.options.onError?.(err)
} catch (errorHandlerErr) {
err = errorHandlerErr
handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err)
}
inner.updateMatch(matchId, (prev) => {
prev._nonReactive.beforeLoadPromise?.resolve()
prev._nonReactive.beforeLoadPromise = undefined
prev._nonReactive.loadPromise?.resolve()
return {
...prev,
error: err,
status: 'error',
isFetching: false,
updatedAt: Date.now(),
abortController: new AbortController(),
}
})
if (!inner.preload && !isRedirect(err) && !isNotFound(err)) {
inner.serialError ??= err
}
}
const isBeforeLoadSsr = (
inner: InnerLoadContext,
matchId: string,
index: number,
route: AnyRoute,
): void | Promise<void> => {
const existingMatch = inner.router.getMatch(matchId)!
const parentMatchId = inner.matches[index - 1]?.id
const parentMatch = parentMatchId
? inner.router.getMatch(parentMatchId)!
: undefined
// in SPA mode, only SSR the root route
if (inner.router.isShell()) {
existingMatch.ssr = route.id === rootRouteId
return
}
if (parentMatch?.ssr === false) {
existingMatch.ssr = false
return
}
const parentOverride = (tempSsr: SSROption) => {
if (tempSsr === true && parentMatch?.ssr === 'data-only') {
return 'data-only'
}
return tempSsr
}
const defaultSsr = inner.router.options.defaultSsr ?? true
if (route.options.ssr === undefined) {
existingMatch.ssr = parentOverride(defaultSsr)
return
}
if (typeof route.options.ssr !== 'function') {
existingMatch.ssr = parentOverride(route.options.ssr)
return
}
const { search, params } = existingMatch
const ssrFnContext: SsrContextOptions<any, any, any> = {
search: makeMaybe(search, existingMatch.searchError),
params: makeMaybe(params, existingMatch.paramsError),
location: inner.location,
matches: inner.matches.map((match) => ({
index: match.index,
pathname: match.pathname,
fullPath: match.fullPath,
staticData: match.staticData,
id: match.id,
routeId: match.routeId,
search: makeMaybe(match.search, match.searchError),
params: makeMaybe(match.params, match.paramsError),
ssr: match.ssr,
})),
}
const tempSsr = route.options.ssr(ssrFnContext)
if (isPromise(tempSsr)) {
return tempSsr.then((ssr) => {
existingMatch.ssr = parentOverride(ssr ?? defaultSsr)
})
}
existingMatch.ssr = parentOverride(tempSsr ?? defaultSsr)
return
}
const setupPendingTimeout = (
inner: InnerLoadContext,
matchId: string,
route: AnyRoute,
match: AnyRouteMatch,
): void => {
if (match._nonReactive.pendingTimeout !== undefined) return
const pendingMs =
route.options.pendingMs ?? inner.router.options.defaultPendingMs
const shouldPending = !!(
inner.onReady &&
!(isServer ?? inner.router.isServer) &&
!resolvePreload(inner, matchId) &&
(route.options.loader ||
route.options.beforeLoad ||
routeNeedsPreload(route)) &&
typeof pendingMs === 'number' &&
pendingMs !== Infinity &&
(route.options.pendingComponent ??
(inner.router.options as any)?.defaultPendingComponent)
)
if (shouldPending) {
const pendingTimeout = setTimeout(() => {
// Update the match and prematurely resolve the loadMatches promise so that
// the pending component can start rendering
triggerOnReady(inner)
}, pendingMs)
match._nonReactive.pendingTimeout = pendingTimeout
}
}
const preBeforeLoadSetup = (
inner: InnerLoadContext,
matchId: string,
route: AnyRoute,
): void | Promise<void> => {
const existingMatch = inner.router.getMatch(matchId)!
// If we are in the middle of a load, either of these will be present
// (not to be confused with `loadPromise`, which is always defined)
if (
!existingMatch._nonReactive.beforeLoadPromise &&
!existingMatch._nonReactive.loaderPromise
)
return
setupPendingTimeout(inner, matchId, route, existingMatch)
const then = () => {
const match = inner.router.getMatch(matchId)!
if (
match.preload &&
(match.status === 'redirected' || match.status === 'notFound')
) {
handleRedirectAndNotFound(inner, match, match.error)
}
}
// Wait for the previous beforeLoad to resolve before we continue
return existingMatch._nonReactive.beforeLoadPromise
? existingMatch._nonReactive.beforeLoadPromise.then(then)
: then()
}
const executeBeforeLoad = (
inner: InnerLoadContext,
matchId: string,
index: number,
route: AnyRoute,
): void | Promise<void> => {
const match = inner.router.getMatch(matchId)!
// explicitly capture the previous loadPromise
let prevLoadPromise = match._nonReactive.loadPromise
match._nonReactive.loadPromise = createControlledPromise<void>(() => {
prevLoadPromise?.resolve()
prevLoadPromise = undefined
})
const { paramsError, searchError } = match
if (paramsError) {
handleSerialError(inner, index, paramsError, 'PARSE_PARAMS')
}
if (searchError) {
handleSerialError(inner, index, searchError, 'VALIDATE_SEARCH')
}
setupPendingTimeout(inner, matchId, route, match)
const abortController = new AbortController()
let isPending = false
const pending = () => {
if (isPending) return
isPending = true
inner.updateMatch(matchId, (prev) => ({
...prev,
isFetching: 'beforeLoad',
fetchCount: prev.fetchCount + 1,
abortController,
// Note: We intentionally don't update context here.
// Context should only be updated after beforeLoad resolves to avoid
// components seeing incomplete context during async beforeLoad execution.
}))
}
const resolve = () => {
match._nonReactive.beforeLoadPromise?.resolve()
match._nonReactive.beforeLoadPromise = undefined
inner.updateMatch(matchId, (prev) => ({
...prev,
isFetching: false,
}))
}
// if there is no `beforeLoad` option, just mark as pending and resolve
// Context will be updated later in loadRouteMatch after loader completes
if (!route.options.beforeLoad) {
inner.router.batch(() => {
pending()
resolve()
})
return
}
match._nonReactive.beforeLoadPromise = createControlledPromise<void>()
// Build context from all parent matches, excluding current match's __beforeLoadContext
// (since we're about to execute beforeLoad for this match)
const context = {
...buildMatchContext(inner, index, false),
...match.__routeContext,
}
const { search, params, cause } = match
const preload = resolvePreload(inner, matchId)
const beforeLoadFnContext: BeforeLoadContextOptions<
any,
any,
any,
any,
any,
any,
any,
any,
any
> = {
search,
abortController,
params,
preload,
context,
location: inner.location,
navigate: (opts: any) =>
inner.router.navigate({
...opts,
_fromLocation: inner.location,
}),
buildLocation: inner.router.buildLocation,
cause: preload ? 'preload' : cause,
matches: inner.matches,
routeId: route.id,
...inner.router.options.additionalContext,
}
const updateContext = (beforeLoadContext: any) => {
if (beforeLoadContext === undefined) {
inner.router.batch(() => {
pending()
resolve()
})
return
}
if (isRedirect(beforeLoadContext) || isNotFound(beforeLoadContext)) {
pending()
handleSerialError(inner, index, beforeLoadContext, 'BEFORE_LOAD')
}
inner.router.batch(() => {
pending()
inner.updateMatch(matchId, (prev) => ({
...prev,
__beforeLoadContext: beforeLoadContext,
}))
resolve()
})
}
let beforeLoadContext
try {
beforeLoadContext = route.options.beforeLoad(beforeLoadFnContext)
if (isPromise(beforeLoadContext)) {
pending()
return beforeLoadContext
.catch((err) => {
handleSerialError(inner, index, err, 'BEFORE_LOAD')
})
.then(updateContext)
}
} catch (err) {
pending()
handleSerialError(inner, index, err, 'BEFORE_LOAD')
}
updateContext(beforeLoadContext)
return
}
const handleBeforeLoad = (
inner: InnerLoadContext,
index: number,
): void | Promise<void> => {
const { id: matchId, routeId } = inner.matches[index]!
const route = inner.router.looseRoutesById[routeId]!
const serverSsr = () => {
// on the server, determine whether SSR the current match or not
if (isServer ?? inner.router.isServer) {
const maybePromise = isBeforeLoadSsr(inner, matchId, index, route)
if (isPromise(maybePromise)) return maybePromise.then(queueExecution)
}
return queueExecution()
}
const execute = () => executeBeforeLoad(inner, matchId, index, route)
const queueExecution = () => {
if (shouldSkipLoader(inner, matchId)) return
const result = preBeforeLoadSetup(inner, matchId, route)
return isPromise(result) ? result.then(execute) : execute()
}
return serverSsr()
}
const executeHead = (
inner: InnerLoadContext,
matchId: string,
route: AnyRoute,
): void | Promise<
Pick<
AnyRouteMatch,
'meta' | 'links' | 'headScripts' | 'headers' | 'scripts' | 'styles'
>
> => {
const match = inner.router.getMatch(matchId)
// in case of a redirecting match during preload, the match does not exist
if (!match) {
return
}
if (!route.options.head && !route.options.scripts && !route.options.headers) {
return
}
const assetContext = {
ssr: inner.router.options.ssr,
matches: inner.matches,
match,
params: match.params,
loaderData: match.loaderData,
}
return Promise.all([
route.options.head?.(assetContext),
route.options.scripts?.(assetContext),
route.options.headers?.(assetContext),
]).then(([headFnContent, scripts, headers]) => {
const meta = headFnContent?.meta
const links = headFnContent?.links
const headScripts = headFnContent?.scripts
const styles = headFnContent?.styles
return {
meta,
links,
headScripts,
headers,
scripts,
styles,
}
})
}
const getLoaderContext = (
inner: InnerLoadContext,
matchPromises: Array<Promise<AnyRouteMatch>>,
matchId: string,
index: number,
route: AnyRoute,
): LoaderFnContext => {
const parentMatchPromise = matchPromises[index - 1] as any
const { params, loaderDeps, abortController, cause } =
inner.router.getMatch(matchId)!
const context = buildMatchContext(inner, index)
const preload = resolvePreload(inner, matchId)
return {
params,
deps: loaderDeps,
preload: !!preload,
parentMatchPromise,
abortController,
context,
location: inner.location,
navigate: (opts) =>
inner.router.navigate({
...opts,
_fromLocation: inner.location,
}),
cause: preload ? 'preload' : cause,
route,
...inner.router.options.additionalContext,
}
}
const runLoader = async (
inner: InnerLoadContext,
matchPromises: Array<Promise<AnyRouteMatch>>,
matchId: string,
index: number,
route: AnyRoute,
): Promise<void> => {
try {
// If the Matches component rendered
// the pending component and needs to show it for
// a minimum duration, we''ll wait for it to resolve
// before committing to the match and resolving
// the loadPromise
const match = inner.router.getMatch(matchId)!
// Actually run the loader and handle the result
try {
if (!(isServer ?? inner.router.isServer) || match.ssr === true) {
loadRouteChunk(route)
}
// Kick off the loader!
const routeLoader = route.options.loader
const loader =
typeof routeLoader === 'function' ? routeLoader : routeLoader?.handler
const loaderResult = loader?.(
getLoaderContext(inner, matchPromises, matchId, index, route),
)
const loaderResultIsPromise = !!loader && isPromise(loaderResult)
const willLoadSomething = !!(
loaderResultIsPromise ||
route._lazyPromise ||
route._componentsPromise ||
route.options.head ||
route.options.scripts ||
route.options.headers ||
match._nonReactive.minPendingPromise
)
if (willLoadSomething) {
inner.updateMatch(matchId, (prev) => ({
...prev,
isFetching: 'loader',
}))
}
if (loader) {
const loaderData = loaderResultIsPromise
? await loaderResult
: loaderResult
handleRedirectAndNotFound(
inner,
inner.router.getMatch(matchId),
loaderData,
)
if (loaderData !== undefined) {
inner.updateMatch(matchId, (prev) => ({
...prev,
loaderData,
}))
}
}
// Lazy option can modify the route options,
// so we need to wait for it to resolve before
// we can use the options
if (route._lazyPromise) await route._lazyPromise
const pendingPromise = match._nonReactive.minPendingPromise
if (pendingPromise) await pendingPromise
// Last but not least, wait for the the components
// to be preloaded before we resolve the match
if (route._componentsPromise) await route._componentsPromise
inner.updateMatch(matchId, (prev) => ({
...prev,
error: undefined,
context: buildMatchContext(inner, index),
status: 'success',
isFetching: false,
updatedAt: Date.now(),
}))
} catch (e) {
let error = e
if ((error as any)?.name === 'AbortError') {
if (match.abortController.signal.aborted) {
match._nonReactive.loaderPromise?.resolve()
match._nonReactive.loaderPromise = undefined
return
}
inner.updateMatch(matchId, (prev) => ({
...prev,
status: prev.status === 'pending' ? 'success' : prev.status,
isFetching: false,
context: buildMatchContext(inner, index),
}))
return
}
const pendingPromise = match._nonReactive.minPendingPromise
if (pendingPromise) await pendingPromise
if (isNotFound(e)) {
await (route.options.notFoundComponent as any)?.preload?.()
}
handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), e)
try {
route.options.onError?.(e)
} catch (onErrorError) {
error = onErrorError
handleRedirectAndNotFound(
inner,
inner.router.getMatch(matchId),
onErrorError,
)
}
if (!isRedirect(error) && !isNotFound(error)) {
await loadRouteChunk(route, ['errorComponent'])
}
inner.updateMatch(matchId, (prev) => ({
...prev,
error,
context: buildMatchContext(inner, index),
status: 'error',
isFetching: false,
}))
}
} catch (err) {
const match = inner.router.getMatch(matchId)
// in case of a redirecting match during preload, the match does not exist
if (match) {
match._nonReactive.loaderPromise = undefined
}
handleRedirectAndNotFound(inner, match, err)
}
}
const loadRouteMatch = async (
inner: InnerLoadContext,
matchPromises: Array<Promise<AnyRouteMatch>>,
index: number,
): Promise<AnyRouteMatch> => {
async function handleLoader(
preload: boolean,
prevMatch: AnyRouteMatch,
previousRouteMatchId: string | undefined,
match: AnyRouteMatch,
route: AnyRoute,
) {
const age = Date.now() - prevMatch.updatedAt
const staleAge = preload
? (route.options.preloadStaleTime ??
inner.router.options.defaultPreloadStaleTime ??
30_000) // 30 seconds for preloads by default
: (route.options.staleTime ?? inner.router.options.defaultStaleTime ?? 0)
const shouldReloadOption = route.options.shouldReload
// Default to reloading the route all the time
// Allow shouldReload to get the last say,
// if provided.
const shouldReload =
typeof shouldReloadOption === 'function'
? shouldReloadOption(
getLoaderContext(inner, matchPromises, matchId, index, route),
)
: shouldReloadOption
// If the route is successful and still fresh, just resolve
const { status, invalid } = match
const staleMatchShouldReload =
age >= staleAge &&
(!!inner.forceStaleReload ||
match.cause === 'enter' ||
(previousRouteMatchId !== undefined &&
previousRouteMatchId !== match.id))
loaderShouldRunAsync =
status === 'success' &&
(invalid || (shouldReload ?? staleMatchShouldReload))
if (preload && route.options.preload === false) {
// Do nothing
} else if (
loaderShouldRunAsync &&
!inner.sync &&
shouldReloadInBackground
) {
loaderIsRunningAsync = true
;(async () => {
try {
await runLoader(inner, matchPromises, matchId, index, route)
const match = inner.router.getMatch(matchId)!
match._nonReactive.loaderPromise?.resolve()
if (match.status !== 'pending') {
match._nonReactive.loadPromise?.resolve()
}
match._nonReactive.loaderPromise = undefined
} catch (err) {
if (isRedirect(err)) {
await inner.router.navigate(err.options)
}
}
})()
} else if (status !== 'success' || loaderShouldRunAsync) {
await runLoader(inner, matchPromises, matchId, index, route)
} else {
syncMatchContext(inner, matchId, index)
}
}
const { id: matchId, routeId } = inner.matches[index]!
let loaderShouldRunAsync = false
let loaderIsRunningAsync = false
const route = inner.router.looseRoutesById[routeId]!
const routeLoader = route.options.loader
const shouldReloadInBackground =
((typeof routeLoader === 'function'
? undefined
: routeLoader?.staleReloadMode) ??
inner.router.options.defaultStaleReloadMode) !== 'blocking'
if (shouldSkipLoader(inner, matchId)) {
const match = inner.router.getMatch(matchId)
if (!match) {
return inner.matches[index]!
}
syncMatchContext(inner, matchId, index)
if (isServer ?? inner.router.isServer) {
return inner.router.getMatch(matchId)!
}
} else {
const prevMatch = inner.router.getMatch(matchId)! // This is where all of the stale-while-revalidate magic happens
const activeIdAtIndex = inner.router.stores.matchesId.state[index]
const activeAtIndex =
(activeIdAtIndex &&
inner.router.stores.activeMatchStoresById.get(activeIdAtIndex)) ||
null
const previousRouteMatchId =
activeAtIndex?.routeId === routeId
? activeIdAtIndex
: inner.router.stores.activeMatchesSnapshot.state.find(
(d) => d.routeId === routeId,
)?.id
const preload = resolvePreload(inner, matchId)
// there is a loaderPromise, so we are in the middle of a load
if (prevMatch._nonReactive.loaderPromise) {
// do not block if we already have stale data we can show
// but only if the ongoing load is not a preload since error handling is different for preloads
// and we don't want to swallow errors
if (
prevMatch.status === 'success' &&
!inner.sync &&
!prevMatch.preload &&
shouldReloadInBackground
) {
return prevMatch
}
await prevMatch._nonReactive.loaderPromise
const match = inner.router.getMatch(matchId)!
const error = match._nonReactive.error || match.error
if (error) {
handleRedirectAndNotFound(inner, match, error)
}
if (match.status === 'pending') {
await handleLoader(
preload,
prevMatch,
previousRouteMatchId,
match,
route,
)
}
} else {
const nextPreload =
preload && !inner.router.stores.activeMatchStoresById.has(matchId)
const match = inner.router.getMatch(matchId)!
match._nonReactive.loaderPromise = createControlledPromise<void>()
if (nextPreload !== match.preload) {
inner.updateMatch(matchId, (prev) => ({
...prev,
preload: nextPreload,
}))
}
await handleLoader(preload, prevMatch, previousRouteMatchId, match, route)
}
}
const match = inner.router.getMatch(matchId)!
if (!loaderIsRunningAsync) {
match._nonReactive.loaderPromise?.resolve()
if (match.status !== 'pending') {
match._nonReactive.loadPromise?.resolve()
}
}
clearTimeout(match._nonReactive.pendingTimeout)
match._nonReactive.pendingTimeout = undefined
if (!loaderIsRunningAsync) match._nonReactive.loaderPromise = undefined
match._nonReactive.dehydrated = undefined
const nextIsFetching = loaderIsRunningAsync ? match.isFetching : false
if (nextIsFetching !== match.isFetching || match.invalid !== false) {
inner.updateMatch(matchId, (prev) => ({
...prev,
isFetching: nextIsFetching,
invalid: false,
}))
return inner.router.getMatch(matchId)!
} else {
return match
}
}
export async function loadMatches(arg: {
router: AnyRouter
location: ParsedLocation
matches: Array<AnyRouteMatch>
preload?: boolean
forceStaleReload?: boolean
onReady?: () => Promise<void>
updateMatch: UpdateMatchFn
sync?: boolean
}): Promise<Array<MakeRouteMatch>> {
const inner: InnerLoadContext = arg
const matchPromises: Array<Promise<AnyRouteMatch>> = []
// make sure the pending component is immediately rendered when hydrating a match that is not SSRed
// the pending component was already rendered on the server and we want to keep it shown on the client until minPendingMs is reached
if (
!(isServer ?? inner.router.isServer) &&
hasForcePendingActiveMatch(inner.router)
) {
triggerOnReady(inner)
}
let beforeLoadNotFound: NotFoundError | undefined
// Execute all beforeLoads one by one
for (let i = 0; i < inner.matches.length; i++) {
try {
const beforeLoad = handleBeforeLoad(inner, i)
if (isPromise(beforeLoad)) await beforeLoad
} catch (err) {
if (isRedirect(err)) {
throw err
}
if (isNotFound(err)) {
beforeLoadNotFound = err