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