@tanstack/router-core 1.163.3 → 1.166.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"load-matches.js","sources":["../../src/load-matches.ts"],"sourcesContent":["import invariant from 'tiny-invariant'\nimport { isServer } from '@tanstack/router-core/isServer'\nimport { batch } from './utils/batch'\nimport { createControlledPromise, isPromise } from './utils'\nimport { isNotFound } from './not-found'\nimport { rootRouteId } from './root'\nimport { isRedirect } from './redirect'\nimport type { NotFoundError } from './not-found'\nimport type { ParsedLocation } from './location'\nimport type {\n AnyRoute,\n BeforeLoadContextOptions,\n LoaderFnContext,\n SsrContextOptions,\n} from './route'\nimport type { AnyRouteMatch, MakeRouteMatch } from './Matches'\nimport type { AnyRouter, SSROption, UpdateMatchFn } from './router'\n\n/**\n * An object of this shape is created when calling `loadMatches`.\n * It contains everything we need for all other functions in this file\n * to work. (It's basically the function's argument, plus a few mutable states)\n */\ntype InnerLoadContext = {\n /** the calling router instance */\n router: AnyRouter\n location: ParsedLocation\n /** mutable state, scoped to a `loadMatches` call */\n firstBadMatchIndex?: number\n /** mutable state, scoped to a `loadMatches` call */\n rendered?: boolean\n updateMatch: UpdateMatchFn\n matches: Array<AnyRouteMatch>\n preload?: boolean\n onReady?: () => Promise<void>\n sync?: boolean\n /** mutable state, scoped to a `loadMatches` call */\n matchPromises: Array<Promise<AnyRouteMatch>>\n}\n\nconst triggerOnReady = (inner: InnerLoadContext): void | Promise<void> => {\n if (!inner.rendered) {\n inner.rendered = true\n return inner.onReady?.()\n }\n}\n\nconst resolvePreload = (inner: InnerLoadContext, matchId: string): boolean => {\n return !!(\n inner.preload && !inner.router.state.matches.some((d) => d.id === matchId)\n )\n}\n\n/**\n * Builds the accumulated context from router options and all matches up to (and optionally including) the given index.\n * Merges __routeContext and __beforeLoadContext from each match.\n */\nconst buildMatchContext = (\n inner: InnerLoadContext,\n index: number,\n includeCurrentMatch: boolean = true,\n): Record<string, unknown> => {\n const context: Record<string, unknown> = {\n ...(inner.router.options.context ?? {}),\n }\n const end = includeCurrentMatch ? index : index - 1\n for (let i = 0; i <= end; i++) {\n const innerMatch = inner.matches[i]\n if (!innerMatch) continue\n const m = inner.router.getMatch(innerMatch.id)\n if (!m) continue\n Object.assign(context, m.__routeContext, m.__beforeLoadContext)\n }\n return context\n}\n\nconst _handleNotFound = (\n inner: InnerLoadContext,\n err: NotFoundError,\n routerCode?: string,\n) => {\n // Find the route that should handle the not found error\n // First check if a specific route is requested to show the error\n const routeCursor =\n inner.router.routesById[err.routeId ?? ''] ?? inner.router.routeTree\n\n // Ensure a NotFoundComponent exists on the route\n if (\n !routeCursor.options.notFoundComponent &&\n (inner.router.options as any)?.defaultNotFoundComponent\n ) {\n routeCursor.options.notFoundComponent = (\n inner.router.options as any\n ).defaultNotFoundComponent\n }\n\n // For BEFORE_LOAD errors that will walk up to a parent route,\n // don't require notFoundComponent on the current (child) route —\n // an ancestor will handle it. Only enforce the invariant when\n // we've reached a route that won't walk up further.\n const willWalkUp = routerCode === 'BEFORE_LOAD' && routeCursor.parentRoute\n\n if (!willWalkUp) {\n // Ensure we have a notFoundComponent\n invariant(\n routeCursor.options.notFoundComponent,\n 'No notFoundComponent found. Please set a notFoundComponent on your route or provide a defaultNotFoundComponent to the router.',\n )\n }\n\n // Find the match for this route\n const matchForRoute = inner.matches.find((m) => m.routeId === routeCursor.id)\n\n invariant(matchForRoute, 'Could not find match for route: ' + routeCursor.id)\n\n // Assign the error to the match - using non-null assertion since we've checked with invariant\n inner.updateMatch(matchForRoute.id, (prev) => ({\n ...prev,\n status: 'notFound',\n error: err,\n isFetching: false,\n }))\n\n if (willWalkUp) {\n err.routeId = routeCursor.parentRoute!.id\n _handleNotFound(inner, err, routerCode)\n }\n}\n\nconst handleRedirectAndNotFound = (\n inner: InnerLoadContext,\n match: AnyRouteMatch | undefined,\n err: unknown,\n routerCode?: string,\n): void => {\n if (!isRedirect(err) && !isNotFound(err)) return\n\n if (isRedirect(err) && err.redirectHandled && !err.options.reloadDocument) {\n throw err\n }\n\n // in case of a redirecting match during preload, the match does not exist\n if (match) {\n match._nonReactive.beforeLoadPromise?.resolve()\n match._nonReactive.loaderPromise?.resolve()\n match._nonReactive.beforeLoadPromise = undefined\n match._nonReactive.loaderPromise = undefined\n\n const status = isRedirect(err) ? 'redirected' : 'notFound'\n\n match._nonReactive.error = err\n\n inner.updateMatch(match.id, (prev) => ({\n ...prev,\n status,\n context: buildMatchContext(inner, match.index),\n isFetching: false,\n error: err,\n }))\n\n if (isNotFound(err) && !err.routeId) {\n err.routeId = match.routeId\n }\n\n match._nonReactive.loadPromise?.resolve()\n }\n\n if (isRedirect(err)) {\n inner.rendered = true\n err.options._fromLocation = inner.location\n err.redirectHandled = true\n err = inner.router.resolveRedirect(err)\n throw err\n } else {\n _handleNotFound(inner, err, routerCode)\n throw err\n }\n}\n\nconst shouldSkipLoader = (\n inner: InnerLoadContext,\n matchId: string,\n): boolean => {\n const match = inner.router.getMatch(matchId)!\n // upon hydration, we skip the loader if the match has been dehydrated on the server\n if (!(isServer ?? inner.router.isServer) && match._nonReactive.dehydrated) {\n return true\n }\n\n if ((isServer ?? inner.router.isServer) && match.ssr === false) {\n return true\n }\n\n return false\n}\n\nconst handleSerialError = (\n inner: InnerLoadContext,\n index: number,\n err: any,\n routerCode: string,\n): void => {\n const { id: matchId, routeId } = inner.matches[index]!\n const route = inner.router.looseRoutesById[routeId]!\n\n // Much like suspense, we use a promise here to know if\n // we've been outdated by a new loadMatches call and\n // should abort the current async operation\n if (err instanceof Promise) {\n throw err\n }\n\n err.routerCode = routerCode\n inner.firstBadMatchIndex ??= index\n handleRedirectAndNotFound(\n inner,\n inner.router.getMatch(matchId),\n err,\n routerCode,\n )\n\n try {\n route.options.onError?.(err)\n } catch (errorHandlerErr) {\n err = errorHandlerErr\n handleRedirectAndNotFound(\n inner,\n inner.router.getMatch(matchId),\n err,\n routerCode,\n )\n }\n\n inner.updateMatch(matchId, (prev) => {\n prev._nonReactive.beforeLoadPromise?.resolve()\n prev._nonReactive.beforeLoadPromise = undefined\n prev._nonReactive.loadPromise?.resolve()\n\n return {\n ...prev,\n error: err,\n status: 'error',\n isFetching: false,\n updatedAt: Date.now(),\n abortController: new AbortController(),\n }\n })\n}\n\nconst isBeforeLoadSsr = (\n inner: InnerLoadContext,\n matchId: string,\n index: number,\n route: AnyRoute,\n): void | Promise<void> => {\n const existingMatch = inner.router.getMatch(matchId)!\n const parentMatchId = inner.matches[index - 1]?.id\n const parentMatch = parentMatchId\n ? inner.router.getMatch(parentMatchId)!\n : undefined\n\n // in SPA mode, only SSR the root route\n if (inner.router.isShell()) {\n existingMatch.ssr = route.id === rootRouteId\n return\n }\n\n if (parentMatch?.ssr === false) {\n existingMatch.ssr = false\n return\n }\n\n const parentOverride = (tempSsr: SSROption) => {\n if (tempSsr === true && parentMatch?.ssr === 'data-only') {\n return 'data-only'\n }\n return tempSsr\n }\n\n const defaultSsr = inner.router.options.defaultSsr ?? true\n\n if (route.options.ssr === undefined) {\n existingMatch.ssr = parentOverride(defaultSsr)\n return\n }\n\n if (typeof route.options.ssr !== 'function') {\n existingMatch.ssr = parentOverride(route.options.ssr)\n return\n }\n const { search, params } = existingMatch\n\n const ssrFnContext: SsrContextOptions<any, any, any> = {\n search: makeMaybe(search, existingMatch.searchError),\n params: makeMaybe(params, existingMatch.paramsError),\n location: inner.location,\n matches: inner.matches.map((match) => ({\n index: match.index,\n pathname: match.pathname,\n fullPath: match.fullPath,\n staticData: match.staticData,\n id: match.id,\n routeId: match.routeId,\n search: makeMaybe(match.search, match.searchError),\n params: makeMaybe(match.params, match.paramsError),\n ssr: match.ssr,\n })),\n }\n\n const tempSsr = route.options.ssr(ssrFnContext)\n if (isPromise(tempSsr)) {\n return tempSsr.then((ssr) => {\n existingMatch.ssr = parentOverride(ssr ?? defaultSsr)\n })\n }\n\n existingMatch.ssr = parentOverride(tempSsr ?? defaultSsr)\n return\n}\n\nconst setupPendingTimeout = (\n inner: InnerLoadContext,\n matchId: string,\n route: AnyRoute,\n match: AnyRouteMatch,\n): void => {\n if (match._nonReactive.pendingTimeout !== undefined) return\n\n const pendingMs =\n route.options.pendingMs ?? inner.router.options.defaultPendingMs\n const shouldPending = !!(\n inner.onReady &&\n !(isServer ?? inner.router.isServer) &&\n !resolvePreload(inner, matchId) &&\n (route.options.loader ||\n route.options.beforeLoad ||\n routeNeedsPreload(route)) &&\n typeof pendingMs === 'number' &&\n pendingMs !== Infinity &&\n (route.options.pendingComponent ??\n (inner.router.options as any)?.defaultPendingComponent)\n )\n\n if (shouldPending) {\n const pendingTimeout = setTimeout(() => {\n // Update the match and prematurely resolve the loadMatches promise so that\n // the pending component can start rendering\n triggerOnReady(inner)\n }, pendingMs)\n match._nonReactive.pendingTimeout = pendingTimeout\n }\n}\n\nconst preBeforeLoadSetup = (\n inner: InnerLoadContext,\n matchId: string,\n route: AnyRoute,\n): void | Promise<void> => {\n const existingMatch = inner.router.getMatch(matchId)!\n\n // If we are in the middle of a load, either of these will be present\n // (not to be confused with `loadPromise`, which is always defined)\n if (\n !existingMatch._nonReactive.beforeLoadPromise &&\n !existingMatch._nonReactive.loaderPromise\n )\n return\n\n setupPendingTimeout(inner, matchId, route, existingMatch)\n\n const then = () => {\n const match = inner.router.getMatch(matchId)!\n if (\n match.preload &&\n (match.status === 'redirected' || match.status === 'notFound')\n ) {\n handleRedirectAndNotFound(inner, match, match.error)\n }\n }\n\n // Wait for the previous beforeLoad to resolve before we continue\n return existingMatch._nonReactive.beforeLoadPromise\n ? existingMatch._nonReactive.beforeLoadPromise.then(then)\n : then()\n}\n\nconst executeBeforeLoad = (\n inner: InnerLoadContext,\n matchId: string,\n index: number,\n route: AnyRoute,\n): void | Promise<void> => {\n const match = inner.router.getMatch(matchId)!\n\n // explicitly capture the previous loadPromise\n const prevLoadPromise = match._nonReactive.loadPromise\n match._nonReactive.loadPromise = createControlledPromise<void>(() => {\n prevLoadPromise?.resolve()\n })\n\n const { paramsError, searchError } = match\n\n if (paramsError) {\n handleSerialError(inner, index, paramsError, 'PARSE_PARAMS')\n }\n\n if (searchError) {\n handleSerialError(inner, index, searchError, 'VALIDATE_SEARCH')\n }\n\n setupPendingTimeout(inner, matchId, route, match)\n\n const abortController = new AbortController()\n\n let isPending = false\n const pending = () => {\n if (isPending) return\n isPending = true\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: 'beforeLoad',\n fetchCount: prev.fetchCount + 1,\n abortController,\n // Note: We intentionally don't update context here.\n // Context should only be updated after beforeLoad resolves to avoid\n // components seeing incomplete context during async beforeLoad execution.\n }))\n }\n\n const resolve = () => {\n match._nonReactive.beforeLoadPromise?.resolve()\n match._nonReactive.beforeLoadPromise = undefined\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: false,\n }))\n }\n\n // if there is no `beforeLoad` option, just mark as pending and resolve\n // Context will be updated later in loadRouteMatch after loader completes\n if (!route.options.beforeLoad) {\n batch(() => {\n pending()\n resolve()\n })\n return\n }\n\n match._nonReactive.beforeLoadPromise = createControlledPromise<void>()\n\n // Build context from all parent matches, excluding current match's __beforeLoadContext\n // (since we're about to execute beforeLoad for this match)\n const context = {\n ...buildMatchContext(inner, index, false),\n ...match.__routeContext,\n }\n const { search, params, cause } = match\n const preload = resolvePreload(inner, matchId)\n const beforeLoadFnContext: BeforeLoadContextOptions<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n > = {\n search,\n abortController,\n params,\n preload,\n context,\n location: inner.location,\n navigate: (opts: any) =>\n inner.router.navigate({\n ...opts,\n _fromLocation: inner.location,\n }),\n buildLocation: inner.router.buildLocation,\n cause: preload ? 'preload' : cause,\n matches: inner.matches,\n routeId: route.id,\n ...inner.router.options.additionalContext,\n }\n\n const updateContext = (beforeLoadContext: any) => {\n if (beforeLoadContext === undefined) {\n batch(() => {\n pending()\n resolve()\n })\n return\n }\n if (isRedirect(beforeLoadContext) || isNotFound(beforeLoadContext)) {\n pending()\n handleSerialError(inner, index, beforeLoadContext, 'BEFORE_LOAD')\n }\n\n batch(() => {\n pending()\n // Only store __beforeLoadContext here, don't update context yet\n // Context will be updated in loadRouteMatch after loader completes\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n __beforeLoadContext: beforeLoadContext,\n }))\n resolve()\n })\n }\n\n let beforeLoadContext\n try {\n beforeLoadContext = route.options.beforeLoad(beforeLoadFnContext)\n if (isPromise(beforeLoadContext)) {\n pending()\n return beforeLoadContext\n .catch((err) => {\n handleSerialError(inner, index, err, 'BEFORE_LOAD')\n })\n .then(updateContext)\n }\n } catch (err) {\n pending()\n handleSerialError(inner, index, err, 'BEFORE_LOAD')\n }\n\n updateContext(beforeLoadContext)\n return\n}\n\nconst handleBeforeLoad = (\n inner: InnerLoadContext,\n index: number,\n): void | Promise<void> => {\n const { id: matchId, routeId } = inner.matches[index]!\n const route = inner.router.looseRoutesById[routeId]!\n\n const serverSsr = () => {\n // on the server, determine whether SSR the current match or not\n if (isServer ?? inner.router.isServer) {\n const maybePromise = isBeforeLoadSsr(inner, matchId, index, route)\n if (isPromise(maybePromise)) return maybePromise.then(queueExecution)\n }\n return queueExecution()\n }\n\n const execute = () => executeBeforeLoad(inner, matchId, index, route)\n\n const queueExecution = () => {\n if (shouldSkipLoader(inner, matchId)) return\n const result = preBeforeLoadSetup(inner, matchId, route)\n return isPromise(result) ? result.then(execute) : execute()\n }\n\n return serverSsr()\n}\n\nconst executeHead = (\n inner: InnerLoadContext,\n matchId: string,\n route: AnyRoute,\n): void | Promise<\n Pick<\n AnyRouteMatch,\n 'meta' | 'links' | 'headScripts' | 'headers' | 'scripts' | 'styles'\n >\n> => {\n const match = inner.router.getMatch(matchId)\n // in case of a redirecting match during preload, the match does not exist\n if (!match) {\n return\n }\n if (!route.options.head && !route.options.scripts && !route.options.headers) {\n return\n }\n const assetContext = {\n ssr: inner.router.options.ssr,\n matches: inner.matches,\n match,\n params: match.params,\n loaderData: match.loaderData,\n }\n\n return Promise.all([\n route.options.head?.(assetContext),\n route.options.scripts?.(assetContext),\n route.options.headers?.(assetContext),\n ]).then(([headFnContent, scripts, headers]) => {\n const meta = headFnContent?.meta\n const links = headFnContent?.links\n const headScripts = headFnContent?.scripts\n const styles = headFnContent?.styles\n\n return {\n meta,\n links,\n headScripts,\n headers,\n scripts,\n styles,\n }\n })\n}\n\nconst getLoaderContext = (\n inner: InnerLoadContext,\n matchId: string,\n index: number,\n route: AnyRoute,\n): LoaderFnContext => {\n const parentMatchPromise = inner.matchPromises[index - 1] as any\n const { params, loaderDeps, abortController, cause } =\n inner.router.getMatch(matchId)!\n\n const context = buildMatchContext(inner, index)\n\n const preload = resolvePreload(inner, matchId)\n\n return {\n params,\n deps: loaderDeps,\n preload: !!preload,\n parentMatchPromise,\n abortController,\n context,\n location: inner.location,\n navigate: (opts) =>\n inner.router.navigate({\n ...opts,\n _fromLocation: inner.location,\n }),\n cause: preload ? 'preload' : cause,\n route,\n ...inner.router.options.additionalContext,\n }\n}\n\nconst runLoader = async (\n inner: InnerLoadContext,\n matchId: string,\n index: number,\n route: AnyRoute,\n): Promise<void> => {\n try {\n // If the Matches component rendered\n // the pending component and needs to show it for\n // a minimum duration, we''ll wait for it to resolve\n // before committing to the match and resolving\n // the loadPromise\n\n const match = inner.router.getMatch(matchId)!\n\n // Actually run the loader and handle the result\n try {\n if (!(isServer ?? inner.router.isServer) || match.ssr === true) {\n loadRouteChunk(route)\n }\n\n // Kick off the loader!\n const loaderResult = route.options.loader?.(\n getLoaderContext(inner, matchId, index, route),\n )\n const loaderResultIsPromise =\n route.options.loader && isPromise(loaderResult)\n\n const willLoadSomething = !!(\n loaderResultIsPromise ||\n route._lazyPromise ||\n route._componentsPromise ||\n route.options.head ||\n route.options.scripts ||\n route.options.headers ||\n match._nonReactive.minPendingPromise\n )\n\n if (willLoadSomething) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: 'loader',\n }))\n }\n\n if (route.options.loader) {\n const loaderData = loaderResultIsPromise\n ? await loaderResult\n : loaderResult\n\n handleRedirectAndNotFound(\n inner,\n inner.router.getMatch(matchId),\n loaderData,\n )\n if (loaderData !== undefined) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n loaderData,\n }))\n }\n }\n\n // Lazy option can modify the route options,\n // so we need to wait for it to resolve before\n // we can use the options\n if (route._lazyPromise) await route._lazyPromise\n const pendingPromise = match._nonReactive.minPendingPromise\n if (pendingPromise) await pendingPromise\n\n // Last but not least, wait for the the components\n // to be preloaded before we resolve the match\n if (route._componentsPromise) await route._componentsPromise\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n error: undefined,\n context: buildMatchContext(inner, index),\n status: 'success',\n isFetching: false,\n updatedAt: Date.now(),\n }))\n } catch (e) {\n let error = e\n\n if ((error as any)?.name === 'AbortError') {\n if (match.abortController.signal.aborted) {\n match._nonReactive.loaderPromise?.resolve()\n match._nonReactive.loaderPromise = undefined\n return\n }\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n status: prev.status === 'pending' ? 'success' : prev.status,\n isFetching: false,\n context: buildMatchContext(inner, index),\n }))\n return\n }\n\n const pendingPromise = match._nonReactive.minPendingPromise\n if (pendingPromise) await pendingPromise\n\n if (isNotFound(e)) {\n await (route.options.notFoundComponent as any)?.preload?.()\n }\n\n handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), e)\n\n try {\n route.options.onError?.(e)\n } catch (onErrorError) {\n error = onErrorError\n handleRedirectAndNotFound(\n inner,\n inner.router.getMatch(matchId),\n onErrorError,\n )\n }\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n error,\n context: buildMatchContext(inner, index),\n status: 'error',\n isFetching: false,\n }))\n }\n } catch (err) {\n const match = inner.router.getMatch(matchId)\n // in case of a redirecting match during preload, the match does not exist\n if (match) {\n match._nonReactive.loaderPromise = undefined\n }\n handleRedirectAndNotFound(inner, match, err)\n }\n}\n\nconst loadRouteMatch = async (\n inner: InnerLoadContext,\n index: number,\n): Promise<AnyRouteMatch> => {\n async function handleLoader(\n preload: boolean,\n prevMatch: AnyRouteMatch,\n match: AnyRouteMatch,\n route: AnyRoute,\n ) {\n const age = Date.now() - prevMatch.updatedAt\n\n const staleAge = preload\n ? (route.options.preloadStaleTime ??\n inner.router.options.defaultPreloadStaleTime ??\n 30_000) // 30 seconds for preloads by default\n : (route.options.staleTime ?? inner.router.options.defaultStaleTime ?? 0)\n\n const shouldReloadOption = route.options.shouldReload\n\n // Default to reloading the route all the time\n // Allow shouldReload to get the last say,\n // if provided.\n const shouldReload =\n typeof shouldReloadOption === 'function'\n ? shouldReloadOption(getLoaderContext(inner, matchId, index, route))\n : shouldReloadOption\n\n // If the route is successful and still fresh, just resolve\n const { status, invalid } = match\n loaderShouldRunAsync =\n status === 'success' && (invalid || (shouldReload ?? age > staleAge))\n if (preload && route.options.preload === false) {\n // Do nothing\n } else if (loaderShouldRunAsync && !inner.sync) {\n loaderIsRunningAsync = true\n ;(async () => {\n try {\n await runLoader(inner, matchId, index, route)\n const match = inner.router.getMatch(matchId)!\n match._nonReactive.loaderPromise?.resolve()\n match._nonReactive.loadPromise?.resolve()\n match._nonReactive.loaderPromise = undefined\n } catch (err) {\n if (isRedirect(err)) {\n await inner.router.navigate(err.options)\n }\n }\n })()\n } else if (status !== 'success' || (loaderShouldRunAsync && inner.sync)) {\n await runLoader(inner, matchId, index, route)\n }\n }\n\n const { id: matchId, routeId } = inner.matches[index]!\n let loaderShouldRunAsync = false\n let loaderIsRunningAsync = false\n const route = inner.router.looseRoutesById[routeId]!\n\n if (shouldSkipLoader(inner, matchId)) {\n if (isServer ?? inner.router.isServer) {\n return inner.router.getMatch(matchId)!\n }\n } else {\n const prevMatch = inner.router.getMatch(matchId)! // This is where all of the stale-while-revalidate magic happens\n const preload = resolvePreload(inner, matchId)\n\n // there is a loaderPromise, so we are in the middle of a load\n if (prevMatch._nonReactive.loaderPromise) {\n // do not block if we already have stale data we can show\n // but only if the ongoing load is not a preload since error handling is different for preloads\n // and we don't want to swallow errors\n if (prevMatch.status === 'success' && !inner.sync && !prevMatch.preload) {\n return prevMatch\n }\n await prevMatch._nonReactive.loaderPromise\n const match = inner.router.getMatch(matchId)!\n const error = match._nonReactive.error || match.error\n if (error) {\n handleRedirectAndNotFound(inner, match, error)\n }\n\n if (match.status === 'pending') {\n await handleLoader(preload, prevMatch, match, route)\n }\n } else {\n const nextPreload =\n preload && !inner.router.state.matches.some((d) => d.id === matchId)\n const match = inner.router.getMatch(matchId)!\n match._nonReactive.loaderPromise = createControlledPromise<void>()\n if (nextPreload !== match.preload) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n preload: nextPreload,\n }))\n }\n\n await handleLoader(preload, prevMatch, match, route)\n }\n }\n const match = inner.router.getMatch(matchId)!\n if (!loaderIsRunningAsync) {\n match._nonReactive.loaderPromise?.resolve()\n match._nonReactive.loadPromise?.resolve()\n }\n\n clearTimeout(match._nonReactive.pendingTimeout)\n match._nonReactive.pendingTimeout = undefined\n if (!loaderIsRunningAsync) match._nonReactive.loaderPromise = undefined\n match._nonReactive.dehydrated = undefined\n\n const nextIsFetching = loaderIsRunningAsync ? match.isFetching : false\n if (nextIsFetching !== match.isFetching || match.invalid !== false) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: nextIsFetching,\n invalid: false,\n }))\n return inner.router.getMatch(matchId)!\n } else {\n return match\n }\n}\n\nexport async function loadMatches(arg: {\n router: AnyRouter\n location: ParsedLocation\n matches: Array<AnyRouteMatch>\n preload?: boolean\n onReady?: () => Promise<void>\n updateMatch: UpdateMatchFn\n sync?: boolean\n}): Promise<Array<MakeRouteMatch>> {\n const inner: InnerLoadContext = Object.assign(arg, {\n matchPromises: [],\n })\n\n // make sure the pending component is immediately rendered when hydrating a match that is not SSRed\n // the pending component was already rendered on the server and we want to keep it shown on the client until minPendingMs is reached\n if (\n !(isServer ?? inner.router.isServer) &&\n inner.router.state.matches.some((d) => d._forcePending)\n ) {\n triggerOnReady(inner)\n }\n\n try {\n // Execute all beforeLoads one by one\n for (let i = 0; i < inner.matches.length; i++) {\n const beforeLoad = handleBeforeLoad(inner, i)\n if (isPromise(beforeLoad)) await beforeLoad\n }\n\n // Execute all loaders in parallel\n const max = inner.firstBadMatchIndex ?? inner.matches.length\n for (let i = 0; i < max; i++) {\n inner.matchPromises.push(loadRouteMatch(inner, i))\n }\n // Use allSettled to ensure all loaders complete regardless of success/failure\n const results = await Promise.allSettled(inner.matchPromises)\n\n const failures = results\n // TODO when we drop support for TS 5.4, we can use the built-in type guard for PromiseRejectedResult\n .filter(\n (result): result is PromiseRejectedResult =>\n result.status === 'rejected',\n )\n .map((result) => result.reason)\n\n // Find first redirect (throw immediately) or notFound (throw after head execution)\n let firstNotFound: unknown\n for (const err of failures) {\n if (isRedirect(err)) {\n throw err\n }\n if (!firstNotFound && isNotFound(err)) {\n firstNotFound = err\n }\n }\n\n // serially execute head functions after all loaders have completed (successfully or not)\n // Each head execution is wrapped in try-catch to ensure all heads run even if one fails\n for (const match of inner.matches) {\n const { id: matchId, routeId } = match\n const route = inner.router.looseRoutesById[routeId]!\n try {\n const headResult = executeHead(inner, matchId, route)\n if (headResult) {\n const head = await headResult\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n ...head,\n }))\n }\n } catch (err) {\n // Log error but continue executing other head functions\n console.error(`Error executing head for route ${routeId}:`, err)\n }\n }\n\n // Throw notFound after head execution\n if (firstNotFound) {\n throw firstNotFound\n }\n\n const readyPromise = triggerOnReady(inner)\n if (isPromise(readyPromise)) await readyPromise\n } catch (err) {\n if (isNotFound(err) && !inner.preload) {\n const readyPromise = triggerOnReady(inner)\n if (isPromise(readyPromise)) await readyPromise\n throw err\n }\n if (isRedirect(err)) {\n throw err\n }\n }\n return inner.matches\n}\n\nexport async function loadRouteChunk(route: AnyRoute) {\n if (!route._lazyLoaded && route._lazyPromise === undefined) {\n if (route.lazyFn) {\n route._lazyPromise = route.lazyFn().then((lazyRoute) => {\n // explicitly don't copy over the lazy route's id\n const { id: _id, ...options } = lazyRoute.options\n Object.assign(route.options, options)\n route._lazyLoaded = true\n route._lazyPromise = undefined // gc promise, we won't need it anymore\n })\n } else {\n route._lazyLoaded = true\n }\n }\n\n // If for some reason lazy resolves more lazy components...\n // We'll wait for that before we attempt to preload the\n // components themselves.\n if (!route._componentsLoaded && route._componentsPromise === undefined) {\n const loadComponents = () => {\n const preloads = []\n for (const type of componentTypes) {\n const preload = (route.options[type] as any)?.preload\n if (preload) preloads.push(preload())\n }\n if (preloads.length)\n return Promise.all(preloads).then(() => {\n route._componentsLoaded = true\n route._componentsPromise = undefined // gc promise, we won't need it anymore\n })\n route._componentsLoaded = true\n route._componentsPromise = undefined // gc promise, we won't need it anymore\n return\n }\n route._componentsPromise = route._lazyPromise\n ? route._lazyPromise.then(loadComponents)\n : loadComponents()\n }\n return route._componentsPromise\n}\n\nfunction makeMaybe<TValue, TError>(\n value: TValue,\n error: TError,\n): { status: 'success'; value: TValue } | { status: 'error'; error: TError } {\n if (error) {\n return { status: 'error' as const, error }\n }\n return { status: 'success' as const, value }\n}\n\nexport function routeNeedsPreload(route: AnyRoute) {\n for (const componentType of componentTypes) {\n if ((route.options[componentType] as any)?.preload) {\n return true\n }\n }\n return false\n}\n\nexport const componentTypes = [\n 'component',\n 'errorComponent',\n 'pendingComponent',\n 'notFoundComponent',\n] as const\n"],"names":["tempSsr","beforeLoadContext","match","route"],"mappings":";;;;;;;AAwCA,MAAM,iBAAiB,CAAC,UAAkD;AACxE,MAAI,CAAC,MAAM,UAAU;AACnB,UAAM,WAAW;AACjB,WAAO,MAAM,UAAA;AAAA,EACf;AACF;AAEA,MAAM,iBAAiB,CAAC,OAAyB,YAA6B;AAC5E,SAAO,CAAC,EACN,MAAM,WAAW,CAAC,MAAM,OAAO,MAAM,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO;AAE7E;AAMA,MAAM,oBAAoB,CACxB,OACA,OACA,sBAA+B,SACH;AAC5B,QAAM,UAAmC;AAAA,IACvC,GA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AAK,cAAc,IACtC,eAAA;AAAA,EACN;AACA,SAAO,MAAM;AACf;AAEA,SAAS,UACP,OACA,OAC2E;AAC3E,MAAI,OAAO;AACT,WAAO,EAAE,QAAQ,SAAkB,MAAA;AAAA,EACrC;AACA,SAAO,EAAE,QAAQ,WAAoB,MAAA;AACvC;AAEO,SAAS,kBAAkB,OAAiB;AACjD,aAAW,iBAAiB,gBAAgB;AAC1C,QAAK,MAAM,QAAQ,aAAa,GAAW,SAAS;AAClD,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAEO,MAAM,iBAAiB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;"}
1
+ {"version":3,"file":"load-matches.js","sources":["../../src/load-matches.ts"],"sourcesContent":["import invariant from 'tiny-invariant'\nimport { isServer } from '@tanstack/router-core/isServer'\nimport { batch } from './utils/batch'\nimport { createControlledPromise, isPromise } from './utils'\nimport { isNotFound } from './not-found'\nimport { rootRouteId } from './root'\nimport { isRedirect } from './redirect'\nimport type { NotFoundError } from './not-found'\nimport type { ParsedLocation } from './location'\nimport type {\n AnyRoute,\n BeforeLoadContextOptions,\n LoaderFnContext,\n SsrContextOptions,\n} from './route'\nimport type { AnyRouteMatch, MakeRouteMatch } from './Matches'\nimport type { AnyRouter, SSROption, UpdateMatchFn } from './router'\n\n/**\n * An object of this shape is created when calling `loadMatches`.\n * It contains everything we need for all other functions in this file\n * to work. (It's basically the function's argument, plus a few mutable states)\n */\ntype InnerLoadContext = {\n /** the calling router instance */\n router: AnyRouter\n location: ParsedLocation\n /** mutable state, scoped to a `loadMatches` call */\n firstBadMatchIndex?: number\n /** mutable state, scoped to a `loadMatches` call */\n rendered?: boolean\n serialError?: unknown\n updateMatch: UpdateMatchFn\n matches: Array<AnyRouteMatch>\n preload?: boolean\n onReady?: () => Promise<void>\n sync?: boolean\n}\n\nconst triggerOnReady = (inner: InnerLoadContext): void | Promise<void> => {\n if (!inner.rendered) {\n inner.rendered = true\n return inner.onReady?.()\n }\n}\n\nconst resolvePreload = (inner: InnerLoadContext, matchId: string): boolean => {\n return !!(\n inner.preload && !inner.router.state.matches.some((d) => d.id === matchId)\n )\n}\n\n/**\n * Builds the accumulated context from router options and all matches up to (and optionally including) the given index.\n * Merges __routeContext and __beforeLoadContext from each match.\n */\nconst buildMatchContext = (\n inner: InnerLoadContext,\n index: number,\n includeCurrentMatch: boolean = true,\n): Record<string, unknown> => {\n const context: Record<string, unknown> = {\n ...(inner.router.options.context ?? {}),\n }\n const end = includeCurrentMatch ? index : index - 1\n for (let i = 0; i <= end; i++) {\n const innerMatch = inner.matches[i]\n if (!innerMatch) continue\n const m = inner.router.getMatch(innerMatch.id)\n if (!m) continue\n Object.assign(context, m.__routeContext, m.__beforeLoadContext)\n }\n return context\n}\n\nconst getNotFoundBoundaryIndex = (\n inner: InnerLoadContext,\n err: NotFoundError,\n): number | undefined => {\n if (!inner.matches.length) {\n return undefined\n }\n\n const requestedRouteId = err.routeId\n const matchedRootIndex = inner.matches.findIndex(\n (m) => m.routeId === inner.router.routeTree.id,\n )\n const rootIndex = matchedRootIndex >= 0 ? matchedRootIndex : 0\n\n let startIndex = requestedRouteId\n ? inner.matches.findIndex((match) => match.routeId === requestedRouteId)\n : (inner.firstBadMatchIndex ?? inner.matches.length - 1)\n\n if (startIndex < 0) {\n startIndex = rootIndex\n }\n\n for (let i = startIndex; i >= 0; i--) {\n const match = inner.matches[i]!\n const route = inner.router.looseRoutesById[match.routeId]!\n if (route.options.notFoundComponent) {\n return i\n }\n }\n\n // If no boundary component is found, preserve explicit routeId targeting behavior,\n // otherwise default to root for untargeted notFounds.\n return requestedRouteId ? startIndex : rootIndex\n}\n\nconst handleRedirectAndNotFound = (\n inner: InnerLoadContext,\n match: AnyRouteMatch | undefined,\n err: unknown,\n): void => {\n if (!isRedirect(err) && !isNotFound(err)) return\n\n if (isRedirect(err) && err.redirectHandled && !err.options.reloadDocument) {\n throw err\n }\n\n // in case of a redirecting match during preload, the match does not exist\n if (match) {\n match._nonReactive.beforeLoadPromise?.resolve()\n match._nonReactive.loaderPromise?.resolve()\n match._nonReactive.beforeLoadPromise = undefined\n match._nonReactive.loaderPromise = undefined\n\n match._nonReactive.error = err\n\n inner.updateMatch(match.id, (prev) => ({\n ...prev,\n status: isRedirect(err)\n ? 'redirected'\n : prev.status === 'pending'\n ? 'success'\n : prev.status,\n context: buildMatchContext(inner, match.index),\n isFetching: false,\n error: err,\n }))\n\n if (isNotFound(err) && !err.routeId) {\n // Stamp the throwing match's routeId so that the finalization step in\n // loadMatches knows where the notFound originated. The actual boundary\n // resolution (walking up to the nearest notFoundComponent) is deferred to\n // the finalization step, where firstBadMatchIndex is stable and\n // headMaxIndex can be capped correctly.\n err.routeId = match.routeId\n }\n\n match._nonReactive.loadPromise?.resolve()\n }\n\n if (isRedirect(err)) {\n inner.rendered = true\n err.options._fromLocation = inner.location\n err.redirectHandled = true\n err = inner.router.resolveRedirect(err)\n }\n\n throw err\n}\n\nconst shouldSkipLoader = (\n inner: InnerLoadContext,\n matchId: string,\n): boolean => {\n const match = inner.router.getMatch(matchId)!\n // upon hydration, we skip the loader if the match has been dehydrated on the server\n if (!(isServer ?? inner.router.isServer) && match._nonReactive.dehydrated) {\n return true\n }\n\n if ((isServer ?? inner.router.isServer) && match.ssr === false) {\n return true\n }\n\n return false\n}\n\nconst handleSerialError = (\n inner: InnerLoadContext,\n index: number,\n err: any,\n routerCode: string,\n): void => {\n const { id: matchId, routeId } = inner.matches[index]!\n const route = inner.router.looseRoutesById[routeId]!\n\n // Much like suspense, we use a promise here to know if\n // we've been outdated by a new loadMatches call and\n // should abort the current async operation\n if (err instanceof Promise) {\n throw err\n }\n\n err.routerCode = routerCode\n inner.firstBadMatchIndex ??= index\n handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err)\n\n try {\n route.options.onError?.(err)\n } catch (errorHandlerErr) {\n err = errorHandlerErr\n handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err)\n }\n\n inner.updateMatch(matchId, (prev) => {\n prev._nonReactive.beforeLoadPromise?.resolve()\n prev._nonReactive.beforeLoadPromise = undefined\n prev._nonReactive.loadPromise?.resolve()\n\n return {\n ...prev,\n error: err,\n status: 'error',\n isFetching: false,\n updatedAt: Date.now(),\n abortController: new AbortController(),\n }\n })\n\n if (!inner.preload && !isRedirect(err) && !isNotFound(err)) {\n inner.serialError ??= err\n }\n}\n\nconst isBeforeLoadSsr = (\n inner: InnerLoadContext,\n matchId: string,\n index: number,\n route: AnyRoute,\n): void | Promise<void> => {\n const existingMatch = inner.router.getMatch(matchId)!\n const parentMatchId = inner.matches[index - 1]?.id\n const parentMatch = parentMatchId\n ? inner.router.getMatch(parentMatchId)!\n : undefined\n\n // in SPA mode, only SSR the root route\n if (inner.router.isShell()) {\n existingMatch.ssr = route.id === rootRouteId\n return\n }\n\n if (parentMatch?.ssr === false) {\n existingMatch.ssr = false\n return\n }\n\n const parentOverride = (tempSsr: SSROption) => {\n if (tempSsr === true && parentMatch?.ssr === 'data-only') {\n return 'data-only'\n }\n return tempSsr\n }\n\n const defaultSsr = inner.router.options.defaultSsr ?? true\n\n if (route.options.ssr === undefined) {\n existingMatch.ssr = parentOverride(defaultSsr)\n return\n }\n\n if (typeof route.options.ssr !== 'function') {\n existingMatch.ssr = parentOverride(route.options.ssr)\n return\n }\n const { search, params } = existingMatch\n\n const ssrFnContext: SsrContextOptions<any, any, any> = {\n search: makeMaybe(search, existingMatch.searchError),\n params: makeMaybe(params, existingMatch.paramsError),\n location: inner.location,\n matches: inner.matches.map((match) => ({\n index: match.index,\n pathname: match.pathname,\n fullPath: match.fullPath,\n staticData: match.staticData,\n id: match.id,\n routeId: match.routeId,\n search: makeMaybe(match.search, match.searchError),\n params: makeMaybe(match.params, match.paramsError),\n ssr: match.ssr,\n })),\n }\n\n const tempSsr = route.options.ssr(ssrFnContext)\n if (isPromise(tempSsr)) {\n return tempSsr.then((ssr) => {\n existingMatch.ssr = parentOverride(ssr ?? defaultSsr)\n })\n }\n\n existingMatch.ssr = parentOverride(tempSsr ?? defaultSsr)\n return\n}\n\nconst setupPendingTimeout = (\n inner: InnerLoadContext,\n matchId: string,\n route: AnyRoute,\n match: AnyRouteMatch,\n): void => {\n if (match._nonReactive.pendingTimeout !== undefined) return\n\n const pendingMs =\n route.options.pendingMs ?? inner.router.options.defaultPendingMs\n const shouldPending = !!(\n inner.onReady &&\n !(isServer ?? inner.router.isServer) &&\n !resolvePreload(inner, matchId) &&\n (route.options.loader ||\n route.options.beforeLoad ||\n routeNeedsPreload(route)) &&\n typeof pendingMs === 'number' &&\n pendingMs !== Infinity &&\n (route.options.pendingComponent ??\n (inner.router.options as any)?.defaultPendingComponent)\n )\n\n if (shouldPending) {\n const pendingTimeout = setTimeout(() => {\n // Update the match and prematurely resolve the loadMatches promise so that\n // the pending component can start rendering\n triggerOnReady(inner)\n }, pendingMs)\n match._nonReactive.pendingTimeout = pendingTimeout\n }\n}\n\nconst preBeforeLoadSetup = (\n inner: InnerLoadContext,\n matchId: string,\n route: AnyRoute,\n): void | Promise<void> => {\n const existingMatch = inner.router.getMatch(matchId)!\n\n // If we are in the middle of a load, either of these will be present\n // (not to be confused with `loadPromise`, which is always defined)\n if (\n !existingMatch._nonReactive.beforeLoadPromise &&\n !existingMatch._nonReactive.loaderPromise\n )\n return\n\n setupPendingTimeout(inner, matchId, route, existingMatch)\n\n const then = () => {\n const match = inner.router.getMatch(matchId)!\n if (\n match.preload &&\n (match.status === 'redirected' || match.status === 'notFound')\n ) {\n handleRedirectAndNotFound(inner, match, match.error)\n }\n }\n\n // Wait for the previous beforeLoad to resolve before we continue\n return existingMatch._nonReactive.beforeLoadPromise\n ? existingMatch._nonReactive.beforeLoadPromise.then(then)\n : then()\n}\n\nconst executeBeforeLoad = (\n inner: InnerLoadContext,\n matchId: string,\n index: number,\n route: AnyRoute,\n): void | Promise<void> => {\n const match = inner.router.getMatch(matchId)!\n\n // explicitly capture the previous loadPromise\n const prevLoadPromise = match._nonReactive.loadPromise\n match._nonReactive.loadPromise = createControlledPromise<void>(() => {\n prevLoadPromise?.resolve()\n })\n\n const { paramsError, searchError } = match\n\n if (paramsError) {\n handleSerialError(inner, index, paramsError, 'PARSE_PARAMS')\n }\n\n if (searchError) {\n handleSerialError(inner, index, searchError, 'VALIDATE_SEARCH')\n }\n\n setupPendingTimeout(inner, matchId, route, match)\n\n const abortController = new AbortController()\n\n let isPending = false\n const pending = () => {\n if (isPending) return\n isPending = true\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: 'beforeLoad',\n fetchCount: prev.fetchCount + 1,\n abortController,\n // Note: We intentionally don't update context here.\n // Context should only be updated after beforeLoad resolves to avoid\n // components seeing incomplete context during async beforeLoad execution.\n }))\n }\n\n const resolve = () => {\n match._nonReactive.beforeLoadPromise?.resolve()\n match._nonReactive.beforeLoadPromise = undefined\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: false,\n }))\n }\n\n // if there is no `beforeLoad` option, just mark as pending and resolve\n // Context will be updated later in loadRouteMatch after loader completes\n if (!route.options.beforeLoad) {\n batch(() => {\n pending()\n resolve()\n })\n return\n }\n\n match._nonReactive.beforeLoadPromise = createControlledPromise<void>()\n\n // Build context from all parent matches, excluding current match's __beforeLoadContext\n // (since we're about to execute beforeLoad for this match)\n const context = {\n ...buildMatchContext(inner, index, false),\n ...match.__routeContext,\n }\n const { search, params, cause } = match\n const preload = resolvePreload(inner, matchId)\n const beforeLoadFnContext: BeforeLoadContextOptions<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n > = {\n search,\n abortController,\n params,\n preload,\n context,\n location: inner.location,\n navigate: (opts: any) =>\n inner.router.navigate({\n ...opts,\n _fromLocation: inner.location,\n }),\n buildLocation: inner.router.buildLocation,\n cause: preload ? 'preload' : cause,\n matches: inner.matches,\n routeId: route.id,\n ...inner.router.options.additionalContext,\n }\n\n const updateContext = (beforeLoadContext: any) => {\n if (beforeLoadContext === undefined) {\n batch(() => {\n pending()\n resolve()\n })\n return\n }\n if (isRedirect(beforeLoadContext) || isNotFound(beforeLoadContext)) {\n pending()\n handleSerialError(inner, index, beforeLoadContext, 'BEFORE_LOAD')\n }\n\n batch(() => {\n pending()\n // Only store __beforeLoadContext here, don't update context yet\n // Context will be updated in loadRouteMatch after loader completes\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n __beforeLoadContext: beforeLoadContext,\n }))\n resolve()\n })\n }\n\n let beforeLoadContext\n try {\n beforeLoadContext = route.options.beforeLoad(beforeLoadFnContext)\n if (isPromise(beforeLoadContext)) {\n pending()\n return beforeLoadContext\n .catch((err) => {\n handleSerialError(inner, index, err, 'BEFORE_LOAD')\n })\n .then(updateContext)\n }\n } catch (err) {\n pending()\n handleSerialError(inner, index, err, 'BEFORE_LOAD')\n }\n\n updateContext(beforeLoadContext)\n return\n}\n\nconst handleBeforeLoad = (\n inner: InnerLoadContext,\n index: number,\n): void | Promise<void> => {\n const { id: matchId, routeId } = inner.matches[index]!\n const route = inner.router.looseRoutesById[routeId]!\n\n const serverSsr = () => {\n // on the server, determine whether SSR the current match or not\n if (isServer ?? inner.router.isServer) {\n const maybePromise = isBeforeLoadSsr(inner, matchId, index, route)\n if (isPromise(maybePromise)) return maybePromise.then(queueExecution)\n }\n return queueExecution()\n }\n\n const execute = () => executeBeforeLoad(inner, matchId, index, route)\n\n const queueExecution = () => {\n if (shouldSkipLoader(inner, matchId)) return\n const result = preBeforeLoadSetup(inner, matchId, route)\n return isPromise(result) ? result.then(execute) : execute()\n }\n\n return serverSsr()\n}\n\nconst executeHead = (\n inner: InnerLoadContext,\n matchId: string,\n route: AnyRoute,\n): void | Promise<\n Pick<\n AnyRouteMatch,\n 'meta' | 'links' | 'headScripts' | 'headers' | 'scripts' | 'styles'\n >\n> => {\n const match = inner.router.getMatch(matchId)\n // in case of a redirecting match during preload, the match does not exist\n if (!match) {\n return\n }\n if (!route.options.head && !route.options.scripts && !route.options.headers) {\n return\n }\n const assetContext = {\n ssr: inner.router.options.ssr,\n matches: inner.matches,\n match,\n params: match.params,\n loaderData: match.loaderData,\n }\n\n return Promise.all([\n route.options.head?.(assetContext),\n route.options.scripts?.(assetContext),\n route.options.headers?.(assetContext),\n ]).then(([headFnContent, scripts, headers]) => {\n const meta = headFnContent?.meta\n const links = headFnContent?.links\n const headScripts = headFnContent?.scripts\n const styles = headFnContent?.styles\n\n return {\n meta,\n links,\n headScripts,\n headers,\n scripts,\n styles,\n }\n })\n}\n\nconst getLoaderContext = (\n inner: InnerLoadContext,\n matchPromises: Array<Promise<AnyRouteMatch>>,\n matchId: string,\n index: number,\n route: AnyRoute,\n): LoaderFnContext => {\n const parentMatchPromise = matchPromises[index - 1] as any\n const { params, loaderDeps, abortController, cause } =\n inner.router.getMatch(matchId)!\n\n const context = buildMatchContext(inner, index)\n\n const preload = resolvePreload(inner, matchId)\n\n return {\n params,\n deps: loaderDeps,\n preload: !!preload,\n parentMatchPromise,\n abortController,\n context,\n location: inner.location,\n navigate: (opts) =>\n inner.router.navigate({\n ...opts,\n _fromLocation: inner.location,\n }),\n cause: preload ? 'preload' : cause,\n route,\n ...inner.router.options.additionalContext,\n }\n}\n\nconst runLoader = async (\n inner: InnerLoadContext,\n matchPromises: Array<Promise<AnyRouteMatch>>,\n matchId: string,\n index: number,\n route: AnyRoute,\n): Promise<void> => {\n try {\n // If the Matches component rendered\n // the pending component and needs to show it for\n // a minimum duration, we''ll wait for it to resolve\n // before committing to the match and resolving\n // the loadPromise\n\n const match = inner.router.getMatch(matchId)!\n\n // Actually run the loader and handle the result\n try {\n if (!(isServer ?? inner.router.isServer) || match.ssr === true) {\n loadRouteChunk(route)\n }\n\n // Kick off the loader!\n const loaderResult = route.options.loader?.(\n getLoaderContext(inner, matchPromises, matchId, index, route),\n )\n const loaderResultIsPromise =\n route.options.loader && isPromise(loaderResult)\n\n const willLoadSomething = !!(\n loaderResultIsPromise ||\n route._lazyPromise ||\n route._componentsPromise ||\n route.options.head ||\n route.options.scripts ||\n route.options.headers ||\n match._nonReactive.minPendingPromise\n )\n\n if (willLoadSomething) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: 'loader',\n }))\n }\n\n if (route.options.loader) {\n const loaderData = loaderResultIsPromise\n ? await loaderResult\n : loaderResult\n\n handleRedirectAndNotFound(\n inner,\n inner.router.getMatch(matchId),\n loaderData,\n )\n if (loaderData !== undefined) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n loaderData,\n }))\n }\n }\n\n // Lazy option can modify the route options,\n // so we need to wait for it to resolve before\n // we can use the options\n if (route._lazyPromise) await route._lazyPromise\n const pendingPromise = match._nonReactive.minPendingPromise\n if (pendingPromise) await pendingPromise\n\n // Last but not least, wait for the the components\n // to be preloaded before we resolve the match\n if (route._componentsPromise) await route._componentsPromise\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n error: undefined,\n context: buildMatchContext(inner, index),\n status: 'success',\n isFetching: false,\n updatedAt: Date.now(),\n }))\n } catch (e) {\n let error = e\n\n if ((error as any)?.name === 'AbortError') {\n if (match.abortController.signal.aborted) {\n match._nonReactive.loaderPromise?.resolve()\n match._nonReactive.loaderPromise = undefined\n return\n }\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n status: prev.status === 'pending' ? 'success' : prev.status,\n isFetching: false,\n context: buildMatchContext(inner, index),\n }))\n return\n }\n\n const pendingPromise = match._nonReactive.minPendingPromise\n if (pendingPromise) await pendingPromise\n\n if (isNotFound(e)) {\n await (route.options.notFoundComponent as any)?.preload?.()\n }\n\n handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), e)\n\n try {\n route.options.onError?.(e)\n } catch (onErrorError) {\n error = onErrorError\n handleRedirectAndNotFound(\n inner,\n inner.router.getMatch(matchId),\n onErrorError,\n )\n }\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n error,\n context: buildMatchContext(inner, index),\n status: 'error',\n isFetching: false,\n }))\n }\n } catch (err) {\n const match = inner.router.getMatch(matchId)\n // in case of a redirecting match during preload, the match does not exist\n if (match) {\n match._nonReactive.loaderPromise = undefined\n }\n handleRedirectAndNotFound(inner, match, err)\n }\n}\n\nconst loadRouteMatch = async (\n inner: InnerLoadContext,\n matchPromises: Array<Promise<AnyRouteMatch>>,\n index: number,\n): Promise<AnyRouteMatch> => {\n async function handleLoader(\n preload: boolean,\n prevMatch: AnyRouteMatch,\n match: AnyRouteMatch,\n route: AnyRoute,\n ) {\n const age = Date.now() - prevMatch.updatedAt\n\n const staleAge = preload\n ? (route.options.preloadStaleTime ??\n inner.router.options.defaultPreloadStaleTime ??\n 30_000) // 30 seconds for preloads by default\n : (route.options.staleTime ?? inner.router.options.defaultStaleTime ?? 0)\n\n const shouldReloadOption = route.options.shouldReload\n\n // Default to reloading the route all the time\n // Allow shouldReload to get the last say,\n // if provided.\n const shouldReload =\n typeof shouldReloadOption === 'function'\n ? shouldReloadOption(\n getLoaderContext(inner, matchPromises, matchId, index, route),\n )\n : shouldReloadOption\n\n // If the route is successful and still fresh, just resolve\n const { status, invalid } = match\n loaderShouldRunAsync =\n status === 'success' && (invalid || (shouldReload ?? age > staleAge))\n if (preload && route.options.preload === false) {\n // Do nothing\n } else if (loaderShouldRunAsync && !inner.sync) {\n loaderIsRunningAsync = true\n ;(async () => {\n try {\n await runLoader(inner, matchPromises, matchId, index, route)\n const match = inner.router.getMatch(matchId)!\n match._nonReactive.loaderPromise?.resolve()\n match._nonReactive.loadPromise?.resolve()\n match._nonReactive.loaderPromise = undefined\n } catch (err) {\n if (isRedirect(err)) {\n await inner.router.navigate(err.options)\n }\n }\n })()\n } else if (status !== 'success' || (loaderShouldRunAsync && inner.sync)) {\n await runLoader(inner, matchPromises, matchId, index, route)\n }\n }\n\n const { id: matchId, routeId } = inner.matches[index]!\n let loaderShouldRunAsync = false\n let loaderIsRunningAsync = false\n const route = inner.router.looseRoutesById[routeId]!\n\n if (shouldSkipLoader(inner, matchId)) {\n if (isServer ?? inner.router.isServer) {\n return inner.router.getMatch(matchId)!\n }\n } else {\n const prevMatch = inner.router.getMatch(matchId)! // This is where all of the stale-while-revalidate magic happens\n const preload = resolvePreload(inner, matchId)\n\n // there is a loaderPromise, so we are in the middle of a load\n if (prevMatch._nonReactive.loaderPromise) {\n // do not block if we already have stale data we can show\n // but only if the ongoing load is not a preload since error handling is different for preloads\n // and we don't want to swallow errors\n if (prevMatch.status === 'success' && !inner.sync && !prevMatch.preload) {\n return prevMatch\n }\n await prevMatch._nonReactive.loaderPromise\n const match = inner.router.getMatch(matchId)!\n const error = match._nonReactive.error || match.error\n if (error) {\n handleRedirectAndNotFound(inner, match, error)\n }\n\n if (match.status === 'pending') {\n await handleLoader(preload, prevMatch, match, route)\n }\n } else {\n const nextPreload =\n preload && !inner.router.state.matches.some((d) => d.id === matchId)\n const match = inner.router.getMatch(matchId)!\n match._nonReactive.loaderPromise = createControlledPromise<void>()\n if (nextPreload !== match.preload) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n preload: nextPreload,\n }))\n }\n\n await handleLoader(preload, prevMatch, match, route)\n }\n }\n const match = inner.router.getMatch(matchId)!\n if (!loaderIsRunningAsync) {\n match._nonReactive.loaderPromise?.resolve()\n match._nonReactive.loadPromise?.resolve()\n }\n\n clearTimeout(match._nonReactive.pendingTimeout)\n match._nonReactive.pendingTimeout = undefined\n if (!loaderIsRunningAsync) match._nonReactive.loaderPromise = undefined\n match._nonReactive.dehydrated = undefined\n\n const nextIsFetching = loaderIsRunningAsync ? match.isFetching : false\n if (nextIsFetching !== match.isFetching || match.invalid !== false) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: nextIsFetching,\n invalid: false,\n }))\n return inner.router.getMatch(matchId)!\n } else {\n return match\n }\n}\n\nexport async function loadMatches(arg: {\n router: AnyRouter\n location: ParsedLocation\n matches: Array<AnyRouteMatch>\n preload?: boolean\n onReady?: () => Promise<void>\n updateMatch: UpdateMatchFn\n sync?: boolean\n}): Promise<Array<MakeRouteMatch>> {\n const inner: InnerLoadContext = arg\n const matchPromises: Array<Promise<AnyRouteMatch>> = []\n\n // make sure the pending component is immediately rendered when hydrating a match that is not SSRed\n // the pending component was already rendered on the server and we want to keep it shown on the client until minPendingMs is reached\n if (\n !(isServer ?? inner.router.isServer) &&\n inner.router.state.matches.some((d) => d._forcePending)\n ) {\n triggerOnReady(inner)\n }\n\n let beforeLoadNotFound: NotFoundError | undefined\n\n // Execute all beforeLoads one by one\n for (let i = 0; i < inner.matches.length; i++) {\n try {\n const beforeLoad = handleBeforeLoad(inner, i)\n if (isPromise(beforeLoad)) await beforeLoad\n } catch (err) {\n if (isRedirect(err)) {\n throw err\n }\n if (isNotFound(err)) {\n beforeLoadNotFound = err\n } else {\n if (!inner.preload) throw err\n }\n break\n }\n\n if (inner.serialError) {\n break\n }\n }\n\n // Execute loaders once, with max index adapted for beforeLoad notFound handling.\n const baseMaxIndexExclusive = inner.firstBadMatchIndex ?? inner.matches.length\n\n const boundaryIndex =\n beforeLoadNotFound && !inner.preload\n ? getNotFoundBoundaryIndex(inner, beforeLoadNotFound)\n : undefined\n\n const maxIndexExclusive =\n beforeLoadNotFound && inner.preload\n ? 0\n : boundaryIndex !== undefined\n ? Math.min(boundaryIndex + 1, baseMaxIndexExclusive)\n : baseMaxIndexExclusive\n\n let firstNotFound: NotFoundError | undefined\n let firstUnhandledRejection: unknown\n\n for (let i = 0; i < maxIndexExclusive; i++) {\n matchPromises.push(loadRouteMatch(inner, matchPromises, i))\n }\n\n try {\n await Promise.all(matchPromises)\n } catch {\n const settled = await Promise.allSettled(matchPromises)\n\n for (const result of settled) {\n if (result.status !== 'rejected') continue\n\n const reason = result.reason\n if (isRedirect(reason)) {\n throw reason\n }\n if (isNotFound(reason)) {\n firstNotFound ??= reason\n } else {\n firstUnhandledRejection ??= reason\n }\n }\n\n if (firstUnhandledRejection !== undefined) {\n throw firstUnhandledRejection\n }\n }\n\n const notFoundToThrow =\n firstNotFound ??\n (beforeLoadNotFound && !inner.preload ? beforeLoadNotFound : undefined)\n\n let headMaxIndex = inner.serialError\n ? (inner.firstBadMatchIndex ?? 0)\n : inner.matches.length - 1\n\n if (!notFoundToThrow && beforeLoadNotFound && inner.preload) {\n return inner.matches\n }\n\n if (notFoundToThrow) {\n // Determine once which matched route will actually render the\n // notFoundComponent, then pass this precomputed index through the remaining\n // finalization steps.\n // This can differ from the throwing route when routeId targets an ancestor\n // boundary (or when bubbling resolves to a parent/root boundary).\n const renderedBoundaryIndex = getNotFoundBoundaryIndex(\n inner,\n notFoundToThrow,\n )\n\n invariant(\n renderedBoundaryIndex !== undefined,\n 'Could not find match for notFound boundary',\n )\n const boundaryMatch = inner.matches[renderedBoundaryIndex]!\n\n const boundaryRoute = inner.router.looseRoutesById[boundaryMatch.routeId]!\n const defaultNotFoundComponent = (inner.router.options as any)\n ?.defaultNotFoundComponent\n\n // Ensure a notFoundComponent exists on the boundary route\n if (!boundaryRoute.options.notFoundComponent && defaultNotFoundComponent) {\n boundaryRoute.options.notFoundComponent = defaultNotFoundComponent\n }\n\n notFoundToThrow.routeId = boundaryMatch.routeId\n\n const boundaryIsRoot = boundaryMatch.routeId === inner.router.routeTree.id\n\n inner.updateMatch(boundaryMatch.id, (prev) => ({\n ...prev,\n ...(boundaryIsRoot\n ? // For root boundary, use globalNotFound so the root component's\n // shell still renders and <Outlet> handles the not-found display,\n // instead of replacing the entire root shell via status='notFound'.\n { status: 'success' as const, globalNotFound: true, error: undefined }\n : // For non-root boundaries, set status:'notFound' so MatchInner\n // renders the notFoundComponent directly.\n { status: 'notFound' as const, error: notFoundToThrow }),\n isFetching: false,\n }))\n\n headMaxIndex = renderedBoundaryIndex\n\n // Ensure the rendering boundary route chunk (and its lazy components, including\n // lazy notFoundComponent) is loaded before we continue to head execution/render.\n await loadRouteChunk(boundaryRoute)\n } else if (!inner.preload) {\n // Clear stale root global-not-found state on normal navigations that do not\n // throw notFound. This must live here (instead of only in runLoader success)\n // because the root loader may be skipped when data is still fresh.\n const rootMatch = inner.matches[0]!\n // `rootMatch` is the next match for this navigation. If it is not global\n // not-found, then any currently stored root global-not-found is stale.\n if (!rootMatch.globalNotFound) {\n // `currentRootMatch` is the current store state (from the previous\n // navigation/load). Update only when a stale flag is actually present.\n const currentRootMatch = inner.router.getMatch(rootMatch.id)\n if (currentRootMatch?.globalNotFound) {\n inner.updateMatch(rootMatch.id, (prev) => ({\n ...prev,\n globalNotFound: false,\n error: undefined,\n }))\n }\n }\n }\n\n // When a serial error occurred (e.g. beforeLoad threw a regular Error),\n // the erroring route's lazy chunk wasn't loaded because loaders were skipped.\n // We need to load it so the code-split errorComponent is available for rendering.\n if (inner.serialError && inner.firstBadMatchIndex !== undefined) {\n const errorRoute =\n inner.router.looseRoutesById[\n inner.matches[inner.firstBadMatchIndex]!.routeId\n ]!\n await loadRouteChunk(errorRoute)\n }\n\n // serially execute heads once after loaders/notFound handling, ensuring\n // all head functions get a chance even if one throws.\n for (let i = 0; i <= headMaxIndex; i++) {\n const match = inner.matches[i]!\n const { id: matchId, routeId } = match\n const route = inner.router.looseRoutesById[routeId]!\n try {\n const headResult = executeHead(inner, matchId, route)\n if (headResult) {\n const head = await headResult\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n ...head,\n }))\n }\n } catch (err) {\n console.error(`Error executing head for route ${routeId}:`, err)\n }\n }\n\n const readyPromise = triggerOnReady(inner)\n if (isPromise(readyPromise)) {\n await readyPromise\n }\n\n if (notFoundToThrow) {\n throw notFoundToThrow\n }\n\n if (inner.serialError && !inner.preload && !inner.onReady) {\n throw inner.serialError\n }\n\n return inner.matches\n}\n\nexport async function loadRouteChunk(route: AnyRoute) {\n if (!route._lazyLoaded && route._lazyPromise === undefined) {\n if (route.lazyFn) {\n route._lazyPromise = route.lazyFn().then((lazyRoute) => {\n // explicitly don't copy over the lazy route's id\n const { id: _id, ...options } = lazyRoute.options\n Object.assign(route.options, options)\n route._lazyLoaded = true\n route._lazyPromise = undefined // gc promise, we won't need it anymore\n })\n } else {\n route._lazyLoaded = true\n }\n }\n\n // If for some reason lazy resolves more lazy components...\n // We'll wait for that before we attempt to preload the\n // components themselves.\n if (!route._componentsLoaded && route._componentsPromise === undefined) {\n const loadComponents = () => {\n const preloads = []\n for (const type of componentTypes) {\n const preload = (route.options[type] as any)?.preload\n if (preload) preloads.push(preload())\n }\n if (preloads.length)\n return Promise.all(preloads).then(() => {\n route._componentsLoaded = true\n route._componentsPromise = undefined // gc promise, we won't need it anymore\n })\n route._componentsLoaded = true\n route._componentsPromise = undefined // gc promise, we won't need it anymore\n return\n }\n route._componentsPromise = route._lazyPromise\n ? route._lazyPromise.then(loadComponents)\n : loadComponents()\n }\n return route._componentsPromise\n}\n\nfunction makeMaybe<TValue, TError>(\n value: TValue,\n error: TError,\n): { status: 'success'; value: TValue } | { status: 'error'; error: TError } {\n if (error) {\n return { status: 'error' as const, error }\n }\n return { status: 'success' as const, value }\n}\n\nexport function routeNeedsPreload(route: AnyRoute) {\n for (const componentType of componentTypes) {\n if ((route.options[componentType] as any)?.preload) {\n return true\n }\n }\n return false\n}\n\nexport const componentTypes = [\n 'component',\n 'errorComponent',\n 'pendingComponent',\n 'notFoundComponent',\n] as const\n"],"names":["tempSsr","beforeLoadContext","match","route"],"mappings":";;;;;;;AAuCA,MAAM,iBAAiB,CAAC,UAAkD;AACxE,MAAI,CAAC,MAAM,UAAU;AACnB,UAAM,WAAW;AACjB,WAAO,MAAM,UAAA;AAAA,EACf;AACF;AAEA,MAAM,iBAAiB,CAAC,OAAyB,YAA6B;AAC5E,SAAO,CAAC,EACN,MAAM,WAAW,CAAC,MAAM,OAAO,MAAM,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO;AAE7E;AAMA,MAAM,oBAAoB,CACxB,OACA,OACA,sBAA+B,SACH;AAC5B,QAAM,UAAmC;AAAA,IACvC,GAAI,MAAM,OAAO,QAAQ,WAAW,CAAA;AAAA,EAAC;AAEvC,QAAM,MAAM,sBAAsB,QAAQ,QAAQ;AAClD,WAAS,IAAI,GAAG,KAAK,KAAK,KAAK;AAC7B,UAAM,aA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;AAAA,IACtB;AAAA,EACF;AAKA,MAAI,CAAC,MAAM,qBAAqB,MAAM,uBAAuB,QAAW;AACtE,UAAM,iBAAiB,MAAM;AAC3B,YAAM,WAAW,CAAA;AACjB,iBAAW,QAAQ,gBAAgB;AACjC,cAAM,UAAW,MAAM,QAAQ,IAAI,GAAW;AAC9C,YAAI,QAAS,UAAS,KAAK,QAAA,CAAS;AAAA,MACtC;AACA,UAAI,SAAS;AACX,eAAO,QAAQ,IAAI,QAAQ,EAAE,KAAK,MAAM;AACtC,gBAAM,oBAAoB;AAC1B,gBAAM,qBAAqB;AAAA,QAC7B,CAAC;AACH,YAAM,oBAAoB;AAC1B,YAAM,qBAAqB;AAC3B;AAAA,IACF;AACA,UAAM,qBAAqB,MAAM,eAC7B,MAAM,aAAa,KAAK,cAAc,IACtC,eAAA;AAAA,EACN;AACA,SAAO,MAAM;AACf;AAEA,SAAS,UACP,OACA,OAC2E;AAC3E,MAAI,OAAO;AACT,WAAO,EAAE,QAAQ,SAAkB,MAAA;AAAA,EACrC;AACA,SAAO,EAAE,QAAQ,WAAoB,MAAA;AACvC;AAEO,SAAS,kBAAkB,OAAiB;AACjD,aAAW,iBAAiB,gBAAgB;AAC1C,QAAK,MAAM,QAAQ,aAAa,GAAW,SAAS;AAClD,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAEO,MAAM,iBAAiB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;"}
@@ -11,6 +11,9 @@ function hydrateMatch(match, deyhydratedMatch) {
11
11
  match.ssr = deyhydratedMatch.ssr;
12
12
  match.updatedAt = deyhydratedMatch.u;
13
13
  match.error = deyhydratedMatch.e;
14
+ if (deyhydratedMatch.g !== void 0) {
15
+ match.globalNotFound = deyhydratedMatch.g;
16
+ }
14
17
  }
15
18
  async function hydrate(router) {
16
19
  invariant(
@@ -51,10 +54,9 @@ async function hydrate(router) {
51
54
  };
52
55
  const matches = router.matchRoutes(router.state.location);
53
56
  const routeChunkPromise = Promise.all(
54
- matches.map((match) => {
55
- const route = router.looseRoutesById[match.routeId];
56
- return router.loadRouteChunk(route);
57
- })
57
+ matches.map(
58
+ (match) => router.loadRouteChunk(router.looseRoutesById[match.routeId])
59
+ )
58
60
  );
59
61
  function setMatchForcePending(match) {
60
62
  const route = router.looseRoutesById[match.routeId];
@@ -102,12 +104,10 @@ async function hydrate(router) {
102
104
  }
103
105
  }
104
106
  });
105
- router.__store.setState((s) => {
106
- return {
107
- ...s,
108
- matches
109
- };
110
- });
107
+ router.__store.setState((s) => ({
108
+ ...s,
109
+ matches
110
+ }));
111
111
  await router.options.hydrate?.(dehydratedData);
112
112
  await Promise.all(
113
113
  router.state.matches.map(async (match) => {
@@ -200,13 +200,11 @@ async function hydrate(router) {
200
200
  resolvedLocation: s.location
201
201
  }));
202
202
  }
203
- router.updateMatch(match.id, (prev) => {
204
- return {
205
- ...prev,
206
- _displayPending: void 0,
207
- displayPendingPromise: void 0
208
- };
209
- });
203
+ router.updateMatch(match.id, (prev) => ({
204
+ ...prev,
205
+ _displayPending: void 0,
206
+ displayPendingPromise: void 0
207
+ }));
210
208
  });
211
209
  });
212
210
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ssr-client.js","sources":["../../../src/ssr/ssr-client.ts"],"sourcesContent":["import invariant from 'tiny-invariant'\nimport { batch } from '../utils/batch'\nimport { isNotFound } from '../not-found'\nimport { createControlledPromise } from '../utils'\nimport { hydrateSsrMatchId } from './ssr-match-id'\nimport type { GLOBAL_SEROVAL, GLOBAL_TSR } from './constants'\nimport type { DehydratedMatch, TsrSsrGlobal } from './types'\nimport type { AnyRouteMatch } from '../Matches'\nimport type { AnyRouter } from '../router'\nimport type { RouteContextOptions } from '../route'\nimport type { AnySerializationAdapter } from './serializer/transformer'\n\ndeclare global {\n interface Window {\n [GLOBAL_TSR]?: TsrSsrGlobal\n [GLOBAL_SEROVAL]?: any\n }\n}\n\nfunction hydrateMatch(\n match: AnyRouteMatch,\n deyhydratedMatch: DehydratedMatch,\n): void {\n match.id = deyhydratedMatch.i\n match.__beforeLoadContext = deyhydratedMatch.b\n match.loaderData = deyhydratedMatch.l\n match.status = deyhydratedMatch.s\n match.ssr = deyhydratedMatch.ssr\n match.updatedAt = deyhydratedMatch.u\n match.error = deyhydratedMatch.e\n}\n\nexport async function hydrate(router: AnyRouter): Promise<any> {\n invariant(\n window.$_TSR,\n 'Expected to find bootstrap data on window.$_TSR, but we did not. Please file an issue!',\n )\n\n const serializationAdapters = router.options.serializationAdapters as\n | Array<AnySerializationAdapter>\n | undefined\n\n if (serializationAdapters?.length) {\n const fromSerializableMap = new Map()\n serializationAdapters.forEach((adapter) => {\n fromSerializableMap.set(adapter.key, adapter.fromSerializable)\n })\n window.$_TSR.t = fromSerializableMap\n window.$_TSR.buffer.forEach((script) => script())\n }\n window.$_TSR.initialized = true\n\n invariant(\n window.$_TSR.router,\n 'Expected to find a dehydrated data on window.$_TSR.router, but we did not. Please file an issue!',\n )\n\n const dehydratedRouter = window.$_TSR.router\n dehydratedRouter.matches.forEach((dehydratedMatch) => {\n dehydratedMatch.i = hydrateSsrMatchId(dehydratedMatch.i)\n })\n if (dehydratedRouter.lastMatchId) {\n dehydratedRouter.lastMatchId = hydrateSsrMatchId(\n dehydratedRouter.lastMatchId,\n )\n }\n const { manifest, dehydratedData, lastMatchId } = dehydratedRouter\n\n router.ssr = {\n manifest,\n }\n const meta = document.querySelector('meta[property=\"csp-nonce\"]') as\n | HTMLMetaElement\n | undefined\n const nonce = meta?.content\n router.options.ssr = {\n nonce,\n }\n\n // Hydrate the router state\n const matches = router.matchRoutes(router.state.location)\n\n // kick off loading the route chunks\n const routeChunkPromise = Promise.all(\n matches.map((match) => {\n const route = router.looseRoutesById[match.routeId]!\n return router.loadRouteChunk(route)\n }),\n )\n\n function setMatchForcePending(match: AnyRouteMatch) {\n // usually the minPendingPromise is created in the Match component if a pending match is rendered\n // however, this might be too late if the match synchronously resolves\n const route = router.looseRoutesById[match.routeId]!\n const pendingMinMs =\n route.options.pendingMinMs ?? router.options.defaultPendingMinMs\n if (pendingMinMs) {\n const minPendingPromise = createControlledPromise<void>()\n match._nonReactive.minPendingPromise = minPendingPromise\n match._forcePending = true\n\n setTimeout(() => {\n minPendingPromise.resolve()\n // We've handled the minPendingPromise, so we can delete it\n router.updateMatch(match.id, (prev) => {\n prev._nonReactive.minPendingPromise = undefined\n return {\n ...prev,\n _forcePending: undefined,\n }\n })\n }, pendingMinMs)\n }\n }\n\n function setRouteSsr(match: AnyRouteMatch) {\n const route = router.looseRoutesById[match.routeId]\n if (route) {\n route.options.ssr = match.ssr\n }\n }\n // Right after hydration and before the first render, we need to rehydrate each match\n // First step is to reyhdrate loaderData and __beforeLoadContext\n let firstNonSsrMatchIndex: number | undefined = undefined\n matches.forEach((match) => {\n const dehydratedMatch = dehydratedRouter.matches.find(\n (d) => d.i === match.id,\n )\n if (!dehydratedMatch) {\n match._nonReactive.dehydrated = false\n match.ssr = false\n setRouteSsr(match)\n return\n }\n\n hydrateMatch(match, dehydratedMatch)\n setRouteSsr(match)\n\n match._nonReactive.dehydrated = match.ssr !== false\n\n if (match.ssr === 'data-only' || match.ssr === false) {\n if (firstNonSsrMatchIndex === undefined) {\n firstNonSsrMatchIndex = match.index\n setMatchForcePending(match)\n }\n }\n })\n\n router.__store.setState((s) => {\n return {\n ...s,\n matches,\n }\n })\n\n // Allow the user to handle custom hydration data\n await router.options.hydrate?.(dehydratedData)\n\n // now that all necessary data is hydrated:\n // 1) fully reconstruct the route context\n // 2) execute `head()` and `scripts()` for each match\n await Promise.all(\n router.state.matches.map(async (match) => {\n try {\n const route = router.looseRoutesById[match.routeId]!\n\n const parentMatch = router.state.matches[match.index - 1]\n const parentContext = parentMatch?.context ?? router.options.context\n\n // `context()` was already executed by `matchRoutes`, however route context was not yet fully reconstructed\n // so run it again and merge route context\n if (route.options.context) {\n const contextFnContext: RouteContextOptions<any, any, any, any, any> =\n {\n deps: match.loaderDeps,\n params: match.params,\n context: parentContext ?? {},\n location: router.state.location,\n navigate: (opts: any) =>\n router.navigate({\n ...opts,\n _fromLocation: router.state.location,\n }),\n buildLocation: router.buildLocation,\n cause: match.cause,\n abortController: match.abortController,\n preload: false,\n matches,\n routeId: route.id,\n }\n match.__routeContext =\n route.options.context(contextFnContext) ?? undefined\n }\n\n match.context = {\n ...parentContext,\n ...match.__routeContext,\n ...match.__beforeLoadContext,\n }\n\n const assetContext = {\n ssr: router.options.ssr,\n matches: router.state.matches,\n match,\n params: match.params,\n loaderData: match.loaderData,\n }\n const headFnContent = await route.options.head?.(assetContext)\n\n const scripts = await route.options.scripts?.(assetContext)\n\n match.meta = headFnContent?.meta\n match.links = headFnContent?.links\n match.headScripts = headFnContent?.scripts\n match.styles = headFnContent?.styles\n match.scripts = scripts\n } catch (err) {\n if (isNotFound(err)) {\n match.error = { isNotFound: true }\n console.error(\n `NotFound error during hydration for routeId: ${match.routeId}`,\n err,\n )\n } else {\n match.error = err as any\n console.error(\n `Error during hydration for route ${match.routeId}:`,\n err,\n )\n throw err\n }\n }\n }),\n )\n\n const isSpaMode = matches[matches.length - 1]!.id !== lastMatchId\n const hasSsrFalseMatches = matches.some((m) => m.ssr === false)\n // all matches have data from the server and we are not in SPA mode so we don't need to kick of router.load()\n if (!hasSsrFalseMatches && !isSpaMode) {\n matches.forEach((match) => {\n // remove the dehydrated flag since we won't run router.load() which would remove it\n match._nonReactive.dehydrated = undefined\n })\n return routeChunkPromise\n }\n\n // schedule router.load() to run after the next tick so we can store the promise in the match before loading starts\n const loadPromise = Promise.resolve()\n .then(() => router.load())\n .catch((err) => {\n console.error('Error during router hydration:', err)\n })\n\n // in SPA mode we need to keep the first match below the root route pending until router.load() is finished\n // this will prevent that other pending components are rendered but hydration is not blocked\n if (isSpaMode) {\n const match = matches[1]\n invariant(\n match,\n 'Expected to find a match below the root match in SPA mode.',\n )\n setMatchForcePending(match)\n\n match._displayPending = true\n match._nonReactive.displayPendingPromise = loadPromise\n\n loadPromise.then(() => {\n batch(() => {\n // ensure router is not in status 'pending' anymore\n // this usually happens in Transitioner but if loading synchronously resolves,\n // Transitioner won't be rendered while loading so it cannot track the change from loading:true to loading:false\n if (router.__store.state.status === 'pending') {\n router.__store.setState((s) => ({\n ...s,\n status: 'idle',\n resolvedLocation: s.location,\n }))\n }\n // hide the pending component once the load is finished\n router.updateMatch(match.id, (prev) => {\n return {\n ...prev,\n _displayPending: undefined,\n displayPendingPromise: undefined,\n }\n })\n })\n })\n }\n return routeChunkPromise\n}\n"],"names":[],"mappings":";;;;;AAmBA,SAAS,aACP,OACA,kBACM;AACN,QAAM,KAAK,iBAAiB;AAC5B,QAAM,sBAAsB,iBAAiB;AAC7C,QAAM,aAAa,iBAAiB;AACpC,QAAM,SAAS,iBAAiB;AAChC,QAAM,MAAM,iBAAiB;AAC7B,QAAM,YAAY,iBAAiB;AACnC,QAAM,QAAQ,iBAAiB;AACjC;AAEA,eAAsB,QAAQ,QAAiC;AAC7D;AAAA,IACE,OAAO;AAAA,IACP;AAAA,EAAA;AAGF,QAAM,wBAAwB,OAAO,QAAQ;AAI7C,MAAI,uBAAuB,QAAQ;AACjC,UAAM,0CAA0B,IAAA;AAChC,0BAAsB,QAAQ,CAAC,YAAY;AACzC,0BAAoB,IAAI,QAAQ,KAAK,QAAQ,gBAAgB;AAAA,IAC/D,CAAC;AACD,WAAO,MAAM,IAAI;AACjB,WAAO,MAAM,OAAO,QAAQ,CAAC,WAAW,QAAQ;AAAA,EAClD;AACA,SAAO,MAAM,cAAc;AAE3B;AAAA,IACE,OAAO,MAAM;AAAA,IACb;AAAA,EAAA;AAGF,QAAM,mBAAmB,OAAO,MAAM;AACtC,mBAAiB,QAAQ,QAAQ,CAAC,oBAAoB;AACpD,oBAAgB,IAAI,kBAAkB,gBAAgB,CAAC;AAAA,EACzD,CAAC;AACD,MAAI,iBAAiB,aAAa;AAChC,qBAAiB,cAAc;AAAA,MAC7B,iBAAiB;AAAA,IAAA;AAAA,EAErB;AACA,QAAM,EAAE,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Aa,wBAAwB;AAE3C,gBAAY,KAAK,MAAM;AACrB,YAAM,MAAM;AAIV,YAAI,OAAO,QAAQ,MAAM,WAAW,WAAW;AAC7C,iBAAO,QAAQ,SAAS,CAAC,OAAO;AAAA,YAC9B,GAAG;AAAA,YACH,QAAQ;AAAA,YACR,kBAAkB,EAAE;AAAA,UAAA,EACpB;AAAA,QACJ;AAEA,eAAO,YAAY,MAAM,IAAI,CAAC,SAAS;AACrC,iBAAO;AAAA,YACL,GAAG;AAAA,YACH,iBAAiB;AAAA,YACjB,uBAAuB;AAAA,UAAA;AAAA,QAE3B,CAAC;AAAA,MACH,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACA,SAAO;AACT;"}
1
+ {"version":3,"file":"ssr-client.js","sources":["../../../src/ssr/ssr-client.ts"],"sourcesContent":["import invariant from 'tiny-invariant'\nimport { batch } from '../utils/batch'\nimport { isNotFound } from '../not-found'\nimport { createControlledPromise } from '../utils'\nimport { hydrateSsrMatchId } from './ssr-match-id'\nimport type { GLOBAL_SEROVAL, GLOBAL_TSR } from './constants'\nimport type { DehydratedMatch, TsrSsrGlobal } from './types'\nimport type { AnyRouteMatch } from '../Matches'\nimport type { AnyRouter } from '../router'\nimport type { RouteContextOptions } from '../route'\nimport type { AnySerializationAdapter } from './serializer/transformer'\n\ndeclare global {\n interface Window {\n [GLOBAL_TSR]?: TsrSsrGlobal\n [GLOBAL_SEROVAL]?: any\n }\n}\n\nfunction hydrateMatch(\n match: AnyRouteMatch,\n deyhydratedMatch: DehydratedMatch,\n): void {\n match.id = deyhydratedMatch.i\n match.__beforeLoadContext = deyhydratedMatch.b\n match.loaderData = deyhydratedMatch.l\n match.status = deyhydratedMatch.s\n match.ssr = deyhydratedMatch.ssr\n match.updatedAt = deyhydratedMatch.u\n match.error = deyhydratedMatch.e\n // Only hydrate global-not-found when a defined value is present in the\n // dehydrated payload. If omitted, preserve the value computed from the\n // current client location (important for SPA fallback HTML served at unknown\n // URLs, where dehydrated matches may come from `/` but client matching marks\n // root as globalNotFound).\n if (deyhydratedMatch.g !== undefined) {\n match.globalNotFound = deyhydratedMatch.g\n }\n}\n\nexport async function hydrate(router: AnyRouter): Promise<any> {\n invariant(\n window.$_TSR,\n 'Expected to find bootstrap data on window.$_TSR, but we did not. Please file an issue!',\n )\n\n const serializationAdapters = router.options.serializationAdapters as\n | Array<AnySerializationAdapter>\n | undefined\n\n if (serializationAdapters?.length) {\n const fromSerializableMap = new Map()\n serializationAdapters.forEach((adapter) => {\n fromSerializableMap.set(adapter.key, adapter.fromSerializable)\n })\n window.$_TSR.t = fromSerializableMap\n window.$_TSR.buffer.forEach((script) => script())\n }\n window.$_TSR.initialized = true\n\n invariant(\n window.$_TSR.router,\n 'Expected to find a dehydrated data on window.$_TSR.router, but we did not. Please file an issue!',\n )\n\n const dehydratedRouter = window.$_TSR.router\n dehydratedRouter.matches.forEach((dehydratedMatch) => {\n dehydratedMatch.i = hydrateSsrMatchId(dehydratedMatch.i)\n })\n if (dehydratedRouter.lastMatchId) {\n dehydratedRouter.lastMatchId = hydrateSsrMatchId(\n dehydratedRouter.lastMatchId,\n )\n }\n const { manifest, dehydratedData, lastMatchId } = dehydratedRouter\n\n router.ssr = {\n manifest,\n }\n const meta = document.querySelector('meta[property=\"csp-nonce\"]') as\n | HTMLMetaElement\n | undefined\n const nonce = meta?.content\n router.options.ssr = {\n nonce,\n }\n\n // Hydrate the router state\n const matches = router.matchRoutes(router.state.location)\n\n // kick off loading the route chunks\n const routeChunkPromise = Promise.all(\n matches.map((match) =>\n router.loadRouteChunk(router.looseRoutesById[match.routeId]!),\n ),\n )\n\n function setMatchForcePending(match: AnyRouteMatch) {\n // usually the minPendingPromise is created in the Match component if a pending match is rendered\n // however, this might be too late if the match synchronously resolves\n const route = router.looseRoutesById[match.routeId]!\n const pendingMinMs =\n route.options.pendingMinMs ?? router.options.defaultPendingMinMs\n if (pendingMinMs) {\n const minPendingPromise = createControlledPromise<void>()\n match._nonReactive.minPendingPromise = minPendingPromise\n match._forcePending = true\n\n setTimeout(() => {\n minPendingPromise.resolve()\n // We've handled the minPendingPromise, so we can delete it\n router.updateMatch(match.id, (prev) => {\n prev._nonReactive.minPendingPromise = undefined\n return {\n ...prev,\n _forcePending: undefined,\n }\n })\n }, pendingMinMs)\n }\n }\n\n function setRouteSsr(match: AnyRouteMatch) {\n const route = router.looseRoutesById[match.routeId]\n if (route) {\n route.options.ssr = match.ssr\n }\n }\n // Right after hydration and before the first render, we need to rehydrate each match\n // First step is to reyhdrate loaderData and __beforeLoadContext\n let firstNonSsrMatchIndex: number | undefined = undefined\n matches.forEach((match) => {\n const dehydratedMatch = dehydratedRouter.matches.find(\n (d) => d.i === match.id,\n )\n if (!dehydratedMatch) {\n match._nonReactive.dehydrated = false\n match.ssr = false\n setRouteSsr(match)\n return\n }\n\n hydrateMatch(match, dehydratedMatch)\n setRouteSsr(match)\n\n match._nonReactive.dehydrated = match.ssr !== false\n\n if (match.ssr === 'data-only' || match.ssr === false) {\n if (firstNonSsrMatchIndex === undefined) {\n firstNonSsrMatchIndex = match.index\n setMatchForcePending(match)\n }\n }\n })\n\n router.__store.setState((s) => ({\n ...s,\n matches,\n }))\n\n // Allow the user to handle custom hydration data\n await router.options.hydrate?.(dehydratedData)\n\n // now that all necessary data is hydrated:\n // 1) fully reconstruct the route context\n // 2) execute `head()` and `scripts()` for each match\n await Promise.all(\n router.state.matches.map(async (match) => {\n try {\n const route = router.looseRoutesById[match.routeId]!\n\n const parentMatch = router.state.matches[match.index - 1]\n const parentContext = parentMatch?.context ?? router.options.context\n\n // `context()` was already executed by `matchRoutes`, however route context was not yet fully reconstructed\n // so run it again and merge route context\n if (route.options.context) {\n const contextFnContext: RouteContextOptions<any, any, any, any, any> =\n {\n deps: match.loaderDeps,\n params: match.params,\n context: parentContext ?? {},\n location: router.state.location,\n navigate: (opts: any) =>\n router.navigate({\n ...opts,\n _fromLocation: router.state.location,\n }),\n buildLocation: router.buildLocation,\n cause: match.cause,\n abortController: match.abortController,\n preload: false,\n matches,\n routeId: route.id,\n }\n match.__routeContext =\n route.options.context(contextFnContext) ?? undefined\n }\n\n match.context = {\n ...parentContext,\n ...match.__routeContext,\n ...match.__beforeLoadContext,\n }\n\n const assetContext = {\n ssr: router.options.ssr,\n matches: router.state.matches,\n match,\n params: match.params,\n loaderData: match.loaderData,\n }\n const headFnContent = await route.options.head?.(assetContext)\n\n const scripts = await route.options.scripts?.(assetContext)\n\n match.meta = headFnContent?.meta\n match.links = headFnContent?.links\n match.headScripts = headFnContent?.scripts\n match.styles = headFnContent?.styles\n match.scripts = scripts\n } catch (err) {\n if (isNotFound(err)) {\n match.error = { isNotFound: true }\n console.error(\n `NotFound error during hydration for routeId: ${match.routeId}`,\n err,\n )\n } else {\n match.error = err as any\n console.error(\n `Error during hydration for route ${match.routeId}:`,\n err,\n )\n throw err\n }\n }\n }),\n )\n\n const isSpaMode = matches[matches.length - 1]!.id !== lastMatchId\n const hasSsrFalseMatches = matches.some((m) => m.ssr === false)\n // all matches have data from the server and we are not in SPA mode so we don't need to kick of router.load()\n if (!hasSsrFalseMatches && !isSpaMode) {\n matches.forEach((match) => {\n // remove the dehydrated flag since we won't run router.load() which would remove it\n match._nonReactive.dehydrated = undefined\n })\n return routeChunkPromise\n }\n\n // schedule router.load() to run after the next tick so we can store the promise in the match before loading starts\n const loadPromise = Promise.resolve()\n .then(() => router.load())\n .catch((err) => {\n console.error('Error during router hydration:', err)\n })\n\n // in SPA mode we need to keep the first match below the root route pending until router.load() is finished\n // this will prevent that other pending components are rendered but hydration is not blocked\n if (isSpaMode) {\n const match = matches[1]\n invariant(\n match,\n 'Expected to find a match below the root match in SPA mode.',\n )\n setMatchForcePending(match)\n\n match._displayPending = true\n match._nonReactive.displayPendingPromise = loadPromise\n\n loadPromise.then(() => {\n batch(() => {\n // ensure router is not in status 'pending' anymore\n // this usually happens in Transitioner but if loading synchronously resolves,\n // Transitioner won't be rendered while loading so it cannot track the change from loading:true to loading:false\n if (router.__store.state.status === 'pending') {\n router.__store.setState((s) => ({\n ...s,\n status: 'idle',\n resolvedLocation: s.location,\n }))\n }\n // hide the pending component once the load is finished\n router.updateMatch(match.id, (prev) => ({\n ...prev,\n _displayPending: undefined,\n displayPendingPromise: undefined,\n }))\n })\n })\n }\n return routeChunkPromise\n}\n"],"names":[],"mappings":";;;;;AAmBA,SAAS,aACP,OACA,kBACM;AACN,QAAM,KAAK,iBAAiB;AAC5B,QAAM,sBAAsB,iBAAiB;AAC7C,QAAM,aAAa,iBAAiB;AACpC,QAAM,SAAS,iBAAiB;AAChC,QAAM,MAAM,iBAAiB;AAC7B,QAAM,YAAY,iBAAiB;AACnC,QAAM,QAAQ,iBAAiB;AAM/B,MAAI,iBAAiB,MAAM,QAAW;AACpC,UAAM,iBAAiB,iBAAiB;AAAA,EAC1C;AACF;AAEA,eAAsB,QAAQ,QAAiC;AAC7D;AAAA,IACE,OAAO;AAAA,IACP;AAAA,EAAA;AAGF,QAAM,wBAAwB,OAAO,QAAQ;AAI7C,MAAI,uBAAuB,QAAQ;AACjC,UAAM,0CAA0B,IAAA;AAChC,0BAAsB,QAAQ,CAAC,YAAY;AACzC,0BAAoB,IAAI,QAAQ,KAAK,QAAQ,gBAAgB;AAAA,IAC/D,CAAC;AACD,WAAO,MAAM,IAAI;AACjB,WAAO,MAAM,OAAO,QAAQ,CAAC,WAAW,QAAQ;AAAA,EAClD;AACA,SAAO,MAAM,cAAc;AAE3B;AAAA,IACE,OAAO,MAAM;AAAA,IACb;AAAA,EAAA;AAGF,QAAM,mBAAmB,OAAO,MAAM;AACtC,mBAAiB,QAAQ,QAAQ,CAAC,oBAAoB;AACpD,oBAAgB,IAAI,kBAAkB,gBAAgB,CAAC;AAAA,EACzD,CAAC;AACD,MAAI,iBAAiB,aAAa;AAChC,qBAAiB,cAAc;AAAA,MAC7B,iBAAiB;AAAA,IAAA;AAAA,EAErB;AACA,QAAM,EAAE,UAAU,gBAAgB,YAAA,IAAgB;AAElD,SAAO,MAAM;AAAA,IACX;A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QAAQ,SAAS,CAAC,OAAO;AAAA,YAC9B,GAAG;AAAA,YACH,QAAQ;AAAA,YACR,kBAAkB,EAAE;AAAA,UAAA,EACpB;AAAA,QACJ;AAEA,eAAO,YAAY,MAAM,IAAI,CAAC,UAAU;AAAA,UACtC,GAAG;AAAA,UACH,iBAAiB;AAAA,UACjB,uBAAuB;AAAA,QAAA,EACvB;AAAA,MACJ,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACA,SAAO;AACT;"}
@@ -28,6 +28,9 @@ function dehydrateMatch(match) {
28
28
  dehydratedMatch[shorthand] = match[key];
29
29
  }
30
30
  }
31
+ if (match.globalNotFound) {
32
+ dehydratedMatch.g = true;
33
+ }
31
34
  return dehydratedMatch;
32
35
  }
33
36
  const INITIAL_SCRIPTS = [
@@ -1 +1 @@
1
- {"version":3,"file":"ssr-server.js","sources":["../../../src/ssr/ssr-server.ts"],"sourcesContent":["import { crossSerializeStream, getCrossReferenceHeader } from 'seroval'\nimport invariant from 'tiny-invariant'\nimport { decodePath } from '../utils'\nimport { createLRUCache } from '../lru-cache'\nimport minifiedTsrBootStrapScript from './tsrScript?script-string'\nimport { GLOBAL_TSR, TSR_SCRIPT_BARRIER_ID } from './constants'\nimport { dehydrateSsrMatchId } from './ssr-match-id'\nimport { defaultSerovalPlugins } from './serializer/seroval-plugins'\nimport { makeSsrSerovalPlugin } from './serializer/transformer'\nimport type { LRUCache } from '../lru-cache'\nimport type { DehydratedMatch, DehydratedRouter } from './types'\nimport type { AnySerializationAdapter } from './serializer/transformer'\nimport type { AnyRouter } from '../router'\nimport type { AnyRouteMatch } from '../Matches'\nimport type { Manifest, RouterManagedTag } from '../manifest'\n\ndeclare module '../router' {\n interface ServerSsr {\n setRenderFinished: () => void\n cleanup: () => void\n }\n interface RouterEvents {\n onInjectedHtml: {\n type: 'onInjectedHtml'\n }\n onSerializationFinished: {\n type: 'onSerializationFinished'\n }\n }\n}\n\nconst SCOPE_ID = 'tsr'\n\nconst TSR_PREFIX = GLOBAL_TSR + '.router='\nconst P_PREFIX = GLOBAL_TSR + '.p(()=>'\nconst P_SUFFIX = ')'\n\nexport function dehydrateMatch(match: AnyRouteMatch): DehydratedMatch {\n const dehydratedMatch: DehydratedMatch = {\n i: dehydrateSsrMatchId(match.id),\n u: match.updatedAt,\n s: match.status,\n }\n\n const properties = [\n ['__beforeLoadContext', 'b'],\n ['loaderData', 'l'],\n ['error', 'e'],\n ['ssr', 'ssr'],\n ] as const\n\n for (const [key, shorthand] of properties) {\n if (match[key] !== undefined) {\n dehydratedMatch[shorthand] = match[key]\n }\n }\n return dehydratedMatch\n}\n\nconst INITIAL_SCRIPTS = [\n getCrossReferenceHeader(SCOPE_ID),\n minifiedTsrBootStrapScript,\n]\n\nclass ScriptBuffer {\n private router: AnyRouter | undefined\n private _queue: Array<string>\n private _scriptBarrierLifted = false\n private _cleanedUp = false\n private _pendingMicrotask = false\n\n constructor(router: AnyRouter) {\n this.router = router\n // Copy INITIAL_SCRIPTS to avoid mutating the shared array\n this._queue = INITIAL_SCRIPTS.slice()\n }\n\n enqueue(script: string) {\n if (this._cleanedUp) return\n this._queue.push(script)\n // If barrier is lifted, schedule injection (if not already scheduled)\n if (this._scriptBarrierLifted && !this._pendingMicrotask) {\n this._pendingMicrotask = true\n queueMicrotask(() => {\n this._pendingMicrotask = false\n this.injectBufferedScripts()\n })\n }\n }\n\n liftBarrier() {\n if (this._scriptBarrierLifted || this._cleanedUp) return\n this._scriptBarrierLifted = true\n if (this._queue.length > 0 && !this._pendingMicrotask) {\n this._pendingMicrotask = true\n queueMicrotask(() => {\n this._pendingMicrotask = false\n this.injectBufferedScripts()\n })\n }\n }\n\n /**\n * Flushes any pending scripts synchronously.\n * Call this before emitting onSerializationFinished to ensure all scripts are injected.\n *\n * IMPORTANT: Only injects if the barrier has been lifted. Before the barrier is lifted,\n * scripts should remain in the queue so takeBufferedScripts() can retrieve them\n */\n flush() {\n if (!this._scriptBarrierLifted) return\n if (this._cleanedUp) return\n this._pendingMicrotask = false\n const scriptsToInject = this.takeAll()\n if (scriptsToInject && this.router?.serverSsr) {\n this.router.serverSsr.injectScript(scriptsToInject)\n }\n }\n\n takeAll() {\n const bufferedScripts = this._queue\n this._queue = []\n if (bufferedScripts.length === 0) {\n return undefined\n }\n // Optimization: if only one script, avoid join\n if (bufferedScripts.length === 1) {\n return bufferedScripts[0] + ';document.currentScript.remove()'\n }\n // Append cleanup script and join - avoid push() to not mutate then iterate\n return bufferedScripts.join(';') + ';document.currentScript.remove()'\n }\n\n injectBufferedScripts() {\n if (this._cleanedUp) return\n // Early return if queue is empty (avoids unnecessary takeAll() call)\n if (this._queue.length === 0) return\n const scriptsToInject = this.takeAll()\n if (scriptsToInject && this.router?.serverSsr) {\n this.router.serverSsr.injectScript(scriptsToInject)\n }\n }\n\n cleanup() {\n this._cleanedUp = true\n this._queue = []\n this.router = undefined\n }\n}\n\nconst isProd = process.env.NODE_ENV === 'production'\n\ntype FilteredRoutes = Manifest['routes']\n\ntype ManifestLRU = LRUCache<string, FilteredRoutes>\n\nconst MANIFEST_CACHE_SIZE = 100\nconst manifestCaches = new WeakMap<Manifest, ManifestLRU>()\n\nfunction getManifestCache(manifest: Manifest): ManifestLRU {\n const cache = manifestCaches.get(manifest)\n if (cache) return cache\n const newCache = createLRUCache<string, FilteredRoutes>(MANIFEST_CACHE_SIZE)\n manifestCaches.set(manifest, newCache)\n return newCache\n}\n\nexport function attachRouterServerSsrUtils({\n router,\n manifest,\n}: {\n router: AnyRouter\n manifest: Manifest | undefined\n}) {\n router.ssr = {\n manifest,\n }\n let _dehydrated = false\n let _serializationFinished = false\n const renderFinishedListeners: Array<() => void> = []\n const serializationFinishedListeners: Array<() => void> = []\n const scriptBuffer = new ScriptBuffer(router)\n let injectedHtmlBuffer = ''\n\n router.serverSsr = {\n injectHtml: (html: string) => {\n if (!html) return\n // Buffer the HTML so it can be retrieved via takeBufferedHtml()\n injectedHtmlBuffer += html\n // Emit event to notify subscribers that new HTML is available\n router.emit({\n type: 'onInjectedHtml',\n })\n },\n injectScript: (script: string) => {\n if (!script) return\n const html = `<script${router.options.ssr?.nonce ? ` nonce='${router.options.ssr.nonce}'` : ''}>${script}</script>`\n router.serverSsr!.injectHtml(html)\n },\n dehydrate: async () => {\n invariant(!_dehydrated, 'router is already dehydrated!')\n let matchesToDehydrate = router.state.matches\n if (router.isShell()) {\n // In SPA mode we only want to dehydrate the root match\n matchesToDehydrate = matchesToDehydrate.slice(0, 1)\n }\n const matches = matchesToDehydrate.map(dehydrateMatch)\n\n let manifestToDehydrate: Manifest | undefined = undefined\n // For currently matched routes, send full manifest (preloads + assets)\n // For all other routes, only send assets (no preloads as they are handled via dynamic imports)\n if (manifest) {\n // Prod-only caching; in dev manifests may be replaced/updated (HMR)\n const currentRouteIdsList = matchesToDehydrate.map((m) => m.routeId)\n const manifestCacheKey = currentRouteIdsList.join('\\0')\n\n let filteredRoutes: FilteredRoutes | undefined\n\n if (isProd) {\n filteredRoutes = getManifestCache(manifest).get(manifestCacheKey)\n }\n\n if (!filteredRoutes) {\n const currentRouteIds = new Set(currentRouteIdsList)\n const nextFilteredRoutes: FilteredRoutes = {}\n\n for (const routeId in manifest.routes) {\n const routeManifest = manifest.routes[routeId]!\n if (currentRouteIds.has(routeId)) {\n nextFilteredRoutes[routeId] = routeManifest\n } else if (\n routeManifest.assets &&\n routeManifest.assets.length > 0\n ) {\n nextFilteredRoutes[routeId] = {\n assets: routeManifest.assets,\n }\n }\n }\n\n if (isProd) {\n getManifestCache(manifest).set(manifestCacheKey, nextFilteredRoutes)\n }\n\n filteredRoutes = nextFilteredRoutes\n }\n\n manifestToDehydrate = {\n routes: filteredRoutes,\n }\n }\n const dehydratedRouter: DehydratedRouter = {\n manifest: manifestToDehydrate,\n matches,\n }\n const lastMatchId = matchesToDehydrate[matchesToDehydrate.length - 1]?.id\n if (lastMatchId) {\n dehydratedRouter.lastMatchId = dehydrateSsrMatchId(lastMatchId)\n }\n const dehydratedData = await router.options.dehydrate?.()\n if (dehydratedData) {\n dehydratedRouter.dehydratedData = dehydratedData\n }\n _dehydrated = true\n\n const trackPlugins = { didRun: false }\n const serializationAdapters = router.options.serializationAdapters as\n | Array<AnySerializationAdapter>\n | undefined\n const plugins = serializationAdapters\n ? serializationAdapters\n .map((t) => makeSsrSerovalPlugin(t, trackPlugins))\n .concat(defaultSerovalPlugins)\n : defaultSerovalPlugins\n\n const signalSerializationComplete = () => {\n _serializationFinished = true\n try {\n serializationFinishedListeners.forEach((l) => l())\n router.emit({ type: 'onSerializationFinished' })\n } catch (err) {\n console.error('Serialization listener error:', err)\n } finally {\n serializationFinishedListeners.length = 0\n renderFinishedListeners.length = 0\n }\n }\n\n crossSerializeStream(dehydratedRouter, {\n refs: new Map(),\n plugins,\n onSerialize: (data, initial) => {\n let serialized = initial ? TSR_PREFIX + data : data\n if (trackPlugins.didRun) {\n serialized = P_PREFIX + serialized + P_SUFFIX\n }\n scriptBuffer.enqueue(serialized)\n },\n scopeId: SCOPE_ID,\n onDone: () => {\n scriptBuffer.enqueue(GLOBAL_TSR + '.e()')\n // Flush all pending scripts synchronously before signaling completion\n // This ensures all scripts are injected before onSerializationFinished is emitted\n scriptBuffer.flush()\n signalSerializationComplete()\n },\n onError: (err) => {\n console.error('Serialization error:', err)\n signalSerializationComplete()\n },\n })\n },\n isDehydrated() {\n return _dehydrated\n },\n isSerializationFinished() {\n return _serializationFinished\n },\n onRenderFinished: (listener) => renderFinishedListeners.push(listener),\n onSerializationFinished: (listener) =>\n serializationFinishedListeners.push(listener),\n setRenderFinished: () => {\n // Wrap in try-catch to ensure scriptBuffer.liftBarrier() is always called\n try {\n renderFinishedListeners.forEach((l) => l())\n } catch (err) {\n console.error('Error in render finished listener:', err)\n } finally {\n // Clear listeners after calling them to prevent memory leaks\n renderFinishedListeners.length = 0\n }\n scriptBuffer.liftBarrier()\n },\n takeBufferedScripts() {\n const scripts = scriptBuffer.takeAll()\n const serverBufferedScript: RouterManagedTag = {\n tag: 'script',\n attrs: {\n nonce: router.options.ssr?.nonce,\n className: '$tsr',\n id: TSR_SCRIPT_BARRIER_ID,\n },\n children: scripts,\n }\n return serverBufferedScript\n },\n liftScriptBarrier() {\n scriptBuffer.liftBarrier()\n },\n takeBufferedHtml() {\n if (!injectedHtmlBuffer) {\n return undefined\n }\n const buffered = injectedHtmlBuffer\n injectedHtmlBuffer = ''\n return buffered\n },\n cleanup() {\n // Guard against multiple cleanup calls\n if (!router.serverSsr) return\n renderFinishedListeners.length = 0\n serializationFinishedListeners.length = 0\n injectedHtmlBuffer = ''\n scriptBuffer.cleanup()\n router.serverSsr = undefined\n },\n }\n}\n\n/**\n * Get the origin for the request.\n *\n * SECURITY: We intentionally do NOT trust the Origin header for determining\n * the router's origin. The Origin header can be spoofed by attackers, which\n * could lead to SSRF-like vulnerabilities where redirects are constructed\n * using a malicious origin (CVE-2024-34351).\n *\n * Instead, we derive the origin from request.url, which is typically set by\n * the server infrastructure (not client-controlled headers).\n *\n * For applications behind proxies that need to trust forwarded headers,\n * use the router's `origin` option to explicitly configure a trusted origin.\n */\nexport function getOrigin(request: Request) {\n try {\n return new URL(request.url).origin\n } catch {}\n return 'http://localhost'\n}\n\n// server and browser can decode/encode characters differently in paths and search params.\n// Server generally strictly follows the WHATWG URL Standard, while browsers may differ for legacy reasons.\n// for example, in paths \"|\" is not encoded on the server but is encoded on chromium (and not on firefox) while \"대\" is encoded on both sides.\n// Another anomaly is that in Node new URLSearchParams and new URL also decode/encode characters differently.\n// new URLSearchParams() encodes \"|\" while new URL() does not, and in this instance\n// chromium treats search params differently than paths, i.e. \"|\" is not encoded in search params.\nexport function getNormalizedURL(url: string | URL, base?: string | URL) {\n // ensure backslashes are encoded correctly in the URL\n if (typeof url === 'string') url = url.replace('\\\\', '%5C')\n\n const rawUrl = new URL(url, base)\n const { path: decodedPathname, handledProtocolRelativeURL } = decodePath(\n rawUrl.pathname,\n )\n const searchParams = new URLSearchParams(rawUrl.search)\n const normalizedHref =\n decodedPathname +\n (searchParams.size > 0 ? '?' : '') +\n searchParams.toString() +\n rawUrl.hash\n\n return {\n url: new URL(normalizedHref, rawUrl.origin),\n handledProtocolRelativeURL,\n }\n}\n"],"names":[],"mappings":";;;;;;;;;AA+BA,MAAM,WAAW;AAEjB,MAAM,aAAa,aAAa;AAChC,MAAM,WAAW,aAAa;AAC9B,MAAM,WAAW;AAEV,SAAS,eAAe,OAAuC;AACpE,QAAM,kBAAmC;AAAA,IACvC,GAAG,oBAAoB,MAAM,EAAE;AAAA,IAC/B,GAAG,MAAM;AAAA,IACT,GAAG,MAAM;AAAA,EAAA;AAGX,QAAM,aAAa;AAAA,IACjB,CAAC,uBAAuB,GAAG;AAAA,IAC3B,CAAC,cAAc,GAAG;AAAA,IAClB,CAAC,SAAS,GAAG;AAAA,IACb,CAAC,OAAO,KAAK;AAAA,EAAA;AAGf,aAAW,CAAC,KAAK,SAAS,KAAK,YAAY;AACzC,QAAI,MAAM,GAAG,MAAM,QAAW;AAC5B,sBAAgB,SAAS,IAAI,MAAM,GAAG;AAAA,IACxC;AAAA,EACF;AACA,SAAO;AACT;AAEA,MAAM,kBAAkB;AAAA,EACtB,wBAAwB,QAAQ;AAAA,EAChC;AACF;AAEA,MAAM,aAAa;AAAA,EAOjB,YAAY,QAAmB;AAJ/B,SAAQ,uBAAuB;AAC/B,SAAQ,aAAa;AACrB,SAAQ,oBAAoB;AAG1B,SAAK,SAAS;AAEd,SAAK,SAAS,gBAAgB,MAAA;AAAA,EAChC;AAAA,EAEA,QAAQ,QAAgB;AACtB,QAAI,KAAK,WAAY;AACrB,SAAK,OAAO,KAAK,MAAM;AAEvB,QAAI,KAAK,wBAAwB,CAAC,KAAK,mBAAmB;AACxD,WAAK,oBAAoB;AACzB,qBAAe,MAAM;AACnB,aAAK,oBAAoB;AACzB,aAAK,sBAAA;AAAA,MACP,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEA,cAAc;AACZ,QAAI,KAAK,wBAAwB,KAAK,WAAY;AAClD,SAAK,uBAAuB;AA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AC,OAAO,UAAW;AACvB,8BAAwB,SAAS;AACjC,qCAA+B,SAAS;AACxC,2BAAqB;AACrB,mBAAa,QAAA;AACb,aAAO,YAAY;AAAA,IACrB;AAAA,EAAA;AAEJ;AAgBO,SAAS,UAAU,SAAkB;AAC1C,MAAI;AACF,WAAO,IAAI,IAAI,QAAQ,GAAG,EAAE;AAAA,EAC9B,QAAQ;AAAA,EAAC;AACT,SAAO;AACT;AAQO,SAAS,iBAAiB,KAAmB,MAAqB;AAEvE,MAAI,OAAO,QAAQ,gBAAgB,IAAI,QAAQ,MAAM,KAAK;AAE1D,QAAM,SAAS,IAAI,IAAI,KAAK,IAAI;AAChC,QAAM,EAAE,MAAM,iBAAiB,2BAAA,IAA+B;AAAA,IAC5D,OAAO;AAAA,EAAA;AAET,QAAM,eAAe,IAAI,gBAAgB,OAAO,MAAM;AACtD,QAAM,iBACJ,mBACC,aAAa,OAAO,IAAI,MAAM,MAC/B,aAAa,SAAA,IACb,OAAO;AAET,SAAO;AAAA,IACL,KAAK,IAAI,IAAI,gBAAgB,OAAO,MAAM;AAAA,IAC1C;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"ssr-server.js","sources":["../../../src/ssr/ssr-server.ts"],"sourcesContent":["import { crossSerializeStream, getCrossReferenceHeader } from 'seroval'\nimport invariant from 'tiny-invariant'\nimport { decodePath } from '../utils'\nimport { createLRUCache } from '../lru-cache'\nimport minifiedTsrBootStrapScript from './tsrScript?script-string'\nimport { GLOBAL_TSR, TSR_SCRIPT_BARRIER_ID } from './constants'\nimport { dehydrateSsrMatchId } from './ssr-match-id'\nimport { defaultSerovalPlugins } from './serializer/seroval-plugins'\nimport { makeSsrSerovalPlugin } from './serializer/transformer'\nimport type { LRUCache } from '../lru-cache'\nimport type { DehydratedMatch, DehydratedRouter } from './types'\nimport type { AnySerializationAdapter } from './serializer/transformer'\nimport type { AnyRouter } from '../router'\nimport type { AnyRouteMatch } from '../Matches'\nimport type { Manifest, RouterManagedTag } from '../manifest'\n\ndeclare module '../router' {\n interface ServerSsr {\n setRenderFinished: () => void\n cleanup: () => void\n }\n interface RouterEvents {\n onInjectedHtml: {\n type: 'onInjectedHtml'\n }\n onSerializationFinished: {\n type: 'onSerializationFinished'\n }\n }\n}\n\nconst SCOPE_ID = 'tsr'\n\nconst TSR_PREFIX = GLOBAL_TSR + '.router='\nconst P_PREFIX = GLOBAL_TSR + '.p(()=>'\nconst P_SUFFIX = ')'\n\nexport function dehydrateMatch(match: AnyRouteMatch): DehydratedMatch {\n const dehydratedMatch: DehydratedMatch = {\n i: dehydrateSsrMatchId(match.id),\n u: match.updatedAt,\n s: match.status,\n }\n\n const properties = [\n ['__beforeLoadContext', 'b'],\n ['loaderData', 'l'],\n ['error', 'e'],\n ['ssr', 'ssr'],\n ] as const\n\n for (const [key, shorthand] of properties) {\n if (match[key] !== undefined) {\n dehydratedMatch[shorthand] = match[key]\n }\n }\n if (match.globalNotFound) {\n dehydratedMatch.g = true\n }\n return dehydratedMatch\n}\n\nconst INITIAL_SCRIPTS = [\n getCrossReferenceHeader(SCOPE_ID),\n minifiedTsrBootStrapScript,\n]\n\nclass ScriptBuffer {\n private router: AnyRouter | undefined\n private _queue: Array<string>\n private _scriptBarrierLifted = false\n private _cleanedUp = false\n private _pendingMicrotask = false\n\n constructor(router: AnyRouter) {\n this.router = router\n // Copy INITIAL_SCRIPTS to avoid mutating the shared array\n this._queue = INITIAL_SCRIPTS.slice()\n }\n\n enqueue(script: string) {\n if (this._cleanedUp) return\n this._queue.push(script)\n // If barrier is lifted, schedule injection (if not already scheduled)\n if (this._scriptBarrierLifted && !this._pendingMicrotask) {\n this._pendingMicrotask = true\n queueMicrotask(() => {\n this._pendingMicrotask = false\n this.injectBufferedScripts()\n })\n }\n }\n\n liftBarrier() {\n if (this._scriptBarrierLifted || this._cleanedUp) return\n this._scriptBarrierLifted = true\n if (this._queue.length > 0 && !this._pendingMicrotask) {\n this._pendingMicrotask = true\n queueMicrotask(() => {\n this._pendingMicrotask = false\n this.injectBufferedScripts()\n })\n }\n }\n\n /**\n * Flushes any pending scripts synchronously.\n * Call this before emitting onSerializationFinished to ensure all scripts are injected.\n *\n * IMPORTANT: Only injects if the barrier has been lifted. Before the barrier is lifted,\n * scripts should remain in the queue so takeBufferedScripts() can retrieve them\n */\n flush() {\n if (!this._scriptBarrierLifted) return\n if (this._cleanedUp) return\n this._pendingMicrotask = false\n const scriptsToInject = this.takeAll()\n if (scriptsToInject && this.router?.serverSsr) {\n this.router.serverSsr.injectScript(scriptsToInject)\n }\n }\n\n takeAll() {\n const bufferedScripts = this._queue\n this._queue = []\n if (bufferedScripts.length === 0) {\n return undefined\n }\n // Optimization: if only one script, avoid join\n if (bufferedScripts.length === 1) {\n return bufferedScripts[0] + ';document.currentScript.remove()'\n }\n // Append cleanup script and join - avoid push() to not mutate then iterate\n return bufferedScripts.join(';') + ';document.currentScript.remove()'\n }\n\n injectBufferedScripts() {\n if (this._cleanedUp) return\n // Early return if queue is empty (avoids unnecessary takeAll() call)\n if (this._queue.length === 0) return\n const scriptsToInject = this.takeAll()\n if (scriptsToInject && this.router?.serverSsr) {\n this.router.serverSsr.injectScript(scriptsToInject)\n }\n }\n\n cleanup() {\n this._cleanedUp = true\n this._queue = []\n this.router = undefined\n }\n}\n\nconst isProd = process.env.NODE_ENV === 'production'\n\ntype FilteredRoutes = Manifest['routes']\n\ntype ManifestLRU = LRUCache<string, FilteredRoutes>\n\nconst MANIFEST_CACHE_SIZE = 100\nconst manifestCaches = new WeakMap<Manifest, ManifestLRU>()\n\nfunction getManifestCache(manifest: Manifest): ManifestLRU {\n const cache = manifestCaches.get(manifest)\n if (cache) return cache\n const newCache = createLRUCache<string, FilteredRoutes>(MANIFEST_CACHE_SIZE)\n manifestCaches.set(manifest, newCache)\n return newCache\n}\n\nexport function attachRouterServerSsrUtils({\n router,\n manifest,\n}: {\n router: AnyRouter\n manifest: Manifest | undefined\n}) {\n router.ssr = {\n manifest,\n }\n let _dehydrated = false\n let _serializationFinished = false\n const renderFinishedListeners: Array<() => void> = []\n const serializationFinishedListeners: Array<() => void> = []\n const scriptBuffer = new ScriptBuffer(router)\n let injectedHtmlBuffer = ''\n\n router.serverSsr = {\n injectHtml: (html: string) => {\n if (!html) return\n // Buffer the HTML so it can be retrieved via takeBufferedHtml()\n injectedHtmlBuffer += html\n // Emit event to notify subscribers that new HTML is available\n router.emit({\n type: 'onInjectedHtml',\n })\n },\n injectScript: (script: string) => {\n if (!script) return\n const html = `<script${router.options.ssr?.nonce ? ` nonce='${router.options.ssr.nonce}'` : ''}>${script}</script>`\n router.serverSsr!.injectHtml(html)\n },\n dehydrate: async () => {\n invariant(!_dehydrated, 'router is already dehydrated!')\n let matchesToDehydrate = router.state.matches\n if (router.isShell()) {\n // In SPA mode we only want to dehydrate the root match\n matchesToDehydrate = matchesToDehydrate.slice(0, 1)\n }\n const matches = matchesToDehydrate.map(dehydrateMatch)\n\n let manifestToDehydrate: Manifest | undefined = undefined\n // For currently matched routes, send full manifest (preloads + assets)\n // For all other routes, only send assets (no preloads as they are handled via dynamic imports)\n if (manifest) {\n // Prod-only caching; in dev manifests may be replaced/updated (HMR)\n const currentRouteIdsList = matchesToDehydrate.map((m) => m.routeId)\n const manifestCacheKey = currentRouteIdsList.join('\\0')\n\n let filteredRoutes: FilteredRoutes | undefined\n\n if (isProd) {\n filteredRoutes = getManifestCache(manifest).get(manifestCacheKey)\n }\n\n if (!filteredRoutes) {\n const currentRouteIds = new Set(currentRouteIdsList)\n const nextFilteredRoutes: FilteredRoutes = {}\n\n for (const routeId in manifest.routes) {\n const routeManifest = manifest.routes[routeId]!\n if (currentRouteIds.has(routeId)) {\n nextFilteredRoutes[routeId] = routeManifest\n } else if (\n routeManifest.assets &&\n routeManifest.assets.length > 0\n ) {\n nextFilteredRoutes[routeId] = {\n assets: routeManifest.assets,\n }\n }\n }\n\n if (isProd) {\n getManifestCache(manifest).set(manifestCacheKey, nextFilteredRoutes)\n }\n\n filteredRoutes = nextFilteredRoutes\n }\n\n manifestToDehydrate = {\n routes: filteredRoutes,\n }\n }\n const dehydratedRouter: DehydratedRouter = {\n manifest: manifestToDehydrate,\n matches,\n }\n const lastMatchId = matchesToDehydrate[matchesToDehydrate.length - 1]?.id\n if (lastMatchId) {\n dehydratedRouter.lastMatchId = dehydrateSsrMatchId(lastMatchId)\n }\n const dehydratedData = await router.options.dehydrate?.()\n if (dehydratedData) {\n dehydratedRouter.dehydratedData = dehydratedData\n }\n _dehydrated = true\n\n const trackPlugins = { didRun: false }\n const serializationAdapters = router.options.serializationAdapters as\n | Array<AnySerializationAdapter>\n | undefined\n const plugins = serializationAdapters\n ? serializationAdapters\n .map((t) => makeSsrSerovalPlugin(t, trackPlugins))\n .concat(defaultSerovalPlugins)\n : defaultSerovalPlugins\n\n const signalSerializationComplete = () => {\n _serializationFinished = true\n try {\n serializationFinishedListeners.forEach((l) => l())\n router.emit({ type: 'onSerializationFinished' })\n } catch (err) {\n console.error('Serialization listener error:', err)\n } finally {\n serializationFinishedListeners.length = 0\n renderFinishedListeners.length = 0\n }\n }\n\n crossSerializeStream(dehydratedRouter, {\n refs: new Map(),\n plugins,\n onSerialize: (data, initial) => {\n let serialized = initial ? TSR_PREFIX + data : data\n if (trackPlugins.didRun) {\n serialized = P_PREFIX + serialized + P_SUFFIX\n }\n scriptBuffer.enqueue(serialized)\n },\n scopeId: SCOPE_ID,\n onDone: () => {\n scriptBuffer.enqueue(GLOBAL_TSR + '.e()')\n // Flush all pending scripts synchronously before signaling completion\n // This ensures all scripts are injected before onSerializationFinished is emitted\n scriptBuffer.flush()\n signalSerializationComplete()\n },\n onError: (err) => {\n console.error('Serialization error:', err)\n signalSerializationComplete()\n },\n })\n },\n isDehydrated() {\n return _dehydrated\n },\n isSerializationFinished() {\n return _serializationFinished\n },\n onRenderFinished: (listener) => renderFinishedListeners.push(listener),\n onSerializationFinished: (listener) =>\n serializationFinishedListeners.push(listener),\n setRenderFinished: () => {\n // Wrap in try-catch to ensure scriptBuffer.liftBarrier() is always called\n try {\n renderFinishedListeners.forEach((l) => l())\n } catch (err) {\n console.error('Error in render finished listener:', err)\n } finally {\n // Clear listeners after calling them to prevent memory leaks\n renderFinishedListeners.length = 0\n }\n scriptBuffer.liftBarrier()\n },\n takeBufferedScripts() {\n const scripts = scriptBuffer.takeAll()\n const serverBufferedScript: RouterManagedTag = {\n tag: 'script',\n attrs: {\n nonce: router.options.ssr?.nonce,\n className: '$tsr',\n id: TSR_SCRIPT_BARRIER_ID,\n },\n children: scripts,\n }\n return serverBufferedScript\n },\n liftScriptBarrier() {\n scriptBuffer.liftBarrier()\n },\n takeBufferedHtml() {\n if (!injectedHtmlBuffer) {\n return undefined\n }\n const buffered = injectedHtmlBuffer\n injectedHtmlBuffer = ''\n return buffered\n },\n cleanup() {\n // Guard against multiple cleanup calls\n if (!router.serverSsr) return\n renderFinishedListeners.length = 0\n serializationFinishedListeners.length = 0\n injectedHtmlBuffer = ''\n scriptBuffer.cleanup()\n router.serverSsr = undefined\n },\n }\n}\n\n/**\n * Get the origin for the request.\n *\n * SECURITY: We intentionally do NOT trust the Origin header for determining\n * the router's origin. The Origin header can be spoofed by attackers, which\n * could lead to SSRF-like vulnerabilities where redirects are constructed\n * using a malicious origin (CVE-2024-34351).\n *\n * Instead, we derive the origin from request.url, which is typically set by\n * the server infrastructure (not client-controlled headers).\n *\n * For applications behind proxies that need to trust forwarded headers,\n * use the router's `origin` option to explicitly configure a trusted origin.\n */\nexport function getOrigin(request: Request) {\n try {\n return new URL(request.url).origin\n } catch {}\n return 'http://localhost'\n}\n\n// server and browser can decode/encode characters differently in paths and search params.\n// Server generally strictly follows the WHATWG URL Standard, while browsers may differ for legacy reasons.\n// for example, in paths \"|\" is not encoded on the server but is encoded on chromium (and not on firefox) while \"대\" is encoded on both sides.\n// Another anomaly is that in Node new URLSearchParams and new URL also decode/encode characters differently.\n// new URLSearchParams() encodes \"|\" while new URL() does not, and in this instance\n// chromium treats search params differently than paths, i.e. \"|\" is not encoded in search params.\nexport function getNormalizedURL(url: string | URL, base?: string | URL) {\n // ensure backslashes are encoded correctly in the URL\n if (typeof url === 'string') url = url.replace('\\\\', '%5C')\n\n const rawUrl = new URL(url, base)\n const { path: decodedPathname, handledProtocolRelativeURL } = decodePath(\n rawUrl.pathname,\n )\n const searchParams = new URLSearchParams(rawUrl.search)\n const normalizedHref =\n decodedPathname +\n (searchParams.size > 0 ? '?' : '') +\n searchParams.toString() +\n rawUrl.hash\n\n return {\n url: new URL(normalizedHref, rawUrl.origin),\n handledProtocolRelativeURL,\n }\n}\n"],"names":[],"mappings":";;;;;;;;;AA+BA,MAAM,WAAW;AAEjB,MAAM,aAAa,aAAa;AAChC,MAAM,WAAW,aAAa;AAC9B,MAAM,WAAW;AAEV,SAAS,eAAe,OAAuC;AACpE,QAAM,kBAAmC;AAAA,IACvC,GAAG,oBAAoB,MAAM,EAAE;AAAA,IAC/B,GAAG,MAAM;AAAA,IACT,GAAG,MAAM;AAAA,EAAA;AAGX,QAAM,aAAa;AAAA,IACjB,CAAC,uBAAuB,GAAG;AAAA,IAC3B,CAAC,cAAc,GAAG;AAAA,IAClB,CAAC,SAAS,GAAG;AAAA,IACb,CAAC,OAAO,KAAK;AAAA,EAAA;AAGf,aAAW,CAAC,KAAK,SAAS,KAAK,YAAY;AACzC,QAAI,MAAM,GAAG,MAAM,QAAW;AAC5B,sBAAgB,SAAS,IAAI,MAAM,GAAG;AAAA,IACxC;AAAA,EACF;AACA,MAAI,MAAM,gBAAgB;AACxB,oBAAgB,IAAI;AAAA,EACtB;AACA,SAAO;AACT;AAEA,MAAM,kBAAkB;AAAA,EACtB,wBAAwB,QAAQ;AAAA,EAChC;AACF;AAEA,MAAM,aAAa;AAAA,EAOjB,YAAY,QAAmB;AAJ/B,SAAQ,uBAAuB;AAC/B,SAAQ,aAAa;AACrB,SAAQ,oBAAoB;AAG1B,SAAK,SAAS;AAEd,SAAK,SAAS,gBAAgB,MAAA;AAAA,EAChC;AAAA,EAEA,QAAQ,QAAgB;A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UAC3B,WAAW;AAAA,UACX,IAAI;AAAA,QAAA;AAAA,QAEN,UAAU;AAAA,MAAA;AAEZ,aAAO;AAAA,IACT;AAAA,IACA,oBAAoB;AAClB,mBAAa,YAAA;AAAA,IACf;AAAA,IACA,mBAAmB;AACjB,UAAI,CAAC,oBAAoB;AACvB,eAAO;AAAA,MACT;AACA,YAAM,WAAW;AACjB,2BAAqB;AACrB,aAAO;AAAA,IACT;AAAA,IACA,UAAU;AAER,UAAI,CAAC,OAAO,UAAW;AACvB,8BAAwB,SAAS;AACjC,qCAA+B,SAAS;AACxC,2BAAqB;AACrB,mBAAa,QAAA;AACb,aAAO,YAAY;AAAA,IACrB;AAAA,EAAA;AAEJ;AAgBO,SAAS,UAAU,SAAkB;AAC1C,MAAI;AACF,WAAO,IAAI,IAAI,QAAQ,GAAG,EAAE;AAAA,EAC9B,QAAQ;AAAA,EAAC;AACT,SAAO;AACT;AAQO,SAAS,iBAAiB,KAAmB,MAAqB;AAEvE,MAAI,OAAO,QAAQ,gBAAgB,IAAI,QAAQ,MAAM,KAAK;AAE1D,QAAM,SAAS,IAAI,IAAI,KAAK,IAAI;AAChC,QAAM,EAAE,MAAM,iBAAiB,2BAAA,IAA+B;AAAA,IAC5D,OAAO;AAAA,EAAA;AAET,QAAM,eAAe,IAAI,gBAAgB,OAAO,MAAM;AACtD,QAAM,iBACJ,mBACC,aAAa,OAAO,IAAI,MAAM,MAC/B,aAAa,SAAA,IACb,OAAO;AAET,SAAO;AAAA,IACL,KAAK,IAAI,IAAI,gBAAgB,OAAO,MAAM;AAAA,IAC1C;AAAA,EAAA;AAEJ;"}
@@ -8,6 +8,7 @@ export interface DehydratedMatch {
8
8
  u: MakeRouteMatch['updatedAt'];
9
9
  s: MakeRouteMatch['status'];
10
10
  ssr?: MakeRouteMatch['ssr'];
11
+ g?: true;
11
12
  }
12
13
  export interface DehydratedRouter {
13
14
  manifest: Manifest | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/router-core",
3
- "version": "1.163.3",
3
+ "version": "1.166.2",
4
4
  "description": "Modern and scalable routing for React applications",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",