Server: Phase 2 (REVIEW not respected yet)

This commit is contained in:
Thomas Karner committed 2026-09-21 11:24:43 +02:00
1 parent 5d16ded553
commit 142b47674d
4271 files changed
+1203269

No files matched your search

+276
View File
@@ -0,0 +1,276 @@
import type { AnyRoute, StaticDataRouteOption } from './route'
import type {
AllContext,
AllLoaderData,
AllParams,
FullSearchSchema,
ParseRoute,
RouteById,
RouteIds,
} from './routeInfo'
import type { AnyRouter, RegisteredRouter, SSROption } from './router'
import type { Constrain } from './utils'
export type AnyMatchAndValue = { match: any; value: any }
export type FindValueByIndex<
TKey,
TValue extends ReadonlyArray<any>,
> = TKey extends `${infer TIndex extends number}` ? TValue[TIndex] : never
export type FindValueByKey<TKey, TValue> =
TValue extends ReadonlyArray<any>
? FindValueByIndex<TKey, TValue>
: TValue[TKey & keyof TValue]
export type CreateMatchAndValue<TMatch, TValue> = TValue extends any
? {
match: TMatch
value: TValue
}
: never
export type NextMatchAndValue<
TKey,
TMatchAndValue extends AnyMatchAndValue,
> = TMatchAndValue extends any
? CreateMatchAndValue<
TMatchAndValue['match'],
FindValueByKey<TKey, TMatchAndValue['value']>
>
: never
export type IsMatchKeyOf<TValue> =
TValue extends ReadonlyArray<any>
? number extends TValue['length']
? `${number}`
: keyof TValue & `${number}`
: TValue extends object
? keyof TValue & string
: never
export type IsMatchPath<
TParentPath extends string,
TMatchAndValue extends AnyMatchAndValue,
> = `${TParentPath}${IsMatchKeyOf<TMatchAndValue['value']>}`
export type IsMatchResult<
TKey,
TMatchAndValue extends AnyMatchAndValue,
> = TMatchAndValue extends any
? TKey extends keyof TMatchAndValue['value']
? TMatchAndValue['match']
: never
: never
export type IsMatchParse<
TPath,
TMatchAndValue extends AnyMatchAndValue,
TParentPath extends string = '',
> = TPath extends `${string}.${string}`
? TPath extends `${infer TFirst}.${infer TRest}`
? IsMatchParse<
TRest,
NextMatchAndValue<TFirst, TMatchAndValue>,
`${TParentPath}${TFirst}.`
>
: never
: {
path: IsMatchPath<TParentPath, TMatchAndValue>
result: IsMatchResult<TPath, TMatchAndValue>
}
export type IsMatch<TMatch, TPath> = IsMatchParse<
TPath,
TMatch extends any ? { match: TMatch; value: TMatch } : never
>
/**
* Narrows matches based on a path
* @experimental
*/
export const isMatch = <TMatch, TPath extends string>(
match: TMatch,
path: Constrain<TPath, IsMatch<TMatch, TPath>['path']>,
): match is IsMatch<TMatch, TPath>['result'] => {
const parts = (path as string).split('.')
let part
let i = 0
let value: any = match
while ((part = parts[i++]) != null && value != null) {
value = value[part]
}
return value != null
}
export interface DefaultRouteMatchExtensions {
scripts?: unknown
links?: unknown
headScripts?: unknown
meta?: unknown
styles?: unknown
}
export interface RouteMatchExtensions extends DefaultRouteMatchExtensions {}
export interface RouteMatch<
out TRouteId,
out TFullPath,
out TAllParams,
out TFullSearchSchema,
out TLoaderData,
out TAllContext,
out TLoaderDeps,
> extends RouteMatchExtensions {
id: string
routeId: TRouteId
fullPath: TFullPath
index: number
pathname: string
params: TAllParams
_strictParams: TAllParams
status: 'pending' | 'success' | 'error' | 'notFound'
isFetching: false | 'beforeLoad' | 'loader'
error: unknown
paramsError: unknown
searchError: unknown
updatedAt: number
loaderData?: TLoaderData
/** @internal Exclusive end of the SSR-verified asset prefix. */
_assetEnd?: number
/** @internal */
_ctx?: Record<string, unknown>
/** @internal */
__beforeLoadContext?: Record<string, unknown>
context: TAllContext
search: TFullSearchSchema
_strictSearch: TFullSearchSchema
abortController: AbortController
cause: 'preload' | 'enter' | 'stay'
loaderDeps: TLoaderDeps
preload: boolean
invalid: boolean
headers?: Record<string, string>
_notFound?: boolean
staticData: StaticDataRouteOption
/** This attribute is not reactive */
ssr?: SSROption
}
export interface PreValidationErrorHandlingRouteMatch<
TRouteId,
TFullPath,
TAllParams,
TFullSearchSchema,
> {
id: string
routeId: TRouteId
fullPath: TFullPath
index: number
pathname: string
search:
| { status: 'success'; value: TFullSearchSchema }
| { status: 'error'; error: unknown }
params:
| { status: 'success'; value: TAllParams }
| { status: 'error'; error: unknown }
staticData: StaticDataRouteOption
ssr?: boolean | 'data-only'
}
export type MakePreValidationErrorHandlingRouteMatchUnion<
TRouter extends AnyRouter = RegisteredRouter,
TRoute extends AnyRoute = ParseRoute<TRouter['routeTree']>,
> = TRoute extends any
? PreValidationErrorHandlingRouteMatch<
TRoute['id'],
TRoute['fullPath'],
TRoute['types']['allParams'],
TRoute['types']['fullSearchSchema']
>
: never
export type MakeRouteMatchFromRoute<TRoute extends AnyRoute> = RouteMatch<
TRoute['types']['id'],
TRoute['types']['fullPath'],
TRoute['types']['allParams'],
TRoute['types']['fullSearchSchema'],
TRoute['types']['loaderData'],
TRoute['types']['allContext'],
TRoute['types']['loaderDeps']
>
export type MakeRouteMatch<
TRouteTree extends AnyRoute = RegisteredRouter['routeTree'],
TRouteId = RouteIds<TRouteTree>,
TStrict extends boolean = true,
> = RouteMatch<
TRouteId,
RouteById<TRouteTree, TRouteId>['types']['fullPath'],
TStrict extends false
? AllParams<TRouteTree>
: RouteById<TRouteTree, TRouteId>['types']['allParams'],
TStrict extends false
? FullSearchSchema<TRouteTree>
: RouteById<TRouteTree, TRouteId>['types']['fullSearchSchema'],
TStrict extends false
? AllLoaderData<TRouteTree>
: RouteById<TRouteTree, TRouteId>['types']['loaderData'],
TStrict extends false
? AllContext<TRouteTree>
: RouteById<TRouteTree, TRouteId>['types']['allContext'],
RouteById<TRouteTree, TRouteId>['types']['loaderDeps']
>
export type AnyRouteMatch = RouteMatch<any, any, any, any, any, any, any>
export type MakeRouteMatchUnion<
TRouter extends AnyRouter = RegisteredRouter,
TRoute extends AnyRoute = ParseRoute<TRouter['routeTree']>,
> = TRoute extends any
? RouteMatch<
TRoute['id'],
TRoute['fullPath'],
TRoute['types']['allParams'],
TRoute['types']['fullSearchSchema'],
TRoute['types']['loaderData'],
TRoute['types']['allContext'],
TRoute['types']['loaderDeps']
>
: never
/**
* The `MatchRouteOptions` type is used to describe the options that can be used when matching a route.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/MatchRouteOptionsType#matchrouteoptions-type)
*/
export interface MatchRouteOptions {
/**
* If `true`, will match against pending location instead of the current location.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/MatchRouteOptionsType#pending-property)
*/
pending?: boolean
/**
* If `true`, will match against the current location with case sensitivity.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/MatchRouteOptionsType#casesensitive-property)
*
* @deprecated Declare case sensitivity in the route definition instead, or globally for all routes using the `caseSensitive` option on the router.
*/
caseSensitive?: boolean
/**
* If `true`, will match against the current location's search params using a deep inclusive check. e.g. `{ a: 1 }` will match for a current location of `{ a: 1, b: 2 }`.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/MatchRouteOptionsType#includesearch-property)
*/
includeSearch?: boolean
/**
* If `true`, will match against the current location using a fuzzy match. e.g. `/posts` will match for a current location of `/posts/123`.
*
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/MatchRouteOptionsType#fuzzy-property)
*/
fuzzy?: boolean
}
+47
View File
@@ -0,0 +1,47 @@
import type { NavigateOptions, ToOptions } from './link'
import type { ParsedLocation } from './location'
import type { RoutePaths } from './routeInfo'
import type { RegisteredRouter, ViewTransitionOptions } from './router'
export interface MatchLocation {
to?: string | number | null
fuzzy?: boolean
caseSensitive?: boolean
from?: string
}
export interface CommitLocationOptions {
replace?: boolean
resetScroll?: boolean
hashScrollIntoView?: boolean | ScrollIntoViewOptions
viewTransition?: boolean | ViewTransitionOptions
/**
* @deprecated All navigations use transitions under the hood now
**/
startTransition?: boolean
ignoreBlocker?: boolean
}
export type NavigateFn = <
TRouter extends RegisteredRouter,
TTo extends string | undefined,
TFrom extends RoutePaths<TRouter['routeTree']> | string = string,
TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,
TMaskTo extends string = '',
>(
opts: NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
) => Promise<void>
export type BuildLocationFn = <
TRouter extends RegisteredRouter,
TTo extends string | undefined,
TFrom extends RoutePaths<TRouter['routeTree']> | string = string,
TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,
TMaskTo extends string = '',
>(
opts: ToOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {
leaveParams?: boolean
_includeValidateSearch?: boolean
_isNavigate?: boolean
},
) => ParsedLocation
+61
View File
@@ -0,0 +1,61 @@
function observeLate<T>(
callback: ((value: T) => unknown) | undefined,
value: T,
) {
if (!callback) {
return
}
try {
const result = callback(value)
if (result !== undefined) {
void Promise.resolve(result).catch(() => {})
}
} catch {}
}
/**
* Await `value` unless `signal` aborts first. A result that settles after the
* abort is passed to `onLate` / `onLateError` instead.
*
* One abort listener per wait: SSR requests nest at most a few waits on one
* signal, so pooling them was measurably slower than this.
*/
export function waitForReason<T>(
value: T | PromiseLike<T>,
signal: AbortSignal,
onLate?: (value: T) => unknown,
onLateError?: (reason: unknown) => unknown,
): Promise<T> {
const promise = Promise.resolve(value)
if (signal.aborted) {
void promise.then(
(result) => observeLate(onLate, result),
(error) => observeLate(onLateError, error),
)
return Promise.reject(signal.reason)
}
return new Promise<T>((resolve, reject) => {
const abort = () => reject(signal.reason)
signal.addEventListener('abort', abort, { once: true })
void promise.then(
(result) => {
signal.removeEventListener('abort', abort)
if (signal.aborted) {
observeLate(onLate, result)
} else {
resolve(result)
}
},
(error) => {
signal.removeEventListener('abort', abort)
if (signal.aborted) {
observeLate(onLateError, error)
} else {
reject(error)
}
},
)
})
}
+42
View File
@@ -0,0 +1,42 @@
import type { SSROption } from './router'
import type { AnySerializationAdapter } from './ssr/serializer/transformer'
export interface RouterConfigOptions<
in out TSerializationAdapters,
in out TDefaultSsr,
> {
serializationAdapters?: TSerializationAdapters
defaultSsr?: TDefaultSsr
}
export interface RouterConfig<
in out TSerializationAdapters,
in out TDefaultSsr,
> {
'~types': RouterConfigTypes<TSerializationAdapters, TDefaultSsr>
serializationAdapters: TSerializationAdapters
defaultSsr: TDefaultSsr | undefined
}
export interface RouterConfigTypes<
in out TSerializationAdapters,
in out TDefaultSsr,
> {
serializationAdapters: TSerializationAdapters
defaultSsr: TDefaultSsr
}
export const createRouterConfig = <
const TSerializationAdapters extends ReadonlyArray<AnySerializationAdapter> =
[],
TDefaultSsr extends SSROption = SSROption,
>(
options: RouterConfigOptions<TSerializationAdapters, TDefaultSsr>,
): RouterConfig<TSerializationAdapters, TDefaultSsr> => {
return {
serializationAdapters: options.serializationAdapters,
defaultSsr: options.defaultSsr,
} as RouterConfig<TSerializationAdapters, TDefaultSsr>
}
export type AnyRouterConfig = RouterConfig<any, any>
+69
View File
@@ -0,0 +1,69 @@
import { defaultSerializeError } from './router'
/**
* Well-known symbol used by {@link defer} to tag a promise with
* its deferred state. Consumers can read `promise[TSR_DEFERRED_PROMISE]`
* to access `status`, `data`, or `error`.
*/
export const TSR_DEFERRED_PROMISE = Symbol.for('TSR_DEFERRED_PROMISE')
export type DeferredPromiseState<T> =
| {
status: 'pending'
data?: T
error?: unknown
}
| {
status: 'success'
data: T
}
| {
status: 'error'
data?: T
error: unknown
}
export type DeferredPromise<T> = Promise<T> & {
[TSR_DEFERRED_PROMISE]: DeferredPromiseState<T>
}
/**
* Wrap a promise with a deferred state for use with `<Await>` and `useAwaited`.
*
* The returned promise is augmented with internal state (status/data/error)
* so UI can read progress or suspend until it settles.
*
* @param _promise The promise to wrap.
* @param options Optional config. Provide `serializeError` to customize how
* errors are serialized for transfer.
* @returns The same promise with attached deferred metadata.
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/deferFunction
*/
export function defer<T>(
_promise: Promise<T>,
options?: {
serializeError?: typeof defaultSerializeError
},
) {
const promise = _promise as DeferredPromise<T>
// this is already deferred promise
if ((promise as any)[TSR_DEFERRED_PROMISE]) {
return promise
}
promise[TSR_DEFERRED_PROMISE] = { status: 'pending' }
promise
.then((data) => {
promise[TSR_DEFERRED_PROMISE].status = 'success'
promise[TSR_DEFERRED_PROMISE].data = data
})
.catch((error) => {
promise[TSR_DEFERRED_PROMISE].status = 'error'
;(promise[TSR_DEFERRED_PROMISE] as any).error = {
data: (options?.serializeError ?? defaultSerializeError)(error),
__isServerError: true,
}
})
return promise
}
+164
View File
@@ -0,0 +1,164 @@
import type { Register } from './router'
import type {
AnyContext,
AnyPathParams,
AnyRoute,
FileBaseRouteOptions,
ResolveParams,
Route,
RouteConstraints,
UpdatableRouteOptions,
} from './route'
import type { AnyValidator } from './validators'
export interface FileRouteTypes {
fileRoutesByFullPath: any
fullPaths: any
to: any
fileRoutesByTo: any
id: any
fileRoutesById: any
}
export type InferFileRouteTypes<TRouteTree extends AnyRoute> =
unknown extends TRouteTree['types']['fileRouteTypes']
? never
: TRouteTree['types']['fileRouteTypes'] extends FileRouteTypes
? TRouteTree['types']['fileRouteTypes']
: never
export interface FileRoutesByPath {
// '/': {
// parentRoute: typeof rootRoute
// }
}
export interface FileRouteOptions<
TRegister,
TFilePath extends string,
TParentRoute extends AnyRoute,
TId extends RouteConstraints['TId'],
TPath extends RouteConstraints['TPath'],
TFullPath extends RouteConstraints['TFullPath'],
TSearchValidator = undefined,
TParams = ResolveParams<TPath>,
TRouteContextFn = AnyContext,
TBeforeLoadFn = AnyContext,
TLoaderDeps extends Record<string, any> = {},
TLoaderFn = undefined,
TSSR = unknown,
TServerMiddlewares = unknown,
THandlers = undefined,
>
extends
FileBaseRouteOptions<
TRegister,
TParentRoute,
TId,
TPath,
TSearchValidator,
TParams,
TLoaderDeps,
TLoaderFn,
AnyContext,
TRouteContextFn,
TBeforeLoadFn,
AnyContext,
TSSR,
TServerMiddlewares,
THandlers
>,
UpdatableRouteOptions<
TParentRoute,
TId,
TFullPath,
TParams,
TSearchValidator,
TLoaderFn,
TLoaderDeps,
AnyContext,
TRouteContextFn,
TBeforeLoadFn
> {}
export type CreateFileRoute<
TFilePath extends string,
TParentRoute extends AnyRoute,
TId extends RouteConstraints['TId'],
TPath extends RouteConstraints['TPath'],
TFullPath extends RouteConstraints['TFullPath'],
> = <
TRegister = Register,
TSearchValidator = undefined,
TParams = ResolveParams<TPath>,
TRouteContextFn = AnyContext,
TBeforeLoadFn = AnyContext,
TLoaderDeps extends Record<string, any> = {},
TLoaderFn = undefined,
TSSR = unknown,
TServerMiddlewares = unknown,
THandlers = undefined,
>(
options?: FileRouteOptions<
TRegister,
TFilePath,
TParentRoute,
TId,
TPath,
TFullPath,
TSearchValidator,
TParams,
TRouteContextFn,
TBeforeLoadFn,
TLoaderDeps,
TLoaderFn,
TSSR,
TServerMiddlewares,
THandlers
>,
) => Route<
TRegister,
TParentRoute,
TPath,
TFullPath,
TFilePath,
TId,
TSearchValidator,
TParams,
AnyContext,
TRouteContextFn,
TBeforeLoadFn,
TLoaderDeps,
TLoaderFn,
unknown,
unknown,
TSSR,
TServerMiddlewares,
THandlers
>
export type LazyRouteOptions = Pick<
UpdatableRouteOptions<
AnyRoute,
string,
string,
AnyPathParams,
AnyValidator,
{},
AnyContext,
AnyContext,
AnyContext,
AnyContext
>,
'component' | 'errorComponent' | 'pendingComponent' | 'notFoundComponent'
>
export interface LazyRoute<in out TRoute extends AnyRoute> {
options: {
id: string
} & LazyRouteOptions
}
export type CreateLazyFileRoute<TRoute extends AnyRoute> = (
opts: LazyRouteOptions,
) => LazyRoute<TRoute>
+9
View File
@@ -0,0 +1,9 @@
import type { AnyRouter } from './router'
declare global {
interface Window {
__TSR_ROUTER__?: AnyRouter
}
}
export {}
+9
View File
@@ -0,0 +1,9 @@
import type { HistoryLocation } from '@tanstack/history'
declare module '@tanstack/history' {
interface HistoryState {
__tempLocation?: HistoryLocation
__tempKey?: string
__hashScrollIntoViewOptions?: boolean | ScrollIntoViewOptions
}
}
+487
View File
@@ -0,0 +1,487 @@
export * from './global'
export { TSR_DEFERRED_PROMISE, defer } from './defer'
export type { DeferredPromiseState, DeferredPromise } from './defer'
export { invariant } from './invariant'
export { preloadWarning } from './link'
export type {
IsRequiredParams,
AddTrailingSlash,
RemoveTrailingSlashes,
AddLeadingSlash,
RemoveLeadingSlashes,
ActiveOptions,
LinkOptionsProps,
ResolveCurrentPath,
ResolveParentPath,
ResolveRelativePath,
FindDescendantToPaths,
InferDescendantToPaths,
RelativeToPath,
RelativeToParentPath,
RelativeToCurrentPath,
AbsoluteToPath,
RelativeToPathAutoComplete,
NavigateOptions,
ToOptions,
ToMaskOptions,
ToSubOptions,
ResolveRoute,
SearchParamOptions,
PathParamOptions,
ToPathOption,
LinkOptions,
MakeOptionalPathParams,
FromPathOption,
MakeOptionalSearchParams,
MaskOptions,
ToSubOptionsProps,
RequiredToOptions,
} from './link'
export type {
RouteToPath,
TrailingSlashOptionByRouter,
ParseRoute,
CodeRouteToPath,
RouteIds,
FullSearchSchema,
FullSearchSchemaInput,
AllParams,
RouteById,
AllContext,
RoutePaths,
RoutesById,
RoutesByPath,
AllLoaderData,
RouteByPath,
} from './routeInfo'
export type {
InferFileRouteTypes,
FileRouteTypes,
FileRoutesByPath,
CreateFileRoute,
LazyRoute,
LazyRouteOptions,
CreateLazyFileRoute,
} from './fileRoute'
export type { ParsedLocation } from './location'
export type {
Manifest,
ServerManifest,
ManifestRoute,
ManifestRouteAssets,
ServerManifestRoute,
ManifestCssLink,
ManifestInlineCss,
ServerManifestInlineCss,
InlineCssTemplate,
ManifestScript,
RouterManagedTag,
RouterManagedTitleTag,
RouterManagedMetaTag,
RouterManagedInlineCssTag,
RouterManagedScriptTag,
RouterManagedLinkTag,
RouterManagedStyleTag,
AssetCrossOrigin,
AssetCrossOriginConfig,
ManifestAssetLink,
ScriptFormat,
} from './manifest'
export {
DEV_STYLES_ATTR,
appendUniqueUserTags,
createInlineCssStyleAsset,
getAssetCrossOrigin,
getManifestScriptFormat,
getScriptPreloadAttrs,
getStylesheetHref,
resolveManifestAssetLink,
resolveManifestCssLink,
} from './manifest'
export { isMatch } from './Matches'
export { _getAssetMatches, _getRenderedMatches } from './load-client'
export { composeSsrBodyScripts, getSsrBodyScriptParts } from './ssr/bodyScripts'
export type {
AnyMatchAndValue,
FindValueByIndex,
FindValueByKey,
CreateMatchAndValue,
NextMatchAndValue,
IsMatchKeyOf,
IsMatchPath,
IsMatchResult,
IsMatchParse,
IsMatch,
RouteMatch,
RouteMatchExtensions,
MakeRouteMatchUnion,
MakeRouteMatch,
AnyRouteMatch,
MakeRouteMatchFromRoute,
MatchRouteOptions,
} from './Matches'
export {
joinPaths,
cleanPath,
trimPathLeft,
trimPathRight,
trimPath,
removeTrailingSlash,
exactPathTest,
resolvePath,
interpolatePath,
getRouteSegments,
hasMissingPathParams,
} from './path'
export { encode, decode } from './qss'
export { rootRouteId } from './root'
export type { RootRouteId } from './root'
export { BaseRoute, BaseRouteApi, BaseRootRoute } from './route'
export type {
AnyPathParams,
SearchSchemaInput,
AnyContext,
RouteContext,
PreloadableObj,
RoutePathOptions,
StaticDataRouteOption,
RoutePathOptionsIntersection,
SearchFilter,
SearchMiddlewareContext,
SearchMiddleware,
ResolveId,
InferFullSearchSchema,
InferFullSearchSchemaInput,
InferAllParams,
InferAllContext,
MetaDescriptor,
RouteLinkEntry,
SearchValidator,
AnySearchValidator,
DefaultSearchValidator,
ErrorRouteProps,
ErrorComponentProps,
DefaultErrorBoundaryTypes,
ErrorBoundaryTypes,
NotFoundRouteProps,
ResolveParams,
ParseParamsFn,
StringifyParamsFn,
ParamsOptions,
UpdatableStaticRouteOption,
ContextReturnType,
ContextAsyncReturnType,
ResolveRouteContext,
ResolveLoaderData,
RoutePrefix,
TrimPath,
TrimPathLeft,
TrimPathRight,
ResolveSearchSchemaFnInput,
ResolveSearchSchemaInput,
ResolveSearchSchemaFn,
ResolveSearchSchema,
ResolveFullSearchSchema,
ResolveFullSearchSchemaInput,
ResolveAllContext,
BeforeLoadContextParameter,
RouteContextParameter,
ResolveAllParamsFromParent,
AnyRoute,
Route,
RouteTypes,
FullSearchSchemaOption,
RemountDepsOptions,
MakeRemountDepsOptionsUnion,
ResolveFullPath,
AnyRouteWithContext,
RouteOptions,
FileBaseRouteOptions,
BaseRouteOptions,
UpdatableRouteOptions,
LoaderStaleReloadMode,
RouteLoaderFn,
RouteLoaderEntry,
LoaderFnContext,
RouteContextFn,
ContextOptions,
RouteContextOptions,
SsrContextOptions,
BeforeLoadContextOptions,
RootRouteOptions,
RootRouteOptionsExtensions,
UpdatableRouteOptionsExtensions,
RouteConstraints,
RouteTypesById,
RouteMask,
RouteExtensions,
RouteLazyFn,
RouteAddChildrenFn,
RouteAddFileChildrenFn,
RouteAddFileTypesFn,
ResolveOptionalParams,
ResolveRequiredParams,
RootRoute,
FilebaseRouteOptionsInterface,
} from './route'
export {
createNonReactiveMutableStore,
createNonReactiveReadonlyStore,
} from './stores'
export type {
RouterBatchFn,
RouterReadableStore,
GetStoreConfig,
RouterStores,
RouterWritableStore,
} from './stores'
export {
defaultSerializeError,
getLocationChangeInfo,
RouterCore,
lazyFn,
SearchParamError,
PathParamError,
getInitialRouterState,
trailingSlashOptions,
} from './router'
export type {
ViewTransitionOptions,
TrailingSlashOption,
Register,
AnyRouter,
AnyRouterWithContext,
RegisteredRouter,
RouterState,
BuildNextOptions,
RouterListener,
RouterEvent,
ListenerFn,
RouterEvents,
MatchRoutesOpts,
RouterOptionsExtensions,
DefaultRemountDepsFn,
PreloadRouteFn,
MatchRouteFn,
RouterContextOptions,
RouterOptions,
RouterConstructorOptions,
UpdateFn,
ParseLocationFn,
InvalidateFn,
ControllablePromise,
EmitFn,
LoadFn,
SubscribeFn,
CommitLocationFn,
GetMatchRoutesFn,
MatchRoutesFn,
StartTransitionFn,
LoadRouteChunkFn,
ClearCacheFn,
CreateRouterFn,
SSROption,
} from './router'
export * from './config'
export type {
MatchLocation,
CommitLocationOptions,
NavigateFn,
BuildLocationFn,
} from './RouterProvider'
export { retainSearchParams, stripSearchParams } from './searchMiddleware'
export {
defaultParseSearch,
defaultStringifySearch,
parseSearchWith,
stringifySearchWith,
} from './searchParams'
export type { SearchSerializer, SearchParser } from './searchParams'
export type { OptionalStructuralSharing } from './structuralSharing'
export {
functionalUpdate,
hasKeys,
replaceEqualDeep,
deepEqual,
createControlledPromise,
isPromise,
isModuleNotFoundError,
DEFAULT_PROTOCOL_ALLOWLIST,
escapeHtml,
getUrlScheme,
isDangerousProtocol,
buildDevStylesUrl,
} from './utils'
export type {
NoInfer,
IsAny,
PickAsRequired,
PickRequired,
PickOptional,
WithoutEmpty,
Expand,
DeepPartial,
MakeDifferenceOptional,
IsUnion,
IsNonEmptyObject,
Assign,
IntersectAssign,
Timeout,
Updater,
NonNullableUpdater,
StringLiteral,
ThrowOrOptional,
ThrowConstraint,
ControlledPromise,
ExtractObjects,
PartialMergeAllObject,
MergeAllPrimitive,
ExtractPrimitives,
PartialMergeAll,
Constrain,
ConstrainLiteral,
UnionToIntersection,
MergeAllObjects,
MergeAll,
ValidateJSON,
StrictOrFrom,
LooseReturnType,
LooseAsyncReturnType,
Awaitable,
} from './utils'
export type {
StandardSchemaValidatorProps,
StandardSchemaValidator,
AnyStandardSchemaValidator,
StandardSchemaValidatorTypes,
AnyStandardSchemaValidateSuccess,
AnyStandardSchemaValidateFailure,
AnyStandardSchemaValidateIssue,
AnyStandardSchemaValidateInput,
AnyStandardSchemaValidate,
ValidatorObj,
AnyValidatorObj,
ValidatorAdapter,
AnyValidatorAdapter,
AnyValidatorFn,
ValidatorFn,
Validator,
AnyValidator,
AnySchema,
DefaultValidator,
ResolveSearchValidatorInputFn,
ResolveSearchValidatorInput,
ResolveValidatorInputFn,
ResolveValidatorInput,
ResolveValidatorOutputFn,
ResolveValidatorOutput,
} from './validators'
export type {
UseRouteContextBaseOptions,
UseRouteContextOptions,
UseRouteContextResult,
} from './useRouteContext'
export type { UseSearchResult, ResolveUseSearch } from './useSearch'
export type { UseParamsResult, ResolveUseParams } from './useParams'
export type { UseNavigateResult } from './useNavigate'
export type { UseLoaderDepsResult, ResolveUseLoaderDeps } from './useLoaderDeps'
export type { UseLoaderDataResult, ResolveUseLoaderData } from './useLoaderData'
export type {
Redirect,
RedirectOptions,
RedirectOptionsRoute,
RedirectFnRoute,
ResolvedRedirect,
AnyRedirect,
} from './redirect'
export {
redirect,
isRedirect,
isResolvedRedirect,
parseRedirect,
} from './redirect'
export type { NotFoundError } from './not-found'
export { isNotFound, notFound } from './not-found'
export {
defaultGetScrollRestorationKey,
getElementScrollRestorationEntry,
storageKey,
setupScrollRestoration,
} from './scroll-restoration'
export type {
ScrollRestorationOptions,
ScrollRestorationEntry,
} from './scroll-restoration'
export type {
ValidateFromPath,
ValidateToPath,
ValidateSearch,
ValidateParams,
InferFrom,
InferTo,
InferMaskTo,
InferMaskFrom,
ValidateNavigateOptions,
ValidateNavigateOptionsArray,
ValidateRedirectOptions,
ValidateRedirectOptionsArray,
ValidateId,
InferStrict,
InferShouldThrow,
InferSelected,
ValidateUseSearchResult,
ValidateUseParamsResult,
} from './typePrimitives'
export type {
AnySerializationAdapter,
SerializationAdapter,
ValidateSerializableInput,
SerializerExtensions,
ValidateSerializable,
RegisteredSerializableInput,
SerializableExtensions,
DefaultSerializable,
Serializable,
TSR_SERIALIZABLE,
TsrSerializable,
SerializationError,
} from './ssr/serializer/transformer'
export { createSerializationAdapter } from './ssr/serializer/transformer'
export { makeSerovalPlugin } from './ssr/serializer/makeSerovalPlugin'
export { RawStream } from './ssr/serializer/RawStream'
export type {
OnRawStreamCallback,
RawStreamHint,
RawStreamOptions,
} from './ssr/serializer/RawStream'
export { composeRewrites, executeRewriteInput } from './rewrite'
export type { LocationRewrite, LocationRewriteFunction } from './router'
+3
View File
@@ -0,0 +1,3 @@
export function invariant(): never {
throw new Error('Invariant failed')
}
+2
View File
@@ -0,0 +1,2 @@
export const isServer = false
export const loadServerRoute: never = undefined as never
+3
View File
@@ -0,0 +1,3 @@
// Development/test mode - returns undefined so fallback to router.isServer is used
export const isServer: boolean | undefined = undefined
export { loadServerRoute } from '../load-server'
+2
View File
@@ -0,0 +1,2 @@
export const isServer = process.env.NODE_ENV === 'test' ? undefined : true
export { loadServerRoute } from '../load-server'
+706
View File
@@ -0,0 +1,706 @@
import type { HistoryState, ParsedHistoryState } from '@tanstack/history'
import type {
AllParams,
CatchAllPaths,
CurrentPath,
FullSearchSchema,
FullSearchSchemaInput,
ParentPath,
RouteByPath,
RouteByToPath,
RoutePaths,
RouteToPath,
ToPath,
} from './routeInfo'
import type {
AnyRouter,
RegisteredRouter,
ViewTransitionOptions,
} from './router'
import type {
ConstrainLiteral,
Expand,
MakeDifferenceOptional,
NoInfer,
NonNullableUpdater,
Updater,
} from './utils'
import type { ParsedLocation } from './location'
export type IsRequiredParams<TParams> =
Record<never, never> extends TParams ? never : true
export interface ParsePathParamsResult<
in out TRequired,
in out TOptional,
in out TRest,
> {
required: TRequired
optional: TOptional
rest: TRest
}
export type AnyParsePathParamsResult = ParsePathParamsResult<
string,
string,
string
>
export type ParsePathParamsBoundaryStart<T extends string> =
T extends `${infer TLeft}{-${infer TRight}`
? ParsePathParamsResult<
ParsePathParams<TLeft>['required'],
| ParsePathParams<TLeft>['optional']
| ParsePathParams<TRight>['required']
| ParsePathParams<TRight>['optional'],
ParsePathParams<TRight>['rest']
>
: T extends `${infer TLeft}{${infer TRight}`
? ParsePathParamsResult<
| ParsePathParams<TLeft>['required']
| ParsePathParams<TRight>['required'],
| ParsePathParams<TLeft>['optional']
| ParsePathParams<TRight>['optional'],
ParsePathParams<TRight>['rest']
>
: never
export type ParsePathParamsSymbol<T extends string> =
T extends `${string}$${infer TRight}`
? TRight extends `${string}/${string}`
? TRight extends `${infer TParam}/${infer TRest}`
? TParam extends ''
? ParsePathParamsResult<
ParsePathParams<TRest>['required'],
'_splat' | ParsePathParams<TRest>['optional'],
ParsePathParams<TRest>['rest']
>
: ParsePathParamsResult<
TParam | ParsePathParams<TRest>['required'],
ParsePathParams<TRest>['optional'],
ParsePathParams<TRest>['rest']
>
: never
: TRight extends ''
? ParsePathParamsResult<never, '_splat', never>
: ParsePathParamsResult<TRight, never, never>
: never
export type ParsePathParamsBoundaryEnd<T extends string> =
T extends `${infer TLeft}}${infer TRight}`
? ParsePathParamsResult<
| ParsePathParams<TLeft>['required']
| ParsePathParams<TRight>['required'],
| ParsePathParams<TLeft>['optional']
| ParsePathParams<TRight>['optional'],
ParsePathParams<TRight>['rest']
>
: never
export type ParsePathParamsEscapeStart<T extends string> =
T extends `${infer TLeft}[${infer TRight}`
? ParsePathParamsResult<
| ParsePathParams<TLeft>['required']
| ParsePathParams<TRight>['required'],
| ParsePathParams<TLeft>['optional']
| ParsePathParams<TRight>['optional'],
ParsePathParams<TRight>['rest']
>
: never
export type ParsePathParamsEscapeEnd<T extends string> =
T extends `${string}]${infer TRight}` ? ParsePathParams<TRight> : never
export type ParsePathParams<T extends string> = T extends `${string}[${string}`
? ParsePathParamsEscapeStart<T>
: T extends `${string}]${string}`
? ParsePathParamsEscapeEnd<T>
: T extends `${string}}${string}`
? ParsePathParamsBoundaryEnd<T>
: T extends `${string}{${string}`
? ParsePathParamsBoundaryStart<T>
: T extends `${string}$${string}`
? ParsePathParamsSymbol<T>
: never
export type AddTrailingSlash<T> = T extends `${string}/` ? T : `${T & string}/`
export type RemoveTrailingSlashes<T> = T & `${string}/` extends never
? T
: T extends `${infer R}/`
? R
: T
export type AddLeadingSlash<T> = T & `/${string}` extends never
? `/${T & string}`
: T
export type RemoveLeadingSlashes<T> = T & `/${string}` extends never
? T
: T extends `/${infer R}`
? R
: T
type JoinPath<TLeft extends string, TRight extends string> = TRight extends ''
? TLeft
: TLeft extends ''
? TRight
: `${RemoveTrailingSlashes<TLeft>}/${RemoveLeadingSlashes<TRight>}`
type RemoveLastSegment<
T extends string,
TAcc extends string = '',
> = T extends `${infer TSegment}/${infer TRest}`
? TRest & `${string}/${string}` extends never
? TRest extends ''
? TAcc
: `${TAcc}${TSegment}`
: RemoveLastSegment<TRest, `${TAcc}${TSegment}/`>
: TAcc
export type ResolveCurrentPath<
TFrom extends string,
TTo extends string,
> = TTo extends '.'
? TFrom
: TTo extends './'
? AddTrailingSlash<TFrom>
: TTo & `./${string}` extends never
? never
: TTo extends `./${infer TRest}`
? AddLeadingSlash<JoinPath<TFrom, TRest>>
: never
export type ResolveParentPath<
TFrom extends string,
TTo extends string,
> = TTo extends '../' | '..'
? TFrom extends '' | '/'
? never
: AddLeadingSlash<RemoveLastSegment<TFrom>>
: TTo & `../${string}` extends never
? AddLeadingSlash<JoinPath<TFrom, TTo>>
: TFrom extends '' | '/'
? never
: TTo extends `../${infer ToRest}`
? ResolveParentPath<RemoveLastSegment<TFrom>, ToRest>
: AddLeadingSlash<JoinPath<TFrom, TTo>>
export type ResolveRelativePath<TFrom, TTo = '.'> = string extends TFrom
? TTo
: string extends TTo
? TFrom
: undefined extends TTo
? TFrom
: TTo extends string
? TFrom extends string
? TTo extends `/${string}`
? TTo
: TTo extends `..${string}`
? ResolveParentPath<TFrom, TTo>
: TTo extends `.${string}`
? ResolveCurrentPath<TFrom, TTo>
: AddLeadingSlash<JoinPath<TFrom, TTo>>
: never
: never
export type FindDescendantToPaths<
TRouter extends AnyRouter,
TPrefix extends string,
> = `${TPrefix}/${string}` & RouteToPath<TRouter>
export type InferDescendantToPaths<
TRouter extends AnyRouter,
TPrefix extends string,
TPaths = FindDescendantToPaths<TRouter, TPrefix>,
> = TPaths extends `${TPrefix}/`
? never
: TPaths extends `${TPrefix}/${infer TRest}`
? TRest
: never
export type RelativeToPath<
TRouter extends AnyRouter,
TTo extends string,
TResolvedPath extends string,
> =
| (TResolvedPath & RouteToPath<TRouter> extends never
? never
: ToPath<TRouter, TTo>)
| `${RemoveTrailingSlashes<TTo>}/${InferDescendantToPaths<TRouter, RemoveTrailingSlashes<TResolvedPath>>}`
export type RelativeToParentPath<
TRouter extends AnyRouter,
TFrom extends string,
TTo extends string,
TResolvedPath extends string = ResolveRelativePath<TFrom, TTo>,
> =
| RelativeToPath<TRouter, TTo, TResolvedPath>
| (TTo extends `${string}..` | `${string}../`
? TResolvedPath extends '/' | ''
? never
: FindDescendantToPaths<
TRouter,
RemoveTrailingSlashes<TResolvedPath>
> extends never
? never
: `${RemoveTrailingSlashes<TTo>}/${ParentPath<TRouter>}`
: never)
export type RelativeToCurrentPath<
TRouter extends AnyRouter,
TFrom extends string,
TTo extends string,
TResolvedPath extends string = ResolveRelativePath<TFrom, TTo>,
> = RelativeToPath<TRouter, TTo, TResolvedPath> | CurrentPath<TRouter>
export type AbsoluteToPath<TRouter extends AnyRouter, TFrom extends string> =
| (string extends TFrom
? CurrentPath<TRouter>
: TFrom extends `/`
? never
: CurrentPath<TRouter>)
| (string extends TFrom
? ParentPath<TRouter>
: TFrom extends `/`
? never
: ParentPath<TRouter>)
| RouteToPath<TRouter>
| (TFrom extends '/'
? never
: string extends TFrom
? never
: InferDescendantToPaths<TRouter, RemoveTrailingSlashes<TFrom>>)
export type RelativeToPathAutoComplete<
TRouter extends AnyRouter,
TFrom extends string,
TTo extends string,
> = string extends TTo
? string
: string extends TFrom
? AbsoluteToPath<TRouter, TFrom>
: TTo & `..${string}` extends never
? TTo & `.${string}` extends never
? AbsoluteToPath<TRouter, TFrom>
: RelativeToCurrentPath<TRouter, TFrom, TTo>
: RelativeToParentPath<TRouter, TFrom, TTo>
export type NavigateOptions<
TRouter extends AnyRouter = RegisteredRouter,
TFrom extends string = string,
TTo extends string | undefined = '.',
TMaskFrom extends string = TFrom,
TMaskTo extends string = '.',
> = ToOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & NavigateOptionProps
/**
* The NavigateOptions type is used to describe the options that can be used when describing a navigation action in TanStack Router.
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType)
*/
export interface NavigateOptionProps {
/**
* If set to `true`, the router will scroll the element with an id matching the hash into view with default `ScrollIntoViewOptions`.
* If set to `false`, the router will not scroll the element with an id matching the hash into view.
* If set to `ScrollIntoViewOptions`, the router will scroll the element with an id matching the hash into view with the provided options.
* @default true
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#hashscrollintoview)
* @see [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView)
*/
hashScrollIntoView?: boolean | ScrollIntoViewOptions
/**
* `replace` is a boolean that determines whether the navigation should replace the current history entry or push a new one.
* @default false
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#replace)
*/
replace?: boolean
/**
* Defaults to `true` so that the scroll position will be reset to 0,0 after the location is committed to the browser history.
* If `false`, the scroll position will not be reset to 0,0 after the location is committed to history.
* @default true
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#resetscroll)
*/
resetScroll?: boolean
/** @deprecated All navigations now use startTransition under the hood */
startTransition?: boolean
/**
* If set to `true`, the router will wrap the resulting navigation in a `document.startViewTransition()` call.
* If `ViewTransitionOptions`, route navigations will be called using `document.startViewTransition({update, types})`
* where `types` will be the strings array passed with `ViewTransitionOptions["types"]`.
* If the browser does not support viewTransition types, the navigation will fall back to normal `document.startTransition()`, same as if `true` was passed.
*
* If the browser does not support this api, this option will be ignored.
* @default false
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#viewtransition)
* @see [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition)
* @see [Google](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#view-transition-types)
*/
viewTransition?: boolean | ViewTransitionOptions
/**
* If `true`, navigation will ignore any blockers that might prevent it.
* @default false
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#ignoreblocker)
*/
ignoreBlocker?: boolean
/**
* If `true`, navigation to a route inside of router will trigger a full page load instead of the traditional SPA navigation.
* @default false
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#reloaddocument)
*/
reloadDocument?: boolean
/**
* This can be used instead of `to` to navigate to a fully built href, e.g. pointing to an external target.
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#href)
*/
href?: string
/** @internal */
publicHref?: string
}
export type ToOptions<
TRouter extends AnyRouter = RegisteredRouter,
TFrom extends string = string,
TTo extends string | undefined = '.',
TMaskFrom extends string = TFrom,
TMaskTo extends string = '.',
> = ToSubOptions<TRouter, TFrom, TTo> & MaskOptions<TRouter, TMaskFrom, TMaskTo>
export interface MaskOptions<
in out TRouter extends AnyRouter,
in out TMaskFrom extends string,
in out TMaskTo extends string,
> {
_fromLocation?: ParsedLocation
mask?: ToMaskOptions<TRouter, TMaskFrom, TMaskTo>
}
export type ToMaskOptions<
TRouter extends AnyRouter = RegisteredRouter,
TMaskFrom extends string = string,
TMaskTo extends string = '.',
> = ToSubOptions<TRouter, TMaskFrom, TMaskTo> & {
unmaskOnReload?: boolean
}
export type ToSubOptions<
TRouter extends AnyRouter = RegisteredRouter,
TFrom extends string = string,
TTo extends string | undefined = '.',
> = ToSubOptionsProps<TRouter, TFrom, TTo> &
SearchParamOptions<TRouter, TFrom, TTo> &
PathParamOptions<TRouter, TFrom, TTo>
export interface RequiredToOptions<
in out TRouter extends AnyRouter,
in out TFrom extends string,
in out TTo extends string | undefined,
> {
/**
* The internal route path to navigate to. This should be a relative or absolute path within your application.
* For external URLs, use the `href` property instead.
* @example "/dashboard" or "../profile"
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#href)
*/
to: ToPathOption<TRouter, TFrom, TTo> & {}
}
export interface OptionalToOptions<
in out TRouter extends AnyRouter,
in out TFrom extends string,
in out TTo extends string | undefined,
> {
/**
* The internal route path to navigate to. This should be a relative or absolute path within your application.
* For external URLs, use the `href` property instead.
* @example "/dashboard" or "../profile"
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType#href)
*/
to?: ToPathOption<TRouter, TFrom, TTo> & {}
}
export type MakeToRequired<
TRouter extends AnyRouter,
TFrom extends string,
TTo extends string | undefined,
> = string extends TFrom
? string extends TTo
? OptionalToOptions<TRouter, TFrom, TTo>
: TTo & CatchAllPaths<TRouter> extends never
? RequiredToOptions<TRouter, TFrom, TTo>
: OptionalToOptions<TRouter, TFrom, TTo>
: OptionalToOptions<TRouter, TFrom, TTo>
export type ToSubOptionsProps<
TRouter extends AnyRouter = RegisteredRouter,
TFrom extends RoutePaths<TRouter['routeTree']> | string = string,
TTo extends string | undefined = '.',
> = MakeToRequired<TRouter, TFrom, TTo> & {
hash?: true | Updater<string>
state?: true | NonNullableUpdater<ParsedHistoryState, HistoryState>
from?: FromPathOption<TRouter, TFrom> & {}
unsafeRelative?: 'path'
}
export type ParamsReducerFn<
in out TRouter extends AnyRouter,
in out TParamVariant extends ParamVariant,
in out TFrom,
in out TTo,
> = (
current: Expand<ResolveFromParams<TRouter, TParamVariant, TFrom>>,
) => Expand<ResolveRelativeToParams<TRouter, TParamVariant, TFrom, TTo>>
type ParamsReducer<
TRouter extends AnyRouter,
TParamVariant extends ParamVariant,
TFrom,
TTo,
> =
| Expand<ResolveRelativeToParams<TRouter, TParamVariant, TFrom, TTo>>
| (ParamsReducerFn<TRouter, TParamVariant, TFrom, TTo> & {})
type ParamVariant = 'PATH' | 'SEARCH'
export type ResolveRoute<
TRouter extends AnyRouter,
TFrom,
TTo,
TPath = ResolveRelativePath<TFrom, TTo>,
> = TPath extends string
? TFrom extends TPath
? RouteByPath<TRouter['routeTree'], TPath>
: RouteByToPath<TRouter, TPath>
: never
type ResolveFromParamType<TParamVariant extends ParamVariant> =
TParamVariant extends 'PATH' ? 'allParams' : 'fullSearchSchema'
type ResolveFromAllParams<
TRouter extends AnyRouter,
TParamVariant extends ParamVariant,
> = TParamVariant extends 'PATH'
? AllParams<TRouter['routeTree']>
: FullSearchSchema<TRouter['routeTree']>
type ResolveFromParams<
TRouter extends AnyRouter,
TParamVariant extends ParamVariant,
TFrom,
> = string extends TFrom
? ResolveFromAllParams<TRouter, TParamVariant>
: RouteByPath<
TRouter['routeTree'],
TFrom
>['types'][ResolveFromParamType<TParamVariant>]
type ResolveToParamType<TParamVariant extends ParamVariant> =
TParamVariant extends 'PATH' ? 'allParams' : 'fullSearchSchemaInput'
type ResolveAllToParams<
TRouter extends AnyRouter,
TParamVariant extends ParamVariant,
> = TParamVariant extends 'PATH'
? AllParams<TRouter['routeTree']>
: FullSearchSchemaInput<TRouter['routeTree']>
export type ResolveToParams<
TRouter extends AnyRouter,
TParamVariant extends ParamVariant,
TFrom,
TTo,
> =
ResolveRelativePath<TFrom, TTo> extends infer TPath
? undefined extends TPath
? never
: string extends TPath
? ResolveAllToParams<TRouter, TParamVariant>
: TPath extends CatchAllPaths<TRouter>
? ResolveAllToParams<TRouter, TParamVariant>
: ResolveRoute<
TRouter,
TFrom,
TTo
>['types'][ResolveToParamType<TParamVariant>]
: never
type ResolveRelativeToParams<
TRouter extends AnyRouter,
TParamVariant extends ParamVariant,
TFrom,
TTo,
TToParams = ResolveToParams<TRouter, TParamVariant, TFrom, TTo>,
> = TParamVariant extends 'SEARCH'
? TToParams
: string extends TFrom
? TToParams
: MakeDifferenceOptional<
ResolveFromParams<TRouter, TParamVariant, TFrom>,
TToParams
>
export interface MakeOptionalSearchParams<
in out TRouter extends AnyRouter,
in out TFrom,
in out TTo,
> {
search?: true | (ParamsReducer<TRouter, 'SEARCH', TFrom, TTo> & {})
}
export interface MakeOptionalPathParams<
in out TRouter extends AnyRouter,
in out TFrom,
in out TTo,
> {
params?: true | (ParamsReducer<TRouter, 'PATH', TFrom, TTo> & {})
}
type MakeRequiredParamsReducer<
TRouter extends AnyRouter,
TParamVariant extends ParamVariant,
TFrom,
TTo,
> =
| (string extends TFrom
? never
: ResolveFromParams<
TRouter,
TParamVariant,
TFrom
> extends ResolveRelativeToParams<TRouter, TParamVariant, TFrom, TTo>
? true
: never)
| (ParamsReducer<TRouter, TParamVariant, TFrom, TTo> & {})
export interface MakeRequiredPathParams<
in out TRouter extends AnyRouter,
in out TFrom,
in out TTo,
> {
params: MakeRequiredParamsReducer<TRouter, 'PATH', TFrom, TTo> & {}
}
export interface MakeRequiredSearchParams<
in out TRouter extends AnyRouter,
in out TFrom,
in out TTo,
> {
search: MakeRequiredParamsReducer<TRouter, 'SEARCH', TFrom, TTo> & {}
}
export type IsRequired<
TRouter extends AnyRouter,
TParamVariant extends ParamVariant,
TFrom,
TTo,
> =
ResolveRelativePath<TFrom, TTo> extends infer TPath
? undefined extends TPath
? never
: TPath extends CatchAllPaths<TRouter>
? never
: IsRequiredParams<
ResolveRelativeToParams<TRouter, TParamVariant, TFrom, TTo>
>
: never
export type SearchParamOptions<TRouter extends AnyRouter, TFrom, TTo> =
IsRequired<TRouter, 'SEARCH', TFrom, TTo> extends never
? MakeOptionalSearchParams<TRouter, TFrom, TTo>
: MakeRequiredSearchParams<TRouter, TFrom, TTo>
export type PathParamOptions<TRouter extends AnyRouter, TFrom, TTo> =
IsRequired<TRouter, 'PATH', TFrom, TTo> extends never
? MakeOptionalPathParams<TRouter, TFrom, TTo>
: MakeRequiredPathParams<TRouter, TFrom, TTo>
export type ToPathOption<
TRouter extends AnyRouter = AnyRouter,
TFrom extends string = string,
TTo extends string | undefined = string,
> = ConstrainLiteral<
TTo,
RelativeToPathAutoComplete<
TRouter,
NoInfer<TFrom> extends string ? NoInfer<TFrom> : '',
NoInfer<TTo> & string
>
>
export type FromPathOption<TRouter extends AnyRouter, TFrom> = ConstrainLiteral<
TFrom,
RoutePaths<TRouter['routeTree']>
>
/**
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/navigation#active-options)
*/
export interface ActiveOptions {
/**
* If true, the link will be active if the current route matches the `to` route path exactly (no children routes)
* @default false
*/
exact?: boolean
/**
* If true, the link will only be active if the current URL hash matches the `hash` prop
* @default false
*/
includeHash?: boolean
/**
* If true, the link will only be active if the current URL search params inclusively match the `search` prop
* @default true
*/
includeSearch?: boolean
/**
* This modifies the `includeSearch` behavior.
* If true, properties in `search` that are explicitly `undefined` must NOT be present in the current URL search params for the link to be active.
* @default false
*/
explicitUndefined?: boolean
}
export interface LinkOptionsProps {
/**
* The standard anchor tag target attribute
*/
target?: HTMLAnchorElement['target']
/**
* Configurable options to determine if the link should be considered active or not
* @default {exact:true,includeHash:true}
*/
activeOptions?: ActiveOptions
/**
* The preloading strategy for this link
* - `false` - No preloading
* - `'intent'` - Preload the linked route when the user focuses, hovers over, or touches the link
* - `'viewport'` - Preload the linked route when it enters the viewport
* - `'render'` - Preload the linked route as soon as it renders
*/
preload?: false | 'intent' | 'viewport' | 'render'
/**
* Delays focus, hover, and viewport preloading by this many milliseconds.
* Touch intent preloads immediately. If focus or hover ends, or the link
* leaves the viewport before this delay, the preload will be cancelled.
*/
preloadDelay?: number
/**
* Control whether the link should be disabled or not
* If set to `true`, the link will be rendered without an `href` attribute
* @default false
*/
disabled?: boolean
/**
* When the preload strategy is set to `intent`, this controls the proximity of the link to the cursor before it is preloaded.
* If the user exits this proximity before this delay, the preload will be cancelled.
*/
preloadIntentProximity?: number
}
export type LinkOptions<
TRouter extends AnyRouter = RegisteredRouter,
TFrom extends string = string,
TTo extends string | undefined = '.',
TMaskFrom extends string = TFrom,
TMaskTo extends string = '.',
> = NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & LinkOptionsProps
export const preloadWarning = 'Error preloading route! ☝️'
File diff suppressed because it is too large. Load diff
+962
View File
@@ -0,0 +1,962 @@
// Keep this filename free of a secondary extension so declaration generation
// can rewrite relative imports for both ESM and CJS.
import { isNotFound } from './not-found'
import { isRedirect, redirect } from './redirect'
import { rootRouteId } from './root'
import { loadRouteChunk } from './load-client'
import { waitForReason } from './await-signal'
import {
getLocationChangeInfo,
lifecycleEnd,
runRouteLifecycle,
} from './router'
import type { ParsedLocation } from './location'
import type { AnyRouteMatch } from './Matches'
import type { NotFoundError } from './not-found'
import type {
AnyRoute,
BeforeLoadContextOptions,
LoaderFnContext,
RouteContextOptions,
SsrContextOptions,
} from './route'
import type { AnyRedirect } from './redirect'
import type { AnyRouter, SSROption } from './router'
declare const serverLanePhase: unique symbol
type ServerLane<TPhase extends 'matched' | 'contextualized' | 'reduced'> = {
readonly [serverLanePhase]: TPhase
location: ParsedLocation
matches: Array<AnyRouteMatch>
}
type MatchedLane = ServerLane<'matched'>
type IndexedOutcome = [index: number, outcome: LoaderOutcome, boundary?: number]
type ContextualizedLane = ServerLane<'contextualized'> & {
end: number
failure?: IndexedOutcome
}
type ReducedLane = ServerLane<'reduced'>
const SUCCESS = 0
const ERROR = 1
const NOT_FOUND = 2
const REDIRECTED = 3
const SKIPPED = 4
const MATCH_SETTLED_ABORT_REASON = Object.freeze({
name: 'AbortError',
message: 'TanStack Router aborted this server match because it settled.',
})
const REDIRECT_ABORT_REASON = Object.freeze({
name: 'AbortError',
message: 'TanStack Router aborted this server match because of a redirect.',
})
type LoaderOutcome =
| [typeof SUCCESS, data: unknown]
| [typeof ERROR, error: unknown]
| [typeof NOT_FOUND, error: NotFoundError]
| [typeof REDIRECTED, redirect: AnyRedirect]
| [typeof SKIPPED]
type LoaderTask = {
index: number
outcome: Promise<LoaderOutcome>
match: Promise<AnyRouteMatch>
}
export type ServerLoadResult =
| {
type: 'render'
status: 200 | 404 | 500
matches: Array<AnyRouteMatch>
}
| { type: 'redirect'; redirect: AnyRedirect }
function getRoute(router: AnyRouter, match: AnyRouteMatch): AnyRoute {
return router.routesById[match.routeId]
}
function normalize(value: unknown, rejected: boolean): LoaderOutcome {
if (isRedirect(value)) {
return [REDIRECTED, value]
}
if (isNotFound(value)) {
return [NOT_FOUND, value]
}
if (rejected && typeof (value as any)?.then === 'function') {
value = new Error('A Promise was thrown', { cause: value })
}
return rejected ? [ERROR, value] : [SUCCESS, value]
}
function normalizeError(
router: AnyRouter,
lane: { location: ParsedLocation },
route: AnyRoute,
cause: unknown,
signal?: AbortSignal,
notify = true,
): LoaderOutcome {
signal?.throwIfAborted()
let outcome = normalize(cause, true)
if (outcome[0] !== ERROR) {
return materializeRedirect(router, lane, route, outcome, signal, notify)
}
try {
route.options.onError?.(outcome[1])
} catch (onErrorCause) {
outcome = normalize(onErrorCause, true)
}
signal?.throwIfAborted()
return materializeRedirect(router, lane, route, outcome, signal, notify)
}
function materializeRedirect(
router: AnyRouter,
lane: { location: ParsedLocation },
route: AnyRoute,
outcome: LoaderOutcome,
signal?: AbortSignal,
notify = true,
): LoaderOutcome {
if (outcome[0] !== REDIRECTED) {
return outcome
}
signal?.throwIfAborted()
try {
outcome[1].options._fromLocation = lane.location
router.resolveRedirect(outcome[1])
signal?.throwIfAborted()
return outcome
} catch (cause) {
signal?.throwIfAborted()
return notify
? normalizeError(router, lane, route, cause, signal, false)
: [ERROR, cause]
}
}
function maybe<TValue>(
value: TValue,
cause: unknown,
): { status: 'success'; value: TValue } | { status: 'error'; error: unknown } {
if (cause !== undefined) {
return { status: 'error', error: cause }
}
return { status: 'success', value }
}
function navigateFrom(router: AnyRouter, location: ParsedLocation) {
return (options: any) =>
router.navigate({
...options,
_fromLocation: location,
})
}
function waitFor<T>(value: Promise<T>, signal?: AbortSignal): Promise<T> {
return signal ? waitForReason(value, signal) : value
}
function resolveSsr(
router: AnyRouter,
lane: MatchedLane,
index: number,
): SSROption | Promise<SSROption> {
const match = lane.matches[index]!
const route = getRoute(router, match)
const parentSsr = lane.matches[index - 1]?.ssr
if (router.isShell()) {
return route.id === rootRouteId
}
if (parentSsr === false) {
return false
}
const inherit = (value: SSROption): SSROption => {
return value === true && parentSsr === 'data-only' ? 'data-only' : value
}
const defaultSsr = router.options.defaultSsr ?? true
const inheritedDefault = inherit(defaultSsr)
// A functional override can fail. Establish the inherited policy first so
// the selected error boundary retains the route's actual renderability.
match.ssr = inheritedDefault
const option = route.options.ssr
if (option === undefined) {
return inheritedDefault
}
if (typeof option !== 'function') {
return inherit(option)
}
const context: SsrContextOptions<any, any, any> = {
search: maybe(match.search, match.searchError),
params: maybe(match.params, match.paramsError),
location: lane.location,
matches: lane.matches.map((candidate) => ({
index: candidate.index,
pathname: candidate.pathname,
fullPath: candidate.fullPath,
staticData: candidate.staticData,
id: candidate.id,
routeId: candidate.routeId,
search: maybe(candidate.search, candidate.searchError),
params: maybe(candidate.params, candidate.paramsError),
ssr: candidate.ssr,
})),
}
try {
return Promise.resolve(option(context)).then((value) =>
inherit(value ?? defaultSsr),
)
} catch (cause) {
// Functional failures keep their asynchronous cancellation checkpoint.
return Promise.reject(cause)
}
}
function stampNotFound(
match: AnyRouteMatch,
outcome: LoaderOutcome,
): LoaderOutcome {
if (outcome[0] === NOT_FOUND && !outcome[1].routeId) {
outcome[1].routeId = match.routeId
}
return outcome
}
async function contextualize(
router: AnyRouter,
lane: MatchedLane,
signal?: AbortSignal,
): Promise<ContextualizedLane> {
const globalBoundary = lane.matches.findIndex((match) => match._notFound)
let end = globalBoundary < 0 ? lane.matches.length : globalBoundary + 1
let failure: IndexedOutcome | undefined
let parentContext: Record<string, unknown> = {
...(router.options.context ?? {}),
}
for (let index = 0; index < end; index++) {
const match = lane.matches[index]!
const route = getRoute(router, match)
try {
const ssr = resolveSsr(router, lane, index)
// Functional policies are assimilated into a native Promise above.
match.ssr = ssr instanceof Promise ? await ssr : ssr
} catch (cause) {
signal?.throwIfAborted()
failure = [
index,
stampNotFound(
match,
normalizeError(router, lane, route, cause, signal),
),
]
end = index
}
signal?.throwIfAborted()
if (failure?.[1][0] === REDIRECTED) {
break
}
match.__beforeLoadContext = undefined
let context = parentContext
try {
let routeContext
if (route.options.context) {
const routeContextOptions: RouteContextOptions<
any,
any,
any,
any,
any
> = {
deps: match.loaderDeps,
params: match.params,
context: parentContext,
location: lane.location,
navigate: navigateFrom(router, lane.location),
buildLocation: router.buildLocation,
cause: match.cause,
abortController: match.abortController,
preload: false,
matches: lane.matches,
routeId: route.id,
}
routeContext = route.options.context(routeContextOptions) ?? undefined
}
context = {
...parentContext,
...routeContext,
}
match.context = context
} catch (cause) {
signal?.throwIfAborted()
if (!failure) {
failure = [
index,
stampNotFound(
match,
normalizeError(router, lane, route, cause, signal),
),
]
}
end = index
break
}
signal?.throwIfAborted()
if (failure) {
break
}
const validationError = match.paramsError ?? match.searchError
if (validationError !== undefined) {
failure = [
index,
stampNotFound(
match,
normalizeError(router, lane, route, validationError, signal),
),
]
end = index
break
}
signal?.throwIfAborted()
if (match.ssr === false || !route.options.beforeLoad) {
parentContext = context
continue
}
const abortController = match.abortController
const options: BeforeLoadContextOptions<
any,
any,
any,
any,
any,
any,
any,
any,
any
> = {
search: match.search,
abortController,
params: match.params,
preload: false,
context,
location: lane.location,
navigate: navigateFrom(router, lane.location),
buildLocation: router.buildLocation,
cause: match.cause,
matches: lane.matches,
routeId: route.id,
...router.options.additionalContext,
}
try {
const beforeLoadContext = await route.options.beforeLoad(options)
signal?.throwIfAborted()
const outcome = stampNotFound(
match,
materializeRedirect(
router,
lane,
route,
normalize(beforeLoadContext, false),
signal,
),
)
if (outcome[0] !== SUCCESS) {
failure = [index, outcome]
end = index
break
}
match.__beforeLoadContext = beforeLoadContext
match.context = {
...context,
...beforeLoadContext,
}
parentContext = match.context
} catch (cause) {
signal?.throwIfAborted()
failure = [
index,
stampNotFound(
match,
normalizeError(router, lane, route, cause, signal),
),
]
end = index
break
}
}
return {
location: lane.location,
matches: lane.matches,
end,
failure,
} as ContextualizedLane
}
function getLoaderContext(
router: AnyRouter,
lane: ContextualizedLane,
match: AnyRouteMatch,
route: AnyRoute,
index: number,
tasks: Array<LoaderTask>,
): LoaderFnContext {
return {
params: match.params,
deps: match.loaderDeps,
preload: false,
parentMatchPromise: tasks[index - 1]?.match,
abortController: match.abortController,
context: match.context,
location: lane.location,
navigate: navigateFrom(router, lane.location),
cause: match.cause,
route,
...router.options.additionalContext,
}
}
function createLoaderTask(
router: AnyRouter,
lane: ContextualizedLane,
index: number,
tasks: Array<LoaderTask>,
signal?: AbortSignal,
): LoaderTask {
const match = lane.matches[index]!
const route = getRoute(router, match)
let outcome: Promise<LoaderOutcome>
if (match.ssr === false) {
outcome = Promise.resolve<LoaderOutcome>([SKIPPED])
} else {
const routeLoader = route.options.loader
const loader =
typeof routeLoader === 'function' ? routeLoader : routeLoader?.handler
if (!loader) {
outcome = Promise.resolve<LoaderOutcome>([SUCCESS, undefined])
} else {
outcome = Promise.resolve()
.then(() =>
loader(getLoaderContext(router, lane, match, route, index, tasks)),
)
.then(
(result) => normalize(result, false),
(cause) => normalize(cause, true),
)
.then((result): LoaderOutcome => {
if (
signal?.aborted ||
match.abortController.signal.reason === REDIRECT_ABORT_REASON
) {
return [SKIPPED]
}
if (result[0] === ERROR) {
result = normalizeError(router, lane, route, result[1], signal)
} else {
result = materializeRedirect(router, lane, route, result, signal)
}
return stampNotFound(match, result)
})
}
}
const parentMatch = outcome.then((result) => {
const snapshot = { ...match }
if (result[0] === SUCCESS) {
snapshot.loaderData = result[1]
snapshot.status = 'success'
snapshot.error = undefined
snapshot.invalid = false
snapshot.isFetching = false
} else if (result[0] === ERROR) {
snapshot.status = 'error'
snapshot.error = result[1]
} else if (result[0] === NOT_FOUND) {
snapshot.status = 'notFound'
snapshot.error = result[1]
}
return snapshot
})
return { index, outcome, match: parentMatch }
}
async function getNotFoundBoundary(
router: AnyRouter,
matches: Array<AnyRouteMatch>,
indexed: IndexedOutcome | undefined,
signal?: AbortSignal,
fallback = 0,
): Promise<number> {
const cause = indexed?.[1][1] as NotFoundError | undefined
let index = cause?.routeId
? matches.findIndex((match) => match.routeId === cause.routeId)
: (indexed?.[0] ?? matches.length - 1)
if (index < 0) {
index = 0
}
for (let candidate = index; candidate >= 0; candidate--) {
const route = getRoute(router, matches[candidate]!)
try {
const loading = loadRouteChunk(route, false)
if (loading) {
await loading
}
} catch {
signal?.throwIfAborted()
}
signal?.throwIfAborted()
if (route.options.notFoundComponent) {
return candidate
}
}
return cause?.routeId ? index : fallback
}
function abortMatches(
matches: Array<AnyRouteMatch>,
start = 0,
reason: unknown = MATCH_SETTLED_ABORT_REASON,
): void {
for (let index = start; index < matches.length; index++) {
matches[index]!.abortController.abort(reason)
}
}
async function applyFailure(
router: AnyRouter,
lane: ContextualizedLane,
indexed: IndexedOutcome | undefined,
signal?: AbortSignal,
): Promise<{ status: 200 | 404 | 500; boundary?: number; kind?: number }> {
if (!indexed) {
const boundary = lane.matches.findIndex((match) => match._notFound)
if (boundary >= 0) {
abortMatches(lane.matches, boundary + 1)
return { status: 404, boundary, kind: NOT_FOUND }
}
return { status: 200 }
}
const [index, outcome] = indexed
if (outcome[0] === ERROR) {
const match = lane.matches[index]!
match._notFound = undefined
match.status = 'error'
match.error = outcome[1]
match.isFetching = false
abortMatches(lane.matches, index + 1)
return { status: 500, boundary: index, kind: ERROR }
}
const boundary =
indexed[2] ??
(await getNotFoundBoundary(router, lane.matches, indexed, signal))
const match = lane.matches[boundary]!
const cause = outcome[1] as NotFoundError
cause.routeId = match.routeId
match._notFound = undefined
if (match.routeId === router.routeTree.id) {
match.status = 'success'
match._notFound = true
match.error = cause
} else {
match.status = 'notFound'
match.error = cause
}
match.isFetching = false
abortMatches(lane.matches, boundary + 1)
return { status: 404, boundary, kind: NOT_FOUND }
}
async function loadNormalChunks(
router: AnyRouter,
lane: ContextualizedLane,
end: number,
signal?: AbortSignal,
): Promise<IndexedOutcome | undefined> {
const chunks: Array<IndexedOutcome | Promise<IndexedOutcome | undefined>> = []
for (let index = 0; index < lane.matches.length; index++) {
const match = lane.matches[index]!
if (index >= end || match.ssr !== true || match.status !== 'success') {
continue
}
const route = getRoute(router, match)
try {
const loading = loadRouteChunk(route)
if (loading) {
const chunk = loading.then(
() => {
signal?.throwIfAborted()
return undefined
},
(cause) => {
signal?.throwIfAborted()
return [
index,
stampNotFound(
match,
normalizeError(router, lane, route, cause, signal),
),
] as IndexedOutcome
},
)
// Route-order reduction can return before later chunks settle.
void chunk.catch(() => {})
chunks.push(chunk)
}
} catch (cause) {
signal?.throwIfAborted()
chunks.push([
index,
stampNotFound(
match,
normalizeError(router, lane, route, cause, signal),
),
])
}
}
for (const chunk of chunks) {
const indexed = Array.isArray(chunk) ? chunk : await chunk
if (indexed) {
return indexed
}
}
return undefined
}
async function projectLane(
router: AnyRouter,
lane: ReducedLane,
signal?: AbortSignal,
): Promise<void> {
for (const match of lane.matches) {
const routeOptions = getRoute(router, match).options
if (routeOptions.head || routeOptions.scripts || routeOptions.headers) {
const context = {
ssr: router.options.ssr,
matches: lane.matches,
match,
params: match.params,
loaderData: match.loaderData,
}
try {
const [head, scripts, headers] = await Promise.all([
routeOptions.head?.(context),
routeOptions.scripts?.(context),
routeOptions.headers?.(context),
])
signal?.throwIfAborted()
match.meta = head?.meta
match.links = head?.links
match.headScripts = head?.scripts
match.styles = head?.styles
match.scripts = scripts
match.headers = headers
} catch (cause) {
signal?.throwIfAborted()
console.error(cause)
}
}
if (match.ssr === false || match.status !== 'success' || match._notFound) {
break
}
}
}
async function executeServerLane(
router: AnyRouter,
location: ParsedLocation,
matchedMatches: Array<AnyRouteMatch>,
signal?: AbortSignal,
): Promise<ServerLoadResult> {
const matched = {
location,
matches: matchedMatches.map((match) => ({
...match,
__beforeLoadContext: undefined,
context: {},
isFetching: false,
abortController: new AbortController(),
})),
} as MatchedLane
const abortLane = () =>
abortMatches(
matched.matches,
0,
signal?.reason ?? MATCH_SETTLED_ABORT_REASON,
)
if (signal?.aborted) {
abortLane()
signal.throwIfAborted()
}
signal?.addEventListener('abort', abortLane, { once: true })
try {
const plannedGlobalBoundary = matched.matches.findIndex(
(match) => match._notFound,
)
if (router.options.notFoundMode !== 'root' && plannedGlobalBoundary >= 0) {
const boundary = await getNotFoundBoundary(
router,
matched.matches,
undefined,
signal,
plannedGlobalBoundary,
)
if (boundary !== plannedGlobalBoundary) {
matched.matches[plannedGlobalBoundary]!._notFound = undefined
matched.matches[boundary]!._notFound = true
}
}
const lane = await contextualize(router, matched, signal)
signal?.throwIfAborted()
let loaderEnd = lane.end
if (lane.failure?.[1][0] === REDIRECTED) {
loaderEnd = 0
} else if (lane.failure?.[1][0] === NOT_FOUND) {
lane.failure[2] = await getNotFoundBoundary(
router,
lane.matches,
lane.failure,
signal,
)
loaderEnd = Math.min(loaderEnd, lane.failure[2] + 1)
}
const tasks: Array<LoaderTask> = []
for (let index = 0; index < loaderEnd; index++) {
const task = createLoaderTask(router, lane, index, tasks, signal)
tasks.push(task)
}
let loaderFailure: IndexedOutcome | undefined
let control = lane.failure?.[1][0] === REDIRECTED ? lane.failure : undefined
try {
await Promise.all(
tasks.map((task) =>
task.outcome.then((loadedOutcome) => {
const match = lane.matches[task.index]!
const outcome = loadedOutcome
if (outcome[0] === SUCCESS) {
match.loaderData = outcome[1]
match.status = 'success'
match.error = undefined
match.invalid = false
match.isFetching = false
match.updatedAt = Date.now()
} else if (outcome[0] === REDIRECTED) {
control = [task.index, outcome]
throw control
} else {
// A selective-SSR skip must stay pending for hydration. Every
// settled server attempt is otherwise renderable unless
// reduction selects it as the lane's terminal failure.
if (match.ssr !== false) {
match.status = 'success'
match.error = undefined
match.invalid = true
match.isFetching = false
}
if (!loaderFailure && outcome[0] !== SKIPPED) {
loaderFailure = [task.index, outcome]
}
}
}),
),
)
} catch (cause) {
if (!Array.isArray(cause)) {
throw cause
}
control = cause as IndexedOutcome
}
signal?.throwIfAborted()
if (control?.[1][0] === REDIRECTED) {
abortMatches(lane.matches, 0, REDIRECT_ABORT_REASON)
return { type: 'redirect', redirect: control[1][1] }
}
let failure = lane.failure ?? loaderFailure
const plannedBoundary = lane.matches.findIndex((match) => match._notFound)
let readinessEnd: number
if (failure) {
const outcomeEnd = (failure[2] ??=
failure[1][0] === NOT_FOUND
? await getNotFoundBoundary(router, lane.matches, failure, signal)
: failure[0])
for (const task of tasks) {
if (task.index >= outcomeEnd) {
break
}
const outcome = await task.outcome
// Presence means a loader previously succeeded, even with `undefined`.
if (
outcome[0] !== SUCCESS &&
outcome[0] < REDIRECTED &&
!('loaderData' in lane.matches[task.index]!)
) {
failure = [task.index, outcome]
failure[2] =
outcome[0] === NOT_FOUND
? await getNotFoundBoundary(router, lane.matches, failure, signal)
: task.index
break
}
}
readinessEnd = failure[2]
} else {
readinessEnd = plannedBoundary < 0 ? lane.matches.length : plannedBoundary
}
const requiredFailure = await loadNormalChunks(
router,
lane,
readinessEnd,
signal,
)
signal?.throwIfAborted()
if (requiredFailure) {
if (requiredFailure[1][0] === REDIRECTED) {
abortMatches(lane.matches, 0, REDIRECT_ABORT_REASON)
return { type: 'redirect', redirect: requiredFailure[1][1] }
}
failure = requiredFailure
}
const terminal = await applyFailure(router, lane, failure, signal)
if (terminal.boundary !== undefined) {
const match = lane.matches[terminal.boundary]!
if (match.ssr === true) {
const route = getRoute(router, match)
try {
if (terminal.kind === ERROR) {
await loadRouteChunk(route, 'errorComponent')
} else if (match._notFound) {
await Promise.all([
loadRouteChunk(route),
loadRouteChunk(route, 'notFoundComponent'),
])
} else {
await loadRouteChunk(route, 'notFoundComponent')
}
} catch {}
signal?.throwIfAborted()
}
}
signal?.throwIfAborted()
await projectLane(
router,
{
location: lane.location,
matches: lane.matches,
} as ReducedLane,
signal,
)
signal?.throwIfAborted()
// Deferred loader work can outlive this lane, and the request signal above
// only covers one way a response ends. SSR cleanup covers them all:
//
// - client disconnected -> abort (work may be pending)
// - serialization or lifetime timeout -> abort (a deferred value hung)
// - body disposed server-side (HEAD strip,
// middleware replaced the response) -> abort (never delivered)
// - plain response / `hydrate: false`: the
// loader data was never dehydrated -> abort (never consumed)
// - stream completed: every dehydrated value
// already settled -> nothing left to abort
//
// `settled` is false in exactly the first four cases.
router.serverSsr?.onCleanup((settled) => {
if (!settled) {
abortLane()
}
})
return { type: 'render', status: terminal.status, matches: lane.matches }
} finally {
signal?.removeEventListener('abort', abortLane)
}
}
type ServerLoadOptions = NonNullable<Parameters<AnyRouter['load']>[0]> & {
_signal?: AbortSignal
}
export async function loadServerRoute(
router: AnyRouter,
opts?: ServerLoadOptions,
): Promise<void> {
router.updateLatestLocation()
const next = router.latestLocation
const previous = router._committed
const previousEnd = router._lifecycleEnd
let result: ServerLoadResult
try {
const canonical = router.buildLocation({
to: next.pathname,
search: true,
params: true,
hash: true,
state: true,
_includeValidateSearch: true,
})
if (next.publicHref !== canonical.publicHref) {
const href = canonical.publicHref || '/'
throw redirect({ href })
}
const fromLocation = router.stores.resolvedLocation.get()
const changeInfo = getLocationChangeInfo(next, fromLocation)
router.emit({ type: 'onBeforeNavigate', ...changeInfo })
router.emit({ type: 'onBeforeLoad', ...changeInfo })
opts?._signal?.throwIfAborted()
result = await waitFor(
executeServerLane(router, next, router.matchRoutes(next), opts?._signal),
opts?._signal,
)
opts?._signal?.throwIfAborted()
} catch (cause) {
opts?._signal?.throwIfAborted()
if (!isRedirect(cause)) {
throw cause
}
cause.options._fromLocation = next
result = { type: 'redirect', redirect: router.resolveRedirect(cause) }
}
router._serverResult = result
let nextEnd = 0
router.batch(() => {
router.stores.location.set(next)
router.stores.status.set('idle')
if (result.type === 'render') {
router._committed = result.matches
nextEnd = router._lifecycleEnd = lifecycleEnd(result.matches)
router.stores.setMatches(result.matches)
router.stores.resolvedLocation.set(next)
}
})
if (result.type === 'render') {
runRouteLifecycle(router, previous, result.matches, previousEnd, nextEnd)
}
router._commitPromise?.resolve()
router._commitPromise = undefined
}
+51
View File
@@ -0,0 +1,51 @@
import type { ParsedHistoryState } from '@tanstack/history'
import type { AnySchema } from './validators'
export interface ParsedLocation<TSearchObj extends AnySchema = {}> {
/**
* The full path of the location, including pathname, search, and hash.
* Does not include the origin. Is the equivalent of calling
* `url.replace(url.origin, '')`
*/
href: string
/**
* @description The pathname of the location, including the leading slash.
*/
pathname: string
/**
* The parsed search parameters of the location in object form.
*/
search: TSearchObj
/**
* The search string of the location, including the leading question mark.
*/
searchStr: string
/**
* The in-memory state of the location as it *may* exist in the browser's history.
*/
state: ParsedHistoryState
/**
* The hash of the location, excluding the leading hash character.
* (e.g., '123' instead of '#123')
*/
hash: string
/**
* The masked location of the location.
*/
maskedLocation?: ParsedLocation<TSearchObj>
/**
* Whether to unmask the location on reload.
*/
unmaskOnReload?: boolean
/**
* @private
* @description The public href of the location.
* If a rewrite is applied, the `href` property will be the rewritten URL.
*/
publicHref: string
/**
* @private
* @description Whether the publicHref is external (different origin from rewrite).
*/
external: boolean
}
+213
View File
@@ -0,0 +1,213 @@
export type AssetCrossOrigin = 'anonymous' | 'use-credentials'
export type ScriptFormat = 'module' | 'iife'
export const DEV_STYLES_ATTR = 'data-tanstack-router-dev-styles'
export type AssetCrossOriginConfig =
| AssetCrossOrigin
| Partial<Record<'script' | 'stylesheet', AssetCrossOrigin>>
export type ManifestAssetLink =
| string
| {
href: string
crossOrigin?: AssetCrossOrigin
}
export function getAssetCrossOrigin(
assetCrossOrigin: AssetCrossOriginConfig | undefined,
kind: 'script' | 'stylesheet',
): AssetCrossOrigin | undefined {
if (!assetCrossOrigin) {
return undefined
}
if (typeof assetCrossOrigin === 'string') {
return assetCrossOrigin
}
return assetCrossOrigin[kind]
}
export function getManifestScriptFormat(
manifest: { scriptFormat?: ScriptFormat } | undefined,
): ScriptFormat {
return manifest?.scriptFormat ?? 'module'
}
export function getScriptPreloadAttrs(
manifest: { scriptFormat?: ScriptFormat } | undefined,
link: ManifestAssetLink,
assetCrossOrigin?: AssetCrossOriginConfig,
): {
rel: 'modulepreload' | 'preload'
as?: 'script'
href: string
crossOrigin?: AssetCrossOrigin
} {
const preloadLink = resolveManifestAssetLink(link)
const crossOrigin =
getAssetCrossOrigin(assetCrossOrigin, 'script') ?? preloadLink.crossOrigin
return {
...(getManifestScriptFormat(manifest) === 'iife'
? { rel: 'preload', as: 'script' }
: { rel: 'modulepreload' }),
href: preloadLink.href,
...(crossOrigin ? { crossOrigin } : {}),
}
}
export function resolveManifestAssetLink(link: ManifestAssetLink) {
if (typeof link === 'string') {
return { href: link, crossOrigin: undefined }
}
return link
}
export type Manifest = {
scriptFormat?: ScriptFormat
inlineStyle?: ManifestInlineCss
routes: Record<string, ManifestRoute>
}
export type ServerManifest = {
scriptFormat?: ScriptFormat
inlineCss?: ServerManifestInlineCss
routes: Record<string, ServerManifestRoute>
}
export type ServerManifestInlineCss = {
styles: Record<string, string>
templates?: Record<string, InlineCssTemplate>
}
export type InlineCssTemplate = {
strings: Array<string>
urls: Array<string>
}
export type ManifestRoute = {
filePath?: string
preloads?: Array<ManifestAssetLink>
scripts?: Array<ManifestScript>
css?: Array<ManifestCssLink>
}
export type ServerManifestRoute = ManifestRoute
export type ManifestRouteAssets = Pick<
ManifestRoute,
'preloads' | 'scripts' | 'css'
>
export type RouterManagedTitleTag = {
tag: 'title'
attrs?: Record<string, any>
children: string
}
export type RouterManagedMetaTag = {
tag: 'meta'
attrs?: Record<string, any>
children?: never
}
export type RouterManagedLinkTag = {
tag: 'link'
attrs?: Record<string, any>
children?: never
}
export type RouterManagedScriptTag = {
tag: 'script'
attrs?: Record<string, any>
children?: string
}
export type ManifestScript = Omit<RouterManagedScriptTag, 'tag'>
export type RouterManagedStyleTag = {
tag: 'style'
attrs?: Record<string, any>
children?: string
inlineCss?: true
}
export type RouterManagedTag =
| RouterManagedTitleTag
| RouterManagedMetaTag
| RouterManagedLinkTag
| RouterManagedScriptTag
| RouterManagedStyleTag
export function appendUniqueUserTags(
target: Array<RouterManagedTag>,
tags: Array<RouterManagedTag>,
) {
if (tags.length === 0) {
return
}
if (tags.length === 1) {
target.push(tags[0]!)
return
}
const seen = new Set<string>()
for (const tag of tags) {
const key = JSON.stringify(tag)
if (seen.has(key)) {
continue
}
seen.add(key)
target.push(tag)
}
}
export type ManifestCssLink =
| string
| {
href: string
crossOrigin?: AssetCrossOrigin
[DEV_STYLES_ATTR]?: true
}
export type ManifestInlineCss = {
attrs?: Record<string, any>
children?: string
}
export type RouterManagedInlineCssTag = RouterManagedStyleTag & {
inlineCss: true
}
export function getStylesheetHref(asset: ManifestCssLink) {
return resolveManifestCssLink(asset).href
}
export function resolveManifestCssLink(link: ManifestCssLink) {
if (typeof link === 'string') {
return { href: link, crossOrigin: undefined }
}
return link
}
export function createInlineCssStyleAsset(css: string): ManifestInlineCss {
return {
attrs: {
suppressHydrationWarning: true,
},
children: css,
}
}
export function createInlineCssPlaceholderAsset(): ManifestInlineCss {
return {
attrs: {
suppressHydrationWarning: true,
},
}
}
File diff suppressed because it is too large. Load diff
+41
View File
@@ -0,0 +1,41 @@
import type { RouteIds } from './routeInfo'
import type { RegisteredRouter } from './router'
export type NotFoundError = {
/**
@deprecated
Use `routeId: rootRouteId` instead
*/
global?: boolean
/**
@private
Do not use this. It's used internally to indicate a path matching error
*/
_global?: boolean
data?: any
throw?: boolean
routeId?: RouteIds<RegisteredRouter['routeTree']>
headers?: HeadersInit
}
/**
* Create a not-found error object recognized by TanStack Router.
*
* Throw this from loaders/actions to trigger the nearest `notFoundComponent`.
* Use `routeId` to target a specific route's not-found boundary. If `throw`
* is true, the error is thrown instead of returned.
*
* @param options Optional settings including `routeId`, `headers`, and `throw`.
* @returns A not-found error object that can be thrown or returned.
* @link https://tanstack.com/router/latest/docs/router/framework/react/api/router/notFoundFunction
*/
export function notFound(options: NotFoundError = {}) {
;(options as any).isNotFound = true
if (options.throw) throw options
return options
}
/** Determine if a value is a TanStack Router not-found error. */
export function isNotFound(obj: any): obj is NotFoundError {
return obj?.isNotFound === true
}
+306
View File
@@ -0,0 +1,306 @@
import { last } from './utils'
import {
SEGMENT_TYPE_OPTIONAL_PARAM,
SEGMENT_TYPE_PARAM,
SEGMENT_TYPE_WILDCARD,
} from './new-process-route-tree'
import type { SieveCache } from './sieve-cache'
import type { DynamicPathSegment } from './new-process-route-tree'
import type { AnyRoute } from './route'
/** Join path segments, cleaning duplicate slashes between parts. */
export function joinPaths(paths: Array<string | undefined>) {
return cleanPath(
paths
.filter((val) => {
return val !== undefined
})
.join('/'),
)
}
/** Remove repeated slashes from a path string. */
export function cleanPath(path: string) {
// remove double slashes
return path.replace(/\/{2,}/g, '/')
}
/** Trim leading slashes (except preserving root '/'). */
export function trimPathLeft(path: string) {
return path === '/' ? path : path.replace(/^\/+/, '')
}
/** Trim trailing slashes (except preserving root '/'). */
export function trimPathRight(path: string) {
const len = path.length
return len > 1 && path[len - 1] === '/' ? path.replace(/\/+$/, '') : path
}
/** Trim both leading and trailing slashes. */
export function trimPath(path: string) {
return trimPathRight(trimPathLeft(path))
}
/** Remove a trailing slash from value when appropriate for comparisons. */
export function removeTrailingSlash(value: string, basepath: string): string {
if (value?.endsWith('/') && value !== '/' && value !== `${basepath}/`) {
return value.slice(0, -1)
}
return value
}
// intended to only compare path name
// see the usage in the isActive under useLinkProps
// /sample/path1 = /sample/path1/
// /sample/path1/some <> /sample/path1
/**
* Compare two pathnames for exact equality after normalizing trailing slashes
* relative to the provided `basepath`.
*/
export function exactPathTest(
pathName1: string,
pathName2: string,
basepath: string,
): boolean {
return (
removeTrailingSlash(pathName1, basepath) ===
removeTrailingSlash(pathName2, basepath)
)
}
// When resolving relative paths, we treat all paths as if they are trailing slash
// documents. All trailing slashes are removed after the path is resolved.
// Here are a few examples:
//
// /a/b/c + ./d = /a/b/c/d
// /a/b/c + ../d = /a/b/d
// /a/b/c + ./d/ = /a/b/c/d
// /a/b/c + ../d/ = /a/b/d
// /a/b/c + ./ = /a/b/c
//
// Absolute paths that start with `/` short circuit the resolution process to the root
// path.
//
// Here are some examples:
//
// /a/b/c + /d = /d
// /a/b/c + /d/ = /d
// /a/b/c + / = /
//
// Non-.-prefixed paths are still treated as relative paths, resolved like `./`
//
// Here are some examples:
//
// /a/b/c + d = /a/b/c/d
// /a/b/c + d/ = /a/b/c/d
// /a/b/c + d/e = /a/b/c/d/e
/**
* Resolve a destination path against a base, honoring trailing-slash policy
* and supporting relative segments (`.`/`..`) and absolute `to` values.
*
* Internal: parameters are positional so the router's hot callers pass no
* options object.
*/
export function resolvePath(
base: string,
to: string,
trailingSlash: 'always' | 'never' | 'preserve' = 'never',
cache?: SieveCache<string, string>,
) {
if (to.includes('//')) {
to = cleanPath(to)
}
if (to.startsWith('/')) {
if (to.length === 1 || trailingSlash === 'preserve') {
return to
}
if (trailingSlash === 'always') {
return to.endsWith('/') ? to : `${to}/`
}
return to.endsWith('/') ? to.slice(0, -1) : to
}
const isBase = to === '.'
let key
if (cache) {
// `trailingSlash` is static per router, so it doesn't need to be part of the cache key
key = isBase ? base : base + '\0' + to
const cached = cache.get(key)
if (cached) return cached
}
let baseSegments: Array<string>
if (isBase) {
baseSegments = base.split('/')
} else {
if (base.includes('//')) {
base = cleanPath(base)
}
baseSegments = base.split('/')
while (baseSegments.length > 1 && last(baseSegments) === '') {
baseSegments.pop()
}
const toSegments = to.split('/')
for (let index = 0, length = toSegments.length; index < length; index++) {
const value = toSegments[index]!
if (value === '') {
if (!index) {
// Leading slash
baseSegments = [value]
} else if (index === length - 1) {
// Trailing Slash
baseSegments.push(value)
} else {
// ignore inter-slashes
}
} else if (value === '..') {
if (baseSegments.length > 1) {
baseSegments.pop()
} else {
baseSegments = ['']
}
} else if (value === '.') {
// ignore
} else {
baseSegments.push(value)
}
}
}
if (baseSegments.length > 1) {
if (last(baseSegments) === '') {
if (trailingSlash === 'never') {
baseSegments.pop()
}
} else if (trailingSlash === 'always') {
baseSegments.push('')
}
}
const joined = baseSegments.join('/')
const result = (isBase ? cleanPath(joined) : joined) || '/'
if (key && cache) cache.set(key, result)
return result
}
/**
* Create a pre-compiled decode config from allowed characters.
* Created once for the router's fixed encoding configuration.
*/
export function compileDecodeCharMap(
pathParamsAllowedCharacters: ReadonlyArray<string>,
) {
const charMap = new Map(
pathParamsAllowedCharacters.map((char) => [encodeURIComponent(char), char]),
)
// Encoded keys contain no '|', and only these four regexp metacharacters.
const regex = new RegExp(
[...charMap.keys()].join('|').replace(/[.*()]/g, '\\$&'),
'g',
)
return (encoded: string) =>
encoded.replace(regex, (match) => charMap.get(match) ?? match)
}
export type InterpolationSegment = string | DynamicPathSegment
export type RouteInterpolation = Array<InterpolationSegment> & {
names?: Array<string>
}
export function getRouteSegments(route: AnyRoute) {
return route._interpolation
}
/** A splat is missing when it has no value; `0` and `false` are stringified like any other param. */
function isMissingSplat(value: unknown): boolean {
return value == null || value === ''
}
/** Devtools checks navigation availability separately from the hot formatter. */
export function hasMissingPathParams(
segments: RouteInterpolation,
params: Record<string, unknown>,
): boolean {
return segments.some((part) => {
if (typeof part === 'string') {
return false
}
const [kind, key] = part
return kind === SEGMENT_TYPE_WILDCARD
? isMissingSplat(params[key])
: kind === SEGMENT_TYPE_PARAM && !(key in params)
})
}
function encodeParam(
key: string,
value: unknown,
decoder: ((encoded: string) => string) | undefined,
): string {
if (typeof value !== 'string') {
return '' + (value ?? undefined)
}
const splat = key === '_splat'
// Early return if the splat contains only URL-safe characters.
if (splat && (!value || /^[a-zA-Z0-9\-._~!/]*$/.test(value))) {
return value
}
let encoded = encodeURIComponent(value)
if (splat) {
// Splats preserve '/', but still encode spaces, '+', '?' and '#'.
// Restore separators before allowed characters can decode a literal '%2F'.
encoded = encoded.replaceAll('%2F', '/')
}
return decoder ? decoder(encoded) : encoded
}
/** Substitute current values into parsed segments, optionally collecting raw params. */
export function interpolatePath(
path: string,
segments: RouteInterpolation,
params: Record<string, unknown>,
decoder?: (encoded: string) => string,
usedParams?: Record<string, unknown>,
): string {
// One parsed template serves both trailing-slash variants.
const trailingSlash = path.endsWith('/') ? '/' : ''
let joined = ''
for (const part of segments) {
if (typeof part === 'string') {
joined += part
continue
}
const [kind, key, prefix, rawSuffix] = part
const splat = kind === SEGMENT_TYPE_WILDCARD
const suffix =
splat && rawSuffix !== undefined ? rawSuffix + trailingSlash : rawSuffix
let paramValue = params[key]
// An omitted optional contributes neither a segment nor used-param metadata.
if (kind === SEGMENT_TYPE_OPTIONAL_PARAM && paramValue == null) {
continue
}
if (usedParams) {
// Match identity needs current raw values, never data retained from another call.
usedParams[key] = paramValue
// TODO: Deprecate *
if (splat) {
usedParams['*'] = paramValue
}
}
if (splat && isMissingSplat(paramValue)) {
// A missing wildcard keeps its affixes, but omits a bare segment.
if (prefix === '/' && !suffix) {
continue
}
paramValue = ''
}
joined += prefix + encodeParam(key, paramValue, decoder) + (suffix || '')
}
return joined + trailingSlash || '/'
}
+81
View File
@@ -0,0 +1,81 @@
/**
* Program is a reimplementation of the `qss` package:
* Copyright (c) Luke Edwards luke.edwards05@gmail.com, MIT License
* https://github.com/lukeed/qss/blob/master/license.md
*
* This reimplementation uses modern browser APIs
* (namely URLSearchParams) and TypeScript while still
* maintaining the original functionality and interface.
*
* Update: this implementation has also been mangled to
* fit exactly our use-case (single value per key in encoding).
*/
/**
* Encodes an object into a query string.
* @param obj - The object to encode into a query string.
* @param stringify - An optional custom stringify function.
* @returns The encoded query string.
* @example
* ```
* // Example input: encode({ token: 'foo', key: 'value' })
* // Expected output: "token=foo&key=value"
* ```
*/
export function encode(
obj: Record<string, any>,
stringify: (value: any) => string = String,
): string {
let result: URLSearchParams | undefined
for (const key in obj) {
const val = obj[key]
if (val !== undefined) {
;(result ||= new URLSearchParams()).set(key, stringify(val))
}
}
return result ? result.toString() : ''
}
/**
* Converts a string value to its appropriate type (string, number, boolean).
* @param mix - The string value to convert.
* @returns The converted value.
* @example
* // Example input: toValue("123")
* // Expected output: 123
*/
function toValue(str: unknown) {
if (!str) return ''
if (str === 'false') return false
if (str === 'true') return true
return +str * 0 === 0 && +str + '' === str ? +str : str
}
/**
* Decodes a query string into an object.
* @param str - The query string to decode.
* @returns The decoded key-value pairs in an object format.
* @example
* // Example input: decode("token=foo&key=value")
* // Expected output: { "token": "foo", "key": "value" }
*/
export function decode(str: any): any {
const searchParams = new URLSearchParams(str)
const result: Record<string, unknown> = Object.create(null)
for (const [key, value] of searchParams.entries()) {
const previousValue = result[key]
if (previousValue == null) {
result[key] = toValue(value)
} else if (Array.isArray(previousValue)) {
previousValue.push(toValue(value))
} else {
result[key] = [previousValue, toValue(value)]
}
}
return result
}
+152
View File
@@ -0,0 +1,152 @@
import type { NavigateOptions } from './link'
import type { AnyRouter, RegisteredRouter } from './router'
export type AnyRedirect = Redirect<any, any, any, any, any>
/**
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType)
*/
export type Redirect<
TRouter extends AnyRouter = RegisteredRouter,
TFrom extends string = string,
TTo extends string | undefined = undefined,
TMaskFrom extends string = TFrom,
TMaskTo extends string = '.',
> = Response & {
options: NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>
}
export type RedirectOptions<
TRouter extends AnyRouter = RegisteredRouter,
TFrom extends string = string,
TTo extends string | undefined = undefined,
TMaskFrom extends string = TFrom,
TMaskTo extends string = '.',
> = {
href?: string
/**
* @deprecated Use `statusCode` instead
**/
code?: number
/**
* The HTTP status code to use when redirecting.
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType#statuscode-property)
*/
statusCode?: number
/**
* If provided, will throw the redirect object instead of returning it. This can be useful in places where `throwing` in a function might cause it to have a return type of `never`. In that case, you can use `redirect({ throw: true })` to throw the redirect object instead of returning it.
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType#throw-property)
*/
throw?: any
/**
* The HTTP headers to use when redirecting.
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType#headers-property)
*/
headers?: HeadersInit
} & NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>
export type ResolvedRedirect<
TRouter extends AnyRouter = RegisteredRouter,
TFrom extends string = string,
TTo extends string = '',
TMaskFrom extends string = TFrom,
TMaskTo extends string = '',
> = Redirect<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>
/**
* Options for route-bound redirect, where 'from' is automatically set.
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType)
*/
export type RedirectOptionsRoute<
TDefaultFrom extends string = string,
TRouter extends AnyRouter = RegisteredRouter,
TTo extends string | undefined = undefined,
TMaskTo extends string = '',
> = Omit<
RedirectOptions<TRouter, TDefaultFrom, TTo, TDefaultFrom, TMaskTo>,
'from'
>
/**
* A redirect function bound to a specific route, with 'from' pre-set to the route's fullPath.
* This enables relative redirects like `Route.redirect({ to: './overview' })`.
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType)
*/
export interface RedirectFnRoute<in out TDefaultFrom extends string = string> {
<
TRouter extends AnyRouter = RegisteredRouter,
const TTo extends string | undefined = undefined,
const TMaskTo extends string = '',
>(
opts: RedirectOptionsRoute<TDefaultFrom, TRouter, TTo, TMaskTo>,
): Redirect<TRouter, TDefaultFrom, TTo, TDefaultFrom, TMaskTo>
}
/**
* Create a redirect Response understood by TanStack Router.
*
* Use from route `loader`/`beforeLoad` or server functions to trigger a
* navigation. If `throw: true` is set, the redirect is thrown instead of
* returned. External `href` values are classified as full-document
* navigations when the router resolves the redirect.
*
* @param opts Options for the redirect. Common fields:
* - `href`: absolute URL for external redirects.
* - `statusCode`: HTTP status code to use (defaults to 307).
* - `headers`: additional headers to include on the Response.
* - Standard navigation options like `to`, `params`, `search`, `replace`,
* and `reloadDocument` for internal redirects.
* @returns A Response augmented with router navigation options.
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction
*/
export function redirect<
TRouter extends AnyRouter = RegisteredRouter,
const TTo extends string | undefined = '.',
const TFrom extends string = string,
const TMaskFrom extends string = TFrom,
const TMaskTo extends string = '',
>(
opts: RedirectOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
): Redirect<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> {
opts.statusCode = opts.statusCode || opts.code || 307
const headers = new Headers(opts.headers)
if (opts.href && headers.get('Location') === null) {
headers.set('Location', opts.href)
}
const response = new Response(null, {
status: opts.statusCode,
headers,
})
;(response as Redirect<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>).options =
opts
if (opts.throw) {
throw response
}
return response as Redirect<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>
}
/** Check whether a value is a TanStack Router redirect Response. */
export function isRedirect(obj: any): obj is AnyRedirect {
return obj instanceof Response && !!(obj as any).options
}
/** True if value is a redirect with a resolved `href` location. */
export function isResolvedRedirect(
obj: any,
): obj is AnyRedirect & { options: { href: string } } {
return isRedirect(obj) && !!obj.options.href
}
/** Parse a serialized redirect object back into a redirect Response. */
export function parseRedirect(obj: any) {
if (obj !== null && typeof obj === 'object' && obj.isSerializedRedirect) {
return redirect(obj)
}
return undefined
}
+97
View File
@@ -0,0 +1,97 @@
import { cleanPath, trimPath } from './path'
import type { LocationRewrite } from './router'
/** Compose multiple rewrite pairs into a single in/out rewrite. */
export function composeRewrites(rewrites: Array<LocationRewrite>) {
return {
input: ({ url }) => {
for (const rewrite of rewrites) {
url = executeRewriteInput(rewrite, url)
}
return url
},
output: ({ url }) => {
for (let i = rewrites.length - 1; i >= 0; i--) {
url = executeRewriteOutput(rewrites[i], url)
}
return url
},
} satisfies LocationRewrite
}
/** Create a rewrite pair that strips/adds a basepath on input/output. */
export function rewriteBasepath(
basepath: string,
caseSensitive?: boolean,
rewrite?: LocationRewrite,
) {
const trimmedBasepath = trimPath(basepath)
const normalizedBasepath = `/${trimmedBasepath}`
const checkBasepath = caseSensitive
? normalizedBasepath
: normalizedBasepath.toLowerCase()
const checkBasepathWithSlash = `${checkBasepath}/`
const basepathRewrite = {
input: ({ url }) => {
const pathname = caseSensitive ? url.pathname : url.pathname.toLowerCase()
// Handle exact basepath match (e.g., /my-app -> /)
if (pathname === checkBasepath) {
url.pathname = '/'
} else if (pathname.startsWith(checkBasepathWithSlash)) {
// Handle basepath with trailing content (e.g., /my-app/users -> /users)
url.pathname = url.pathname.slice(normalizedBasepath.length)
}
return url
},
output: ({ url }) => {
// `url.pathname` always starts with "/", so only slashes already inside
// it can repeat; cleanPath keeps the joinPaths normalization.
url.pathname = cleanPath(`/${trimmedBasepath}${url.pathname}`)
return url
},
} satisfies LocationRewrite
// Strip the basepath before custom input and restore it after custom output.
return rewrite
? ({
input: ({ url }) =>
executeRewriteInput(rewrite, basepathRewrite.input({ url })),
output: ({ url }) =>
basepathRewrite.output({ url: executeRewriteOutput(rewrite, url) }),
} satisfies LocationRewrite)
: basepathRewrite
}
/** Execute a location input rewrite if provided. */
export function executeRewriteInput(
rewrite: LocationRewrite | undefined,
url: URL,
): URL {
const res = rewrite?.input?.({ url })
if (res) {
if (typeof res === 'string') {
return new URL(res)
} else if (res instanceof URL) {
return res
}
}
return url
}
/** Execute a location output rewrite if provided. */
export function executeRewriteOutput(
rewrite: LocationRewrite | undefined,
url: URL,
): URL {
const res = rewrite?.output?.({ url })
if (res) {
if (typeof res === 'string') {
return new URL(res)
} else if (res instanceof URL) {
return res
}
}
return url
}
+3
View File
@@ -0,0 +1,3 @@
/** Stable identifier used for the root route in a route tree. */
export const rootRouteId = '__root__'
export type RootRouteId = typeof rootRouteId
File diff suppressed because it is too large. Load diff
+235
View File
@@ -0,0 +1,235 @@
import type { InferFileRouteTypes } from './fileRoute'
import type { AddTrailingSlash, RemoveTrailingSlashes } from './link'
import type { AnyRoute } from './route'
import type { AnyRouter, TrailingSlashOption } from './router'
import type { PartialMergeAll } from './utils'
export type ParseRoute<TRouteTree, TAcc = TRouteTree> = TRouteTree extends {
types: { children: infer TChildren }
}
? unknown extends TChildren
? TAcc
: TChildren extends ReadonlyArray<any>
? ParseRoute<TChildren[number], TAcc | TChildren[number]>
: ParseRoute<
TChildren[keyof TChildren],
TAcc | TChildren[keyof TChildren]
>
: TAcc
export type ParseRouteWithoutBranches<TRouteTree> =
ParseRoute<TRouteTree> extends infer TRoute extends AnyRoute
? TRoute extends any
? unknown extends TRoute['types']['children']
? TRoute
: TRoute['types']['children'] extends ReadonlyArray<any>
? '/' extends TRoute['types']['children'][number]['path']
? never
: TRoute
: '/' extends TRoute['types']['children'][keyof TRoute['types']['children']]['path']
? never
: TRoute
: never
: never
export type CodeRoutesById<TRouteTree extends AnyRoute> =
ParseRoute<TRouteTree> extends infer TRoutes extends AnyRoute
? {
[K in TRoutes as K['id']]: K
}
: never
export type RoutesById<TRouteTree extends AnyRoute> =
InferFileRouteTypes<TRouteTree> extends never
? CodeRoutesById<TRouteTree>
: InferFileRouteTypes<TRouteTree>['fileRoutesById']
export type RouteById<TRouteTree extends AnyRoute, TId> = Extract<
RoutesById<TRouteTree>[TId & keyof RoutesById<TRouteTree>],
AnyRoute
>
export type CodeRouteIds<TRouteTree extends AnyRoute> =
ParseRoute<TRouteTree> extends infer TRoutes extends AnyRoute
? TRoutes['id']
: never
export type RouteIds<TRouteTree extends AnyRoute> =
InferFileRouteTypes<TRouteTree> extends never
? CodeRouteIds<TRouteTree>
: InferFileRouteTypes<TRouteTree>['id']
export type ParentPath<TRouter extends AnyRouter> =
TrailingSlashOptionByRouter<TRouter> extends 'always'
? '../'
: TrailingSlashOptionByRouter<TRouter> extends 'never'
? '..'
: '../' | '..'
export type CurrentPath<TRouter extends AnyRouter> =
TrailingSlashOptionByRouter<TRouter> extends 'always'
? './'
: TrailingSlashOptionByRouter<TRouter> extends 'never'
? '.'
: './' | '.'
export type ToPath<TRouter extends AnyRouter, TTo extends string> =
TrailingSlashOptionByRouter<TRouter> extends 'always'
? AddTrailingSlash<TTo>
: TrailingSlashOptionByRouter<TRouter> extends 'never'
? RemoveTrailingSlashes<TTo>
: AddTrailingSlash<TTo> | RemoveTrailingSlashes<TTo>
export type CatchAllPaths<TRouter extends AnyRouter> =
| CurrentPath<TRouter>
| ParentPath<TRouter>
export type CodeRoutesByPath<TRouteTree extends AnyRoute> =
ParseRoute<TRouteTree> extends infer TRoutes extends AnyRoute
? {
[K in TRoutes as K['fullPath']]: K
}
: never
export type RoutesByPath<TRouteTree extends AnyRoute> =
InferFileRouteTypes<TRouteTree> extends never
? CodeRoutesByPath<TRouteTree>
: InferFileRouteTypes<TRouteTree>['fileRoutesByFullPath']
export type RouteByPath<TRouteTree extends AnyRoute, TPath> = Extract<
RoutesByPath<TRouteTree>[TPath & keyof RoutesByPath<TRouteTree>],
AnyRoute
>
export type CodeRoutePaths<TRouteTree extends AnyRoute> =
ParseRoute<TRouteTree> extends infer TRoutes extends AnyRoute
? TRoutes['fullPath']
: never
export type RoutePaths<TRouteTree extends AnyRoute> = unknown extends TRouteTree
? string
:
| (InferFileRouteTypes<TRouteTree> extends never
? CodeRoutePaths<TRouteTree>
: InferFileRouteTypes<TRouteTree>['fullPaths'])
| '/'
export type RouteToPathAlwaysTrailingSlash<TRoute extends AnyRoute> =
TRoute['path'] extends '/'
? TRoute['fullPath']
: TRoute['fullPath'] extends '/'
? TRoute['fullPath']
: `${TRoute['fullPath']}/`
export type RouteToPathNeverTrailingSlash<TRoute extends AnyRoute> =
TRoute['path'] extends '/'
? TRoute['fullPath'] extends '/'
? TRoute['fullPath']
: RemoveTrailingSlashes<TRoute['fullPath']>
: TRoute['fullPath']
export type RouteToPathPreserveTrailingSlash<TRoute extends AnyRoute> =
| RouteToPathNeverTrailingSlash<TRoute>
| RouteToPathAlwaysTrailingSlash<TRoute>
export type RouteToPathByTrailingSlashOption<TRoute extends AnyRoute> = {
always: RouteToPathAlwaysTrailingSlash<TRoute>
preserve: RouteToPathPreserveTrailingSlash<TRoute>
never: RouteToPathNeverTrailingSlash<TRoute>
}
export type TrailingSlashOptionByRouter<TRouter extends AnyRouter> =
TrailingSlashOption extends TRouter['options']['trailingSlash']
? 'never'
: NonNullable<TRouter['options']['trailingSlash']>
export type RouteToByRouter<
TRouter extends AnyRouter,
TRoute extends AnyRoute,
> = RouteToPathByTrailingSlashOption<TRoute>[TrailingSlashOptionByRouter<TRouter>]
export type CodeRouteToPath<TRouter extends AnyRouter> =
ParseRouteWithoutBranches<TRouter['routeTree']> extends infer TRoute extends
AnyRoute
? TRoute extends any
? RouteToByRouter<TRouter, TRoute>
: never
: never
export type FileRouteToPath<
TRouter extends AnyRouter,
TTo = InferFileRouteTypes<TRouter['routeTree']>['to'],
TTrailingSlashOption = TrailingSlashOptionByRouter<TRouter>,
> = 'never' extends TTrailingSlashOption
? TTo
: 'always' extends TTrailingSlashOption
? AddTrailingSlash<TTo>
: TTo | AddTrailingSlash<TTo>
export type RouteToPath<TRouter extends AnyRouter> = unknown extends TRouter
? string
: InferFileRouteTypes<TRouter['routeTree']> extends never
? CodeRouteToPath<TRouter>
: FileRouteToPath<TRouter>
export type CodeRoutesByToPath<TRouter extends AnyRouter> =
ParseRouteWithoutBranches<TRouter['routeTree']> extends infer TRoutes extends
AnyRoute
? {
[TRoute in TRoutes as RouteToByRouter<TRouter, TRoute>]: TRoute
}
: never
export type RoutesByToPath<TRouter extends AnyRouter> =
InferFileRouteTypes<TRouter['routeTree']> extends never
? CodeRoutesByToPath<TRouter>
: InferFileRouteTypes<TRouter['routeTree']>['fileRoutesByTo']
export type CodeRouteByToPath<TRouter extends AnyRouter, TTo> = Extract<
RoutesByToPath<TRouter>[TTo & keyof RoutesByToPath<TRouter>],
AnyRoute
>
export type FileRouteByToPath<TRouter extends AnyRouter, TTo> =
'never' extends TrailingSlashOptionByRouter<TRouter>
? CodeRouteByToPath<TRouter, TTo>
: 'always' extends TrailingSlashOptionByRouter<TRouter>
? TTo extends '/'
? CodeRouteByToPath<TRouter, TTo>
: TTo extends `${infer TPath}/`
? CodeRouteByToPath<TRouter, TPath>
: never
: CodeRouteByToPath<
TRouter,
TTo extends '/' ? TTo : RemoveTrailingSlashes<TTo>
>
export type RouteByToPath<TRouter extends AnyRouter, TTo> =
InferFileRouteTypes<TRouter['routeTree']> extends never
? CodeRouteByToPath<TRouter, TTo>
: FileRouteByToPath<TRouter, TTo>
export type FullSearchSchema<TRouteTree extends AnyRoute> =
ParseRoute<TRouteTree> extends infer TRoutes extends AnyRoute
? PartialMergeAll<TRoutes['types']['fullSearchSchema']>
: never
export type FullSearchSchemaInput<TRouteTree extends AnyRoute> =
ParseRoute<TRouteTree> extends infer TRoutes extends AnyRoute
? PartialMergeAll<TRoutes['types']['fullSearchSchemaInput']>
: never
export type AllParams<TRouteTree extends AnyRoute> =
ParseRoute<TRouteTree> extends infer TRoutes extends AnyRoute
? PartialMergeAll<TRoutes['types']['allParams']>
: never
export type AllContext<TRouteTree extends AnyRoute> =
ParseRoute<TRouteTree> extends infer TRoutes extends AnyRoute
? PartialMergeAll<TRoutes['types']['allContext']>
: never
export type AllLoaderData<TRouteTree extends AnyRoute> =
ParseRoute<TRouteTree> extends infer TRoutes extends AnyRoute
? PartialMergeAll<TRoutes['types']['loaderData']>
: never
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,53 @@
export default function (storageKey: string, key?: string) {
let byKey
try {
byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}')
} catch {
return
}
const elementEntries = byKey?.[key || history.state?.__TSR_key]
let windowRestored = false
for (const elementSelector in elementEntries) {
const entry = elementEntries[elementSelector]
const scrollX = entry?.scrollX
const scrollY = entry?.scrollY
if (Number.isFinite(scrollX) && Number.isFinite(scrollY)) {
if (elementSelector === 'window') {
scrollTo(scrollX, scrollY)
windowRestored = true
} else if (elementSelector) {
try {
const element = document.querySelector(elementSelector)
if (element) {
element.scrollLeft = scrollX
element.scrollTop = scrollY
}
} catch {}
}
}
}
if (windowRestored) return
const hash = location.hash.slice(1)
if (hash) {
const hashScrollIntoViewOptions =
history.state?.__hashScrollIntoViewOptions ?? true
if (hashScrollIntoViewOptions) {
const el = document.getElementById(hash)
if (el) {
el.scrollIntoView(hashScrollIntoViewOptions)
}
}
return
}
scrollTo(0, 0)
}
@@ -0,0 +1,5 @@
import type { AnyRouter } from '../router'
export function getScrollRestorationScriptForRouter(_router: AnyRouter) {
return null
}
@@ -0,0 +1,43 @@
import minifiedScrollRestorationScript from '../scroll-restoration-inline?script-string'
import {
defaultGetScrollRestorationKey,
storageKey,
} from '../scroll-restoration'
import { escapeHtml } from '../utils'
import type { AnyRouter } from '../router'
const defaultInlineScrollRestorationScript = `(${minifiedScrollRestorationScript})(${escapeHtml(
JSON.stringify(storageKey),
)})`
function getScrollRestorationScript(key?: string) {
if (key === undefined) {
return defaultInlineScrollRestorationScript
}
return `(${minifiedScrollRestorationScript})(${escapeHtml(JSON.stringify(storageKey))},${escapeHtml(JSON.stringify(key))})`
}
export function getScrollRestorationScriptForRouter(router: AnyRouter) {
if (
typeof router.options.scrollRestoration === 'function' &&
!router.options.scrollRestoration({ location: router.latestLocation })
) {
return null
}
const getKey = router.options.getScrollRestorationKey
if (!getKey) {
return defaultInlineScrollRestorationScript
}
const location = router.latestLocation
const userKey = getKey(location)
const defaultKey = defaultGetScrollRestorationKey(location)
if (userKey === defaultKey) {
return defaultInlineScrollRestorationScript
}
return getScrollRestorationScript(userKey)
}
+367
View File
@@ -0,0 +1,367 @@
import { isServer } from '@tanstack/router-core/isServer'
import type { AnyRouter } from './router'
import type { ParsedLocation } from './location'
export type ScrollRestorationEntry = { scrollX: number; scrollY: number }
type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>
type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>
export type ScrollRestorationOptions = {
getKey?: (location: ParsedLocation) => string
scrollBehavior?: ScrollToOptions['behavior']
}
function getSafeSessionStorage() {
try {
// Accessing sessionStorage itself can throw SecurityError in locked-down
// contexts, e.g. sandboxed/opaque origins or blocked storage policies.
return sessionStorage
} catch {
return
}
}
// SessionStorage key used to store scroll positions across navigations.
export const storageKey = 'tsr-scroll-restoration-v1_3'
const safeSessionStorage = getSafeSessionStorage()
function createScrollRestorationCache() {
try {
return JSON.parse(
safeSessionStorage?.getItem(storageKey) || '{}',
) as ScrollRestorationByKey
} catch {
// ignore invalid session storage payloads
return {}
}
}
function persistScrollRestorationCache() {
try {
safeSessionStorage?.setItem(
storageKey,
JSON.stringify(scrollRestorationCache),
)
} catch {
if (process.env.NODE_ENV !== 'production') {
console.warn(
'[ts-router] Could not persist scroll restoration state to sessionStorage.',
)
}
}
}
const scrollRestorationCache = /* @__PURE__ */ createScrollRestorationCache()
const scrollRestorationIdAttribute = 'data-scroll-restoration-id'
/**
* The default `getKey` function for `useScrollRestoration`.
* It returns the `key` from the location state or the `href` of the location.
*
* The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.
*/
export const defaultGetScrollRestorationKey = (location: ParsedLocation) => {
return location.state.__TSR_key! || location.href
}
function getScrollRestorationSelector(element: Element): string {
const attrId = element.getAttribute(scrollRestorationIdAttribute)
if (attrId) {
return `[${scrollRestorationIdAttribute}="${attrId}"]`
}
let selector = ''
let el: any = element
let parent: HTMLElement
while ((parent = el.parentNode)) {
let index = 1
let sibling = el
while ((sibling = sibling.previousElementSibling)) {
index++
}
const part = `${el.localName}:nth-child(${index})`
selector = selector ? `${part} > ${selector}` : part
el = parent
}
return selector
}
export function getElementScrollRestorationEntry(
router: AnyRouter,
options: (
| {
id: string
getElement?: () => Window | Element | undefined | null
}
| {
id?: string
getElement: () => Window | Element | undefined | null
}
) & {
getKey?: (location: ParsedLocation) => string
},
): ScrollRestorationEntry | undefined {
const getKey = options.getKey || defaultGetScrollRestorationKey
const restoreKey = getKey(router.latestLocation)
const entries = scrollRestorationCache[restoreKey]
if (!entries) {
return
}
if (options.id) {
return entries[`[${scrollRestorationIdAttribute}="${options.id}"]`]
}
const element = options.getElement?.()
if (!element) {
return
}
return entries[
element === window
? windowScrollTarget
: getScrollRestorationSelector(element as Element)
]
}
let ignoreScroll = false
const windowScrollTarget = 'window'
function getElement(selector: string | (() => Element | null | undefined)) {
try {
return typeof selector === 'function'
? selector()
: document.querySelector(selector)
} catch {}
return
}
function getScrollToTopElements(
scrollToTopSelectors: NonNullable<
AnyRouter['options']['scrollToTopSelectors']
>,
) {
const elements = new Set<Element>()
for (const selector of scrollToTopSelectors) {
if (selector === windowScrollTarget) {
continue
}
const element = getElement(selector)
if (element) {
elements.add(element)
}
}
return elements
}
export function setupScrollRestoration(router: AnyRouter, force?: boolean) {
// Keep hash/top scrolling active even when sessionStorage is unavailable.
const shouldSetupScrollRestoration = force ?? router.options.scrollRestoration
const scroll = router._scroll
if (shouldSetupScrollRestoration) {
scroll.restoring = true
}
if (isServer ?? router.isServer) {
return
}
const getKey =
router.options.getScrollRestorationKey || defaultGetScrollRestorationKey
const trackedScrollTargets = new Set<Document | Element>()
// Snapshot the current page's tracked scroll targets before navigation or unload.
const snapshotCurrentScrollTargets = (restoreKey: string) => {
const keyEntry = (scrollRestorationCache[restoreKey] ||=
{} as ScrollRestorationByElement)
for (const target of trackedScrollTargets) {
if (target === document) {
keyEntry[windowScrollTarget] = { scrollX, scrollY }
} else if ((target as Element).isConnected) {
keyEntry[getScrollRestorationSelector(target as Element)] = {
scrollX: (target as Element).scrollLeft,
scrollY: (target as Element).scrollTop,
}
}
}
}
if (shouldSetupScrollRestoration && !scroll.restoration) {
scroll.restoration = true
ignoreScroll = false
history.scrollRestoration = 'manual'
document.addEventListener(
'scroll',
(event) => {
if (ignoreScroll) {
return
}
trackedScrollTargets.add(event.target as Document | Element)
},
true,
)
router.subscribe('onBeforeLoad', (event) => {
if (event.fromLocation) {
snapshotCurrentScrollTargets(getKey(event.fromLocation))
}
trackedScrollTargets.clear()
})
addEventListener('pagehide', () => {
snapshotCurrentScrollTargets(
getKey(
router.stores.resolvedLocation.get() ?? router.stores.location.get(),
),
)
persistScrollRestorationCache()
})
}
if (scroll.reset) {
return
}
scroll.reset = true
// Restore destination scroll after the new route has rendered.
router.subscribe('onRendered', (event) => {
const behavior = router.options.scrollRestorationBehavior
const scrollToTopSelectors = router.options.scrollToTopSelectors
const shouldResetScroll = scroll.next
const hashNavigation = scroll.hash
let scrollToTopElements: Set<Element> | undefined
trackedScrollTargets.clear()
scroll.next = true
scroll.hash = false
if (
typeof router.options.scrollRestoration === 'function' &&
!router.options.scrollRestoration({ location: router.latestLocation })
) {
return
}
const cacheKey = getKey(event.toLocation)
const fromCacheKey = event.fromLocation && getKey(event.fromLocation)
if (scroll.restoring && fromCacheKey && fromCacheKey !== cacheKey) {
const fromElementEntries = scrollRestorationCache[fromCacheKey]
if (fromElementEntries) {
let toElementEntries = scrollRestorationCache[cacheKey]
for (const elementSelector in fromElementEntries) {
if (elementSelector === windowScrollTarget) {
if (shouldResetScroll) {
continue
}
} else {
const element = getElement(elementSelector)
if (!element) {
continue
}
if (shouldResetScroll && scrollToTopSelectors) {
scrollToTopElements ??=
getScrollToTopElements(scrollToTopSelectors)
if (scrollToTopElements.has(element)) {
continue
}
}
}
if (!toElementEntries) {
toElementEntries = scrollRestorationCache[cacheKey] =
{} as ScrollRestorationByElement
}
toElementEntries[elementSelector] ??=
fromElementEntries[elementSelector]!
}
}
}
ignoreScroll = true
try {
const hash = event.toLocation.hash
const hashScrollIntoViewOptions =
event.toLocation.state.__hashScrollIntoViewOptions ?? true
let windowRestored = false
if (shouldResetScroll) {
if (!hash && scrollToTopSelectors) {
scrollToTopElements ??= getScrollToTopElements(scrollToTopSelectors)
}
const skipWindowRestore =
hash && hashScrollIntoViewOptions && hashNavigation
const elementEntries = scroll.restoring
? scrollRestorationCache[cacheKey]
: undefined
if (elementEntries) {
for (const elementSelector in elementEntries) {
const { scrollX, scrollY } = elementEntries[elementSelector]!
if (elementSelector === windowScrollTarget) {
if (skipWindowRestore) {
continue
}
scrollTo({
top: scrollY,
left: scrollX,
behavior,
})
windowRestored = true
} else {
const element = getElement(elementSelector)
if (element) {
element.scrollLeft = scrollX
element.scrollTop = scrollY
scrollToTopElements?.delete(element)
}
}
}
}
if (!hash) {
const scrollOptions = {
top: 0,
left: 0,
behavior,
}
if (!windowRestored) {
scrollTo(scrollOptions)
}
if (scrollToTopElements) {
for (const element of scrollToTopElements) {
element.scrollTo(scrollOptions)
}
}
}
}
if (!windowRestored && hash && hashScrollIntoViewOptions) {
document.getElementById(hash)?.scrollIntoView(hashScrollIntoViewOptions)
}
} finally {
ignoreScroll = false
}
})
}
+141
View File
@@ -0,0 +1,141 @@
import { deepEqual, hasOwn } from './utils'
import type { NoInfer, PickOptional } from './utils'
import type {
SearchMiddleware,
SearchMiddlewareContext,
SearchMiddlewareMeta,
} from './route'
import type { IsRequiredParams } from './link'
type SearchMiddlewareNextWithMeta<TSearchSchema> = (
newSearch: TSearchSchema,
collectMeta: true,
) => { search: TSearchSchema; meta: SearchMiddlewareMeta }
/**
* Retain specified search params across navigations.
*
* If `keys` is `true`, retain all current params. Otherwise, copy only the
* listed keys from the current search into the next search.
*
* @param keys `true` to retain all, or a list of keys to retain.
* @returns A search middleware suitable for route `search.middlewares`.
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/retainSearchParamsFunction
*/
export function retainSearchParams<TSearchSchema extends object>(
keys: Array<keyof TSearchSchema> | true,
): SearchMiddleware<TSearchSchema> {
return ({ search, next }) => {
const { search: resultSearch, meta } = (
next as unknown as SearchMiddlewareNextWithMeta<TSearchSchema>
)(search, true)
if (keys === true) {
const copy = { ...search, ...resultSearch }
const removed = meta.removed
const explicit = meta.explicit
for (const key of removed?.keys() || []) {
if (
(explicit && hasOwn.call(explicit, key)) ||
deepEqual(search[key as keyof TSearchSchema], removed!.get(key))
) {
delete copy[key as keyof TSearchSchema]
}
}
for (const key of meta.removedAny || []) {
delete copy[key as keyof TSearchSchema]
}
for (const key of meta.defaulted?.keys() || []) {
if (
key in search &&
!meta.removedAny?.has(key) &&
!(
meta.removed?.has(key) &&
((explicit && hasOwn.call(explicit, key)) ||
deepEqual(
search[key as keyof TSearchSchema],
meta.removed.get(key),
))
)
) {
copy[key as keyof TSearchSchema] = search[key as keyof TSearchSchema]
}
}
return copy
}
const copy = { ...resultSearch }
const explicit = meta.explicit
// add missing keys from search to copy
for (const key of keys) {
const stringKey = key as string
const removed =
meta.removedAny?.has(stringKey) ||
(meta.removed?.has(stringKey) &&
((explicit && hasOwn.call(explicit, stringKey)) ||
deepEqual(search[key], meta.removed.get(stringKey))))
if (
!removed &&
(!(key in copy) ||
(key in search &&
meta.defaulted?.has(stringKey) &&
deepEqual(copy[key], meta.defaulted.get(stringKey))))
) {
copy[key] = search[key]
}
}
return copy
}
}
/**
* Remove optional or default-valued search params from navigations.
*
* - Pass `true` (only if there are no required search params) to strip all.
* - Pass an array to always remove those optional keys.
* - Pass an object of default values; keys equal (deeply) to the defaults are removed.
*
* @returns A search middleware suitable for route `search.middlewares`.
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/stripSearchParamsFunction
*/
export function stripSearchParams<
TSearchSchema,
TOptionalProps = PickOptional<NoInfer<TSearchSchema>>,
const TValues = Partial<NoInfer<TSearchSchema>> | Array<keyof TOptionalProps>,
const TInput = IsRequiredParams<TSearchSchema> extends never
? TValues | true
: TValues,
>(input: NoInfer<TInput>): SearchMiddleware<TSearchSchema> {
return (({ search, next, meta }: SearchMiddlewareContext<TSearchSchema>) => {
if (input === true) {
Object.keys(search as object).forEach((key) => {
if (meta) {
;(meta.removedAny ||= new Set()).add(key)
}
})
return {}
}
const nextResult = next(search)
const result = { ...nextResult } as Record<string, unknown>
if (Array.isArray(input)) {
input.forEach((key) => {
delete result[key as string]
if (meta) {
;(meta.removedAny ||= new Set()).add(key as string)
}
})
} else {
Object.entries(input as Record<string, unknown>).forEach(
([key, value]) => {
if (deepEqual(result[key], value)) {
delete result[key]
if (meta) {
;(meta.removed ||= new Map()).set(key, value)
}
}
},
)
}
return result as any
}) as SearchMiddleware<TSearchSchema>
}
+103
View File
@@ -0,0 +1,103 @@
import { decode, encode } from './qss'
import type { AnySchema } from './validators'
// JSON can start with whitespace, ", [, {, -, a digit, or fa/nu/tr.
// False positives safely fall through to JSON.parse.
const jsonStart = /^(?:\s|["[{\d-]|fa|nu|tr)/
/** Default `parseSearch` that strips leading '?' and JSON-parses values. */
export const defaultParseSearch = parseSearchWith(JSON.parse)
/** Default `stringifySearch` using JSON.stringify for complex values. */
export const defaultStringifySearch = stringifySearchWith(
JSON.stringify,
JSON.parse,
)
/**
* Build a `parseSearch` function using a provided JSON-like parser.
*
* The returned function strips a leading `?`, decodes values, and attempts to
* JSON-parse string values using the given `parser`.
*
* @param parser Function to parse a string value (e.g. `JSON.parse`).
* @returns A `parseSearch` function compatible with `Router` options.
* @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization
*/
export function parseSearchWith(parser: (str: string) => any) {
const isJsonParser = parser === JSON.parse
return (searchStr: string): AnySchema => {
if (searchStr[0] === '?') {
searchStr = searchStr.substring(1)
}
const query: Record<string, unknown> = decode(searchStr)
// Try to parse any query params that might be json
for (const key in query) {
const value = query[key]
if (typeof value === 'string') {
// Skip JSON.parse when the value cannot begin valid JSON.
if (isJsonParser && !jsonStart.test(value)) {
continue
}
try {
query[key] = parser(value)
} catch (_err) {
// silent
}
}
}
return query
}
}
/**
* Build a `stringifySearch` function using a provided serializer.
*
* Non-primitive values are serialized with `stringify`. If a `parser` is
* supplied, string values that are parseable are re-serialized to ensure
* symmetry with `parseSearch`.
*
* @param stringify Function to serialize a value (e.g. `JSON.stringify`).
* @param parser Optional parser to detect parseable strings.
* @returns A `stringifySearch` function compatible with `Router` options.
* @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization
*/
export function stringifySearchWith(
stringify: (search: any) => string,
parser?: (str: string) => any,
) {
const isJsonParser = parser === JSON.parse
function stringifyValue(val: any) {
if (val && typeof val === 'object') {
try {
return stringify(val)
} catch (_err) {
// silent
}
} else if (parser && typeof val === 'string') {
// Skip JSON.parse when the value cannot begin valid JSON.
if (isJsonParser && !jsonStart.test(val)) {
return val
}
try {
// Check if it's a valid parseable string.
// If it is, then stringify it again.
parser(val)
return stringify(val)
} catch (_err) {
// silent
}
}
return val
}
return (search: Record<string, any>) => {
const searchStr = encode(search, stringifyValue)
return searchStr ? `?${searchStr}` : ''
}
}
export type SearchSerializer = (searchObj: Record<string, any>) => string
export type SearchParser = (searchStr: string) => Record<string, any>
+75
View File
@@ -0,0 +1,75 @@
export type SieveCache<TKey, TValue> = {
get: (key: TKey) => TValue | undefined
set: (key: TKey, value: TValue) => void
clear: () => void
}
/**
* A fixed-capacity cache using the SIEVE eviction algorithm
* (https://cachemon.github.io/SIEVE-website/).
*
* Entries live in the Map's FIFO insertion order; a hit only flips a `visited`
* bit instead of relinking the entry, which makes `get` (by far the hottest
* operation here) one `Map.get` plus a boolean store. Eviction sweeps a `hand`
* from the oldest entry towards the newest, clearing `visited` bits until it
* finds an unvisited entry to drop, so entries touched since the last sweep
* survive one more round. This keeps LRU-like hit ratios while being
* scan-resistant.
*/
export function createSieveCache<TKey, TValue>(
max: number,
): SieveCache<TKey, TValue> {
type Node = {
key: TKey
value: TValue
visited: boolean
}
const cache = new Map<TKey, Node>()
let hand: IterableIterator<Node> | undefined
let newest: Node | undefined
return {
get(key) {
const entry = cache.get(key)
if (!entry) {
return undefined
}
entry.visited = true
return entry.value
},
set(key, value) {
const existing = cache.get(key)
if (existing) {
existing.value = value
return
}
if (cache.size >= max) {
// sweep from `hand` towards `newest` (wrapping around to `oldest`),
// clearing `visited` bits, and evict the first unvisited entry
let node = hand?.next().value
while (!node || node.visited) {
if (node) {
node.visited = false
} else {
hand = cache.values()
}
node = hand!.next().value
}
// Live Map iterators see later insertions. Reset at the boundary so the
// next sweep wraps to the oldest entry instead of visiting a replacement.
if (node === newest) {
hand = undefined
}
cache.delete(node.key)
}
const entry: Node = { key, value, visited: false }
newest = entry
cache.set(key, entry)
},
clear() {
cache.clear()
hand = undefined
newest = undefined
},
}
}
+617
View File
@@ -0,0 +1,617 @@
# SSR streaming
This document explains how TanStack Router adds hydration scripts to server-rendered HTML.
It describes the transport in `router-core` and the React, Solid, and Vue adapters.
## Main terms
The renderer and Seroval produce output independently.
- The **application output** is the HTML from the framework renderer.
- A **hydration source** is one complete JavaScript source string from the router or Seroval.
- An **initial tag** is a hydration `<script>` that `<Scripts>` renders with the application HTML.
- A **late record** is a self-removing hydration `<script>` that the transform inserts later.
- When hydration is enabled, the **boundary** is the final script from the first server render of `<Scripts>`.
- A **safe point** is a position where the transform can insert a late record.
- The **canonical close** is the exact byte sequence `</body></html>`.
The transport keeps the order from each producer.
It does not define one arrival order across both producers.
Instead, it inserts ready hydration sources at safe points in the application output.
The canonical close is the only application output that the merge path moves intentionally.
## Main components
A framework adapter produces application output as UTF-8 bytes or as an eager HTML string.
Seroval produces complete hydration sources.
`attachRouterServerSsrUtils()` creates one request-local hydration state with `createHydrationScripts()`.
`ServerSsr` stores this state directly.
The hydration state owns these tasks:
- It stores the request nonce.
- It creates the initial tags and the boundary.
- It frames late records.
- It keeps sources in FIFO order.
- It applies backlog limits.
- It reports output state and failures.
- It removes retained data during cleanup.
The stream transform reads this state.
It does not create the `<script>` framing.
It treats each late record as opaque bytes.
The transform only recognizes fixed protocol bytes in application output.
It is not an HTML parser.
## Request flow
A normal hydration request has these steps:
1. The hydration state starts with the Seroval cross-reference header and the router bootstrap.
2. `serverSsr.dehydrate()` builds the router state and starts Seroval.
3. Seroval sends complete hydration sources to the hydration state.
4. The first server render of `<Scripts>` takes all hydration sources that are ready.
5. `<Scripts>` renders initial tags, route scripts, manifest scripts, and one boundary.
6. The transform inserts later hydration sources at safe points.
7. Natural completion, cancellation, or failure cleans Router-owned request state.
The serialized router state contains rendered route-match data.
It can also contain data from `router.options.dehydrate()`.
Promises and streams in that data can produce hydration sources later.
The request signal stops Router's wait for this hook, but is not passed into
the application callback.
## Initial hydration tags
The hydration state counts each retained source when the source arrives.
This count includes the cross-reference header and router bootstrap.
It also includes sources that arrive before `<Scripts>` renders.
The first `<Scripts>` render takes all queued sources.
The initial tags then own those sources.
The hydration state removes them from its backlog count.
The take is a one-time operation.
A later `<Scripts>` render cannot create a second boundary.
### Initial tag size
Small adjacent sources can share one initial tag.
Their source text and separators must fit in 16 Ki UTF-16 code units.
A source that exceeds this limit stays in its own tag.
The code does not join that source to another source.
Every initial hydration tag has the `data-tsr-stream-part` attribute.
### Initial tag cleanup
The final initial tag normally includes cleanup code.
The cleanup code walks through preceding element siblings with `data-tsr-stream-part`.
It removes those siblings and then removes its own tag.
The cleanup code uses sibling links.
It does not create a DOM collection or call `document.querySelectorAll()`.
If appending cleanup makes the final initial tag exceed 16 Ki, the code creates a separate cleanup tag.
It never appends cleanup code to an already oversized source.
If no initial source exists, `<Scripts>` emits no initial cleanup tag.
It can still emit the boundary.
A hydration syntax error or runtime error can prevent cleanup.
In that case, temporary initial tags can remain in the document.
### Order inside `<Scripts>`
`<Scripts>` emits server content in this order:
1. Initial hydration tags.
2. Route and manifest script elements.
3. The boundary.
The boundary is the last child emitted by `<Scripts>`.
It is not required to be the last child in `<body>`.
React can hoist eligible external route scripts under its renderer rules.
The transport does not control when asynchronous or external scripts run.
## Placement of `<Scripts>`
`<Scripts>` marks the first position where late records can appear.
Render it in `<body>`.
Application markup, framework-owned deferred patch records, and closing markup can follow the boundary.
Late router records can appear between these output parts at the safe points below.
The byte-pattern rules below still apply.
While the transform remains in the `Merge` phase, it treats the first exact `</body></html>` after the boundary as the real document close.
The structural document close normally supplies this sequence.
Raw application data after the boundary must not contain an earlier exact copy.
React treats each exact lowercase `</script>` as a safe point.
After the boundary, each such sequence must be a position where script insertion is valid.
These rules are application and adapter contracts.
The byte scanner cannot tell structural markup from matching text.
## The boundary
The boundary is a private transport marker emitted by `<Scripts>`.
The boundary script removes itself in the browser.
The transform scans for the boundary only after the initial take.
Before that take, it forwards consumed application bytes without a boundary scan.
When the transform finds the boundary, it enters the `Merge` phase and lifts the hydration barrier.
Queued late sources then become eligible for output.
If application EOF arrives before the boundary, hydration-enabled merge mode releases the initial sources as late records.
The transform then drains them after the delivered document, as it does for any EOF safe point.
The page cannot hydrate without the route scripts that `<Scripts>` renders, but the response completes.
Disabled hydration and initial pass-through do not require a boundary.
## Transform paths
One stream implementation serves every request.
It starts in pass-through when the hydration state can reserve the fast path before any application output.
Otherwise it starts in merge mode and can change to pass-through later.
Both entries use the same `PassThrough` phase.
### Initial pass-through
The hydration state reserves initial pass-through only when all these conditions are true:
- The state is live and has no failure.
- Serialization is complete.
- The initial take or `disableHydration()` committed the initial output.
- No queued or active hydration output remains.
- No consumer or earlier fast-path reservation conflicts with this reservation.
The stream then never claims the hydration output and never scans.
It forwards each `Uint8Array` from the renderer unchanged.
It does not scan, copy, or move those bytes.
A Node renderer can also send string records.
The path encodes one string record at a time in chunks of at most 64 KiB.
It does not join separate string records.
At application EOF, the path marks rendering as complete and closes normally.
### Disabled hydration
`serverSsr.disableHydration()` disables router hydration output for one request.
Call it instead of `dehydrate()`, before rendering starts.
The runtime also rejects calls after any of these events:
- `dehydrate()` starts.
- The first `<Scripts>` take commits initial output.
- The transform claims the hydration output.
- The hydration producer completes or starts an active record.
The call removes the queued bootstrap sources.
It commits the initial state, lifts the barrier, and marks the producer as complete.
The request emits no hydration tags or router boundary.
`<Scripts>` can still render normal route and manifest scripts.
The transform can use initial pass-through.
### Merge mode
The transform uses merge mode when it cannot reserve initial pass-through.
Merge mode claims the request hydration output for one consumer.
A second consumer causes an error.
Merge mode recognizes these universal byte patterns:
1. The fixed router boundary suffix.
2. The exact canonical close.
An adapter can add one safe-point profile:
- `script-close` matches exact lowercase `</script>`.
- `record-end` uses the end of a complete renderer record.
The core does not select a profile from a framework name.
The adapter selects it.
The boundary and script-close matchers keep partial matches across input chunks.
Their patterns have a unique first byte.
The canonical close repeats its first byte.
The transform uses an exact search and a carry of at most 13 bytes for that pattern.
### Merge phases
| Phase | Meaning |
| ---------------- | -------------------------------------------------------------- |
| `BeforeBoundary` | Forward application output and wait for the one-time boundary. |
| `Merge` | Find safe points and the canonical close. |
| `HeldClose` | Keep the canonical close while later output drains. |
| `PassThrough` | Forward all later application output without scanning. |
A stream starts in `PassThrough` when initial pass-through is reserved; otherwise only `Merge` can enter it.
`HeldClose` must preserve final document order, so it cannot enter that phase.
A ready late record starts only after the boundary and at a safe point.
An active late record drains completely before application output resumes.
### Dynamic pass-through
Merge mode can stop scanning after the boundary.
It does this only when all these conditions are true:
- The hydration output is `Done`.
- No hydration source or active record remains.
- The transform holds no partial canonical close.
- The hydration state can reserve the fast path for the current consumer.
After the switch, all later application output passes through unchanged.
The transform does not scan or move later document closes.
## Adapter safe points
| Adapter or path | Additional safe point |
| --------------- | --------------------------------- |
| React | Exact lowercase `</script>` |
| Solid | End of a complete renderer record |
| Vue | None |
| Eager string | None |
The boundary and canonical close are safe points for every adapter.
Ordinary EOF is also a safe point after the boundary.
A partial canonical close at EOF is forwarded as ordinary content, as described below.
### React
The transform treats React chunk boundaries as arbitrary.
It does not use them as safe points.
The script-close profile lets a late record follow a complete React patch script.
It can also emit router data while React waits for later Suspense work.
The adapter uses `renderToReadableStream` when that function exists.
Otherwise, it uses `renderToPipeableStream`.
Both paths use the same script-close profile.
Both paths set `progressiveChunkSize` to positive infinity so React does not split completed Suspense boundaries into separate patches based only on output size.
The adapter does not inspect the React version.
### Solid
The Solid adapter preserves each complete shell or patch string as one renderer record.
It uses the end of that record as a safe point.
An internal 64 KiB encoding chunk is not a record end.
The safe point occurs only after the complete source record drains.
### Vue
The Vue adapter does not treat renderer record ends as safe points.
It uses only the boundary, the canonical close, and eligible EOF.
The Vue application output must have one `<html>` element as its outer root.
An outer Vue Fragment or root array is not supported.
Its closing marker follows `</html>`, and the transform does not preserve that position.
Fragments inside `<html>` are supported.
## Canonical document close
Merge mode recognizes only this exact adjacent lowercase sequence:
```html
</body></html>
```
While the transform remains in the `Merge` phase, the first matching sequence after the boundary becomes the held canonical close.
The transform emits preceding application bytes and holds the 14-byte close.
A match inside one byte chunk advances past the close without copying it.
The transform can emit the preceding prefix as a view of that chunk.
A match across chunks uses the carry and one small combined buffer.
The transform caches the search result for the current byte chunk, including a missing match.
Returning from a renderer safe point reuses that result; advancing to another byte chunk clears it.
The transform continues to process renderer patches and late records after it holds the close.
All other application bytes keep their order.
Late records keep FIFO order.
The two streams can interleave only at safe points.
After successful completion, the transform emits a fresh 14-byte copy of the held close last.
On failure or cancellation, the transform does not emit the held close.
Bytes already delivered to the consumer remain delivered.
The match is case-sensitive and byte-exact.
Whitespace or a text node between `</body>` and `</html>` prevents a match.
If the transform completes successfully without a canonical match, it preserves all application bytes.
A later record can then appear after `</html>`.
This can happen at a React script close, a Solid record end, or EOF.
Supporting every equivalent HTML form requires an HTML parser.
This transport uses exact byte matching instead.
Initial and dynamic pass-through never move a document close.
They also preserve bytes that follow `</html>`.
### EOF rules
After the boundary, ordinary EOF can provide the final safe point.
If a late record is `Active`, it drains first.
These rules apply after no record is active:
- If output is `Ready`, the transform drains ready late records at EOF.
- If output is `Waiting`, the transform waits for a state change.
- If normal serialization reaches `Done`, the transform completes.
- If output is `Failed`, the transform fails immediately.
A partial canonical-close prefix at EOF is ordinary application content.
The transform forwards those bytes first and then applies the rules above.
A late record can follow them, exactly as after a document without a canonical close.
Server cleanup terminates the transform instead of using these `Done` rules.
## Hydration output states
`claimOutput()` creates one pull view for merge mode.
The view has five states:
| State | Meaning |
| --------- | ---------------------------------------------------------------------------------- |
| `Waiting` | No late record is eligible. The queue can still contain blocked sources. |
| `Ready` | Queued sources can start at the next safe point. |
| `Active` | One late record is in progress and must finish. |
| `Done` | Normal output drained, hydration is disabled, or cleanup made the output inactive. |
| `Failed` | The response must fail immediately. |
The hydration output permits one consumer claim.
While it is live, it permits one active subscriber at a time.
Another subscriber can register after the first subscriber unregisters.
After cleanup, subscription returns a function that does nothing.
The transform calls `pullChunk()` only from a response-stream pull.
Each call returns at most 64 KiB of bytes.
## Late record framing
`hydrationScripts.ts` owns the complete framing of every late record.
The framing includes the opening tag, escaped nonce, separators, self-removal source, and closing tag.
A late record has this logical form:
```text
<script nonce="...">source;source;document.currentScript.remove()</script>
```
The nonce attribute is absent when the request has no nonce.
The code escapes `&`, double quotes, single quotes, `<`, and `>` in a dynamic nonce.
The transform does not inspect this framing.
### Late record size
The hydration output selects a FIFO source prefix for each late record.
Its target is at most 64 Ki UTF-16 code units for the complete framed record.
The hydration output never splits one hydration source across script tags.
Therefore, one large source can create a record above the target.
If a complete record is at most 16 Ki code units, the hydration output joins and encodes it once.
The hydration output encodes larger records in bounded parts with `encodeInto()`.
Every returned byte chunk is at most 64 KiB.
Application output cannot appear inside an active record.
### Queue ownership
The queue uses one source array and a head index.
When it selects the complete unconsumed array, it can reuse that array internally.
For a partial selection, it copies the selected prefix.
It replaces consumed queue slots with empty slots instead of shifting the live suffix.
The queue removes its backing array when it becomes empty.
For a busy queue, it can compact after at least 1,024 consumed entries.
The consumed prefix must also be at least as large as the live suffix.
Compaction keeps FIFO order.
The hydration output releases a source from backlog accounting after its text finishes encoding.
The record stays `Active` until its separators and closing code drain.
The boundary does not move or copy queued source strings.
It only makes them eligible for a pull.
Normal serialization adds `$_TSR.e()` as the final hydration source.
The hydration output becomes `Done` after that source and all earlier sources drain.
A backlog error changes the state to `Failed`, drops queued and active sources,
and causes Router to dispose of the SSR serializer.
Cleanup clears the queue and changes a claimed output to `Done`.
## Backpressure and memory limits
One downstream pull emits at most one output chunk.
The transform starts at most one application read ahead.
The merge path can retain these main values:
- One current application record and its encoder cursor, or one in-flight or prefetched nonterminal application read.
- One encoded application-string chunk of at most 64 KiB. The current input string record can be larger.
- At most 13 bytes from a partial canonical close.
- One active late record with its selected sources.
- One queue of later hydration sources.
- One hydration output buffer of at most 64 KiB.
The hydration state permits at most 4,096 retained sources across initial, queued, and active output.
It also permits at most 16,777,216 UTF-16 code units of regular retained source text.
These limits include constructor seeds and later sources.
They apply before and after the initial take.
The limits apply to the pending backlog, not to total response output.
Initial-source accounting ends at the initial take.
Late-source accounting ends when each source finishes encoding.
One source can exceed the 16 Mi-code-unit limit.
This exception supports one large loader or query value.
A second oversized source cannot be retained while the first is queued or being encoded.
Cleanup clears source arrays, active encoder state, callbacks, timers, and stored errors.
New eligible output and failures can wake the transform through one subscription.
`pullChunk()` does not notify the subscriber about successful state transitions.
When a producer update or barrier transition changes the output state, the hydration state still notifies the transform.
This notification can occur while a response-stream pull is pending.
Server cleanup terminates through a separate cleanup listener.
Application reads wake the transform separately.
The transform uses one waiting resolver at a time.
It does not create `Promise.race()` handlers in its pump.
## Unicode and string input
Built-in streaming adapters send UTF-8 `Uint8Array` records.
The transform forwards application bytes without decoding them.
A UTF-8 character can span byte records.
A Node pipeable stream can also send string records.
The transform encodes each string record independently in chunks of at most 64 KiB.
It does not repair a surrogate pair that spans two separate string records.
A record-end safe point occurs after the complete string, not after an internal encoding chunk.
Each hydration source is one complete JavaScript string.
A semicolon separates adjacent sources in one tag.
HTML markup separates sources in different tags.
`TextEncoder` and `encodeInto()` do not split a valid surrogate pair inside one source.
The implementation does not cut sources at estimated UTF-16 offsets.
### Eager string output
The eager helper uses the same merge path when initial pass-through is unavailable.
It encodes `<!DOCTYPE html>` and the HTML string in bounded parts.
It decodes merged output incrementally with `TextDecoder`.
It does not first collect one complete byte buffer or call `Response.text()`.
When initial pass-through is available, the helper returns `<!DOCTYPE html>` plus the original HTML string.
It then cleans the server state in a `finally` block.
## Completion and cleanup
The streaming paths use one finalizer.
The eager fast path uses its own `try` and `finally` because it has no response stream.
| Result | Response output | Application reader | `onAbort` |
| ------------------------ | --------------- | ------------------ | --------- |
| Natural completion | Close | Release | No |
| Request abort | Error | Cancel | Yes |
| Consumer cancellation | No extra signal | Cancel | Yes |
| Stream or output failure | Error | Cancel | Yes |
| Serialization timeout | Error | Cancel | Yes |
| Lifetime timeout | Error | Cancel | Yes |
| External server cleanup | Error | Cancel | Yes |
The terminal guard makes cleanup run once.
A non-success result calls the adapter `onAbort` function at most once.
After natural completion, the transform releases the application reader.
After another result, it cancels the reader.
Reader cancellation can finish after router cleanup.
Finally, server cleanup disposes of the SSR serializer and clears Router-owned hydration state.
It also stops the reader pump that Router's SSR RawStream bridge creates.
It clears the request router's `router.ssr` and `router.serverSsr` slots.
Cleanup listeners receive one boolean, `settled`.
It is true when every value the router dehydrated has settled.
Rejected hydration output, including a backlog failure, stops serialization without marking deferred values as settled.
Router aborts the request's route-match controllers only when `settled` is false, because only then can loader work still be pending.
Canceling a RawStream that the SSR or JSON bridge reconstructs removes Router's Seroval-stream listener.
Seroval and its official plugins remain responsible for work that they create.
### Timeouts
In merge mode, application EOF starts the serialization timeout and calls `setRenderFinished()`.
This happens as soon as a prefetched read reports EOF, even if the consumer pauses.
The default serialization timeout is 60 seconds.
The timeout runs only while Seroval remains active.
It changes hydration output to `Failed` when it expires.
Every live streaming transform also has a lifetime timeout.
Its default is twice the serialization timeout.
Some Web runtimes return numeric timer IDs with no `unref()` method.
The code calls `unref()` only when the returned timer handle provides it.
The serialization timeout stays referenced because it protects active work after application rendering ends.
### External cleanup and response disposal
`ServerSsr.cleanup()` notifies each live transform.
The transform then fails with an `AbortError`, cancels its reader, and calls the adapter abort function.
A stream response also provides an idempotent `dispose()` function.
Disposal removes router ownership before it cancels the response body.
A renderer can ignore that body cancellation.
After response handoff, request-abort binding has four cases:
- If the request is already aborted, handoff disposes the stream immediately.
- If the live transform already observes the same request signal, handoff reuses its listener. On request abort, SSR cleanup also disposes the final response, including a body wrapped by middleware.
- Otherwise, with live router SSR state, handoff adds a listener to dispose the stream, and SSR cleanup removes that listener.
- Without live router SSR state, abort still disposes the stream. The one-time listener ends with the request signal.
### Adapter cancellation limits
Every streaming adapter rejects a request that is already aborted before renderer setup.
The adapters and core transform also detect an abort during synchronous setup before they return a response.
The React readable path passes the request signal to `renderToReadableStream`.
The React pipeable path passes `abort()` to the transform.
For Solid, cancelling the transform's reader errors the writable used by its renderer.
Vue pipes its public readable renderer stream into the transform, so reader cancellation propagates to Vue.
Neither renderer provides a disposal handle for unresolved component work.
The adapters stop outgoing bytes and release router-owned state.
An unresolved Solid or Vue resource can retain its renderer closure until that resource settles.
React and Solid bot-readiness waits observe an adapter signal that the transform aborts on failure or cancellation, including request abort, lifetime expiry, and external SSR cleanup.
These waits cannot keep the response promise pending after the transform terminates.
The extra controller is allocated only for bot waits on the readable-stream paths.
Each wait removes its listener when the wait ends.
## Test coverage
Unit tests cover every byte split of the boundary and script-close patterns.
They also cover every internal split of the canonical close.
Hydration-state tests cover initial ownership, exact framing, nonce escaping, FIFO order, size limits, completion, failure, and cleanup.
Transform tests cover safe points, content after `<Scripts>`, EOF, close carry, ordering, cancellation, timeouts, Unicode, and stream errors.
Adapter tests make sure that React, Solid, and Vue select the documented safe-point profiles.
Real-renderer tests cover React 19 script closes and Solid record ends.
React and Solid browser suites cover CSP for ordinary SSR output.
No browser CSP test forces a late dynamic hydration record.
Vue has no equivalent browser CSP suite.
Normal unit tests cover backpressure correctness and lost-record prevention.
Slow-consumer memory tests run only when `RUN_BACKPRESSURE_PERF=1`.
Browser tests cover hydration data, interaction, data order, and removal of initial hydration tags and the boundary.
The [SSR streaming benchmark](../../benchmarks/ssr-streaming/README.md) measures throughput and retained memory.
Use interleaved warm runs for latency comparisons.
Use isolated processes with forced garbage collection for memory comparisons.
Treat machine-specific measurements as supporting evidence.
They are not part of the transport contract.
+57
View File
@@ -0,0 +1,57 @@
import { _getAssetMatches } from '../load-client'
import type { Manifest, RouterManagedTag } from '../manifest'
import type { AnyRouteMatch } from '../Matches'
import type { InitialHydrationScriptTags } from './hydrationScripts'
type ScriptTags = Array<RouterManagedTag>
export type SsrBodyScriptParts = readonly [ScriptTags, ScriptTags]
export function getSsrBodyScriptParts(
matches: Array<AnyRouteMatch>,
manifest: Manifest | undefined,
nonce: string | undefined,
routeScriptAttrs?: Record<string, unknown>,
): SsrBodyScriptParts {
const assetMatches = _getAssetMatches(matches)
const routeScripts: ScriptTags = []
const manifestScripts: ScriptTags = []
for (const match of assetMatches) {
for (const script of Array.isArray(match.scripts) ? match.scripts : []) {
if (!script) {
continue
}
const { children, ...attrs } = script
routeScripts.push({
tag: 'script',
attrs: { ...attrs, ...routeScriptAttrs, nonce },
children,
})
}
}
if (manifest) {
for (const match of assetMatches) {
for (const asset of manifest.routes[match.routeId]?.scripts ?? []) {
manifestScripts.push({
tag: 'script',
attrs: { ...asset.attrs, nonce },
children: asset.children,
})
}
}
}
return [routeScripts, manifestScripts]
}
export function composeSsrBodyScripts(
[routeScripts, manifestScripts]: SsrBodyScriptParts,
initialHydrationScripts?: InitialHydrationScriptTags,
): Array<RouterManagedTag> {
if (!initialHydrationScripts) {
return [...routeScripts, ...manifestScripts]
}
return [
...initialHydrationScripts.before,
...routeScripts,
...manifestScripts,
initialHydrationScripts.boundary,
]
}
+14
View File
@@ -0,0 +1,14 @@
export { mergeHeaders } from './headers'
export { json } from './json'
export type { JsonResponse } from './json'
export { hydrate } from './ssr-client'
export * from './ssr-client'
export type { TsrSsrGlobal, DehydratedMatch, DehydratedRouter } from './types'
export {
createDefaultSerovalPlugins,
defaultSerovalPlugins,
defaultSerovalDeserializerPlugins,
} from './serializer/seroval-plugins'
export { makeSerovalPlugin } from './serializer/makeSerovalPlugin'
export type { AnySerializationAdapter } from './serializer/transformer'
export { createRawStreamDeserializePlugin } from './serializer/RawStreamRPCPlugin'
+2
View File
@@ -0,0 +1,2 @@
export const GLOBAL_TSR = '$_TSR'
export declare const GLOBAL_SEROVAL: '$R'
+129
View File
@@ -0,0 +1,129 @@
import { createServerHistory } from '@tanstack/history'
import { _getRenderedMatches } from '../load-client'
import { waitForReason as waitForRequest } from '../await-signal'
import { mergeHeaders } from './headers'
import {
attachRouterServerSsrUtils,
getNormalizedURL,
getOrigin,
} from './ssr-server'
import {
bindSsrResponseToRequest,
disposeSsrResponse,
isSsrResponse,
} from './handlerCallback'
import type { HandlerCallback } from './handlerCallback'
import type { AnyHeaders } from './headers'
import type { AnyRouter } from '../router'
import type { ServerManifest } from '../manifest'
export type RequestHandler<TRouter extends AnyRouter> = (
cb: HandlerCallback<TRouter>,
) => Promise<Response>
export { waitForRequest }
function createLateResponseDisposer(signal: AbortSignal) {
return (result: unknown) => {
if (result instanceof Response || isSsrResponse(result)) {
disposeSsrResponse(result, signal.reason)
}
}
}
export function createRequestHandler<TRouter extends AnyRouter>({
createRouter,
request,
getRouterManifest,
}: {
createRouter: () => TRouter
request: Request
getRouterManifest?: () => ServerManifest | Promise<ServerManifest>
}): RequestHandler<TRouter> {
return async (cb) => {
const signal = request.signal
signal.throwIfAborted()
const manifest = getRouterManifest
? await waitForRequest(getRouterManifest(), signal)
: undefined
signal.throwIfAborted()
const router = createRouter()
let responseOwnsCleanup = false
try {
attachRouterServerSsrUtils({
router,
manifest,
})
// normalizing and sanitizing the pathname here for server, so we always deal with the same format during SSR.
const { url } = getNormalizedURL(request.url, 'http://localhost')
const origin = getOrigin(request)
const href = url.href.replace(url.origin, '')
// Create a history for the router
const history = createServerHistory(href)
// Update the router with the history and context
router.update({
history,
origin: router.options.origin ?? origin,
})
await router.load({
_signal: signal,
})
signal.throwIfAborted()
const result = router._serverResult
if (result?.type === 'redirect') {
return result.redirect
}
await router.serverSsr?.dehydrate({ signal })
signal.throwIfAborted()
const responseHeaders = getRequestHeaders({
router,
})
signal.throwIfAborted()
const disposeLate = createLateResponseDisposer(signal)
const response = await waitForRequest(
cb({
request,
router,
responseHeaders,
}),
signal,
disposeLate,
disposeLate,
)
const ssrResponse = bindSsrResponseToRequest(router, response, signal)
signal.throwIfAborted()
responseOwnsCleanup = ssrResponse.serverSsrCleanup === 'stream'
return ssrResponse.response
} finally {
if (!responseOwnsCleanup) {
// Clean up router SSR state if the callback won't handle it
// (e.g., if an error occurred before the callback was invoked).
// Transformed streaming response bodies clean up when consumed/cancelled.
router.serverSsr?.cleanup()
}
}
}
}
function getRequestHeaders(opts: { router: AnyRouter }): Headers {
const matchHeaders: Array<AnyHeaders> = []
for (const match of _getRenderedMatches(opts.router.stores.matches.get())) {
matchHeaders.push(match.headers)
}
return mergeHeaders(
{
'Content-Type': 'text/html; charset=UTF-8',
},
...matchHeaders,
)
}
+159
View File
@@ -0,0 +1,159 @@
import type { AnyRouter } from '../router'
export type SsrResponse =
| {
response: Response
serverSsrCleanup: 'none'
}
| {
response: Response
serverSsrCleanup: 'stream'
dispose: (reason?: unknown) => undefined
}
export type HandlerCallbackResult = Response | SsrResponse
export function isSsrResponse(value: unknown): value is SsrResponse {
return (
typeof value === 'object' &&
value !== null &&
'response' in value &&
'serverSsrCleanup' in value
)
}
export function normalizeSsrResponse(
result: HandlerCallbackResult,
): SsrResponse {
return isSsrResponse(result)
? result
: { response: result, serverSsrCleanup: 'none' }
}
function cancelResponseBody(response: Response, reason?: unknown): void {
const body = response.body
if (!body) {
return
}
void body.cancel(reason).catch(console.error)
}
export function disposeSsrResponse(
result: HandlerCallbackResult,
reason?: unknown,
): undefined {
const response = normalizeSsrResponse(result)
if (response.serverSsrCleanup === 'stream') {
response.dispose(reason)
} else {
cancelResponseBody(response.response, reason)
}
}
/** The HTTP status that Router's server load selected for this render. */
export function getSsrStatus(router: AnyRouter) {
return router._serverResult?.type === 'render'
? router._serverResult.status
: 200
}
export function createSsrStreamResponse(
router: AnyRouter,
response: Response,
): Extract<SsrResponse, { serverSsrCleanup: 'stream' }> {
const body = response.body
if (!body) {
throw new Error('Invariant failed: SSR stream response requires a body')
}
return {
response,
serverSsrCleanup: 'stream',
dispose(reason?: unknown): undefined {
// Sever router ownership before asking user/renderer stream machinery to
// cancel. A custom stream is allowed to ignore cancellation forever.
router.serverSsr?.cleanup()
void body.cancel(reason).catch(() => {})
},
}
}
export function bindSsrResponseToRequest(
router: AnyRouter | undefined,
result: HandlerCallbackResult,
signal: AbortSignal,
): SsrResponse {
const ssrResponse = normalizeSsrResponse(result)
if (ssrResponse.serverSsrCleanup !== 'stream') {
if (signal.aborted) {
disposeSsrResponse(result, signal.reason)
}
return ssrResponse
}
const abort = () => {
disposeSsrResponse(ssrResponse, signal.reason)
}
if (signal.aborted) {
abort()
return ssrResponse
}
const serverSsr = router?.serverSsr
if (serverSsr?.hydrationScripts.requestSignal === signal) {
// The transform already observes this request. Its cleanup must also
// dispose the final response, including any middleware-owned body.
serverSsr.onCleanup(() => {
if (signal.aborted) {
abort()
}
})
return ssrResponse
}
signal.addEventListener('abort', abort, { once: true })
if (!serverSsr) {
return ssrResponse
}
serverSsr.onCleanup(() => {
signal.removeEventListener('abort', abort)
})
return ssrResponse
}
export function replaceSsrResponse(
result: HandlerCallbackResult,
response: Response,
reason?: unknown,
): Extract<SsrResponse, { serverSsrCleanup: 'none' }> {
disposeSsrResponse(result, reason)
return { response, serverSsrCleanup: 'none' }
}
export function stripSsrResponseBody(
result: HandlerCallbackResult,
reason?: unknown,
): Extract<SsrResponse, { serverSsrCleanup: 'none' }> {
const ssrResponse = normalizeSsrResponse(result)
disposeSsrResponse(ssrResponse, reason)
return {
response: new Response(null, ssrResponse.response),
serverSsrCleanup: 'none',
}
}
export interface HandlerCallback<TRouter extends AnyRouter> {
(ctx: {
request: Request
router: TRouter
responseHeaders: Headers
}): HandlerCallbackResult | Promise<HandlerCallbackResult>
}
export function defineHandlerCallback<TRouter extends AnyRouter>(
handler: HandlerCallback<TRouter>,
): HandlerCallback<TRouter> {
return handler
}
+40
View File
@@ -0,0 +1,40 @@
import { splitSetCookieString } from 'cookie-es'
import type { OutgoingHttpHeaders } from 'node:http2'
export type AnyHeaders =
| Headers
| HeadersInit
| Record<string, string>
| Array<[string, string]>
| OutgoingHttpHeaders
| undefined
// Helper function to convert various HeaderInit types to a Headers instance
function toHeadersInstance(init: AnyHeaders) {
if (init instanceof Headers) {
return init
} else if (Array.isArray(init)) {
return new Headers(init)
} else if (typeof init === 'object') {
return new Headers(init as HeadersInit)
} else {
return null
}
}
// Function to merge headers with proper overrides
export function mergeHeaders(...headers: Array<AnyHeaders>) {
return headers.reduce((acc: Headers, header) => {
const headersInstance = toHeadersInstance(header)
if (!headersInstance) return acc
for (const [key, value] of headersInstance.entries()) {
if (key === 'set-cookie') {
const splitCookies = splitSetCookieString(value)
splitCookies.forEach((cookie) => acc.append('set-cookie', cookie))
} else {
acc.set(key, value)
}
}
return acc
}, new Headers())
}
+138
View File
@@ -0,0 +1,138 @@
const textEncoder = new TextEncoder()
const DOCUMENT_CLOSE = '</body></html>'
export const SCRIPT_CLOSE = '</script>'
export const DOCUMENT_CLOSE_ANCHOR_INDEX = DOCUMENT_CLOSE.indexOf('y')
export const SCRIPT_CLOSE_ANCHOR_INDEX = SCRIPT_CLOSE.indexOf('p')
export const DOCUMENT_CLOSE_BYTES = textEncoder.encode(DOCUMENT_CLOSE)
export const SCRIPT_CLOSE_BYTES = textEncoder.encode(SCRIPT_CLOSE)
export function encodeIntoBoundedChunk(
source: string,
sourceOffset: number,
output: Uint8Array,
outputOffset = 0,
) {
// encodeInto() stops before a code point that does not fit, so it never
// splits a surrogate pair across chunks.
return textEncoder.encodeInto(
sourceOffset === 0 ? source : source.slice(sourceOffset),
outputOffset === 0 ? output : output.subarray(outputOffset),
)
}
/**
* State for matching a fixed ASCII sequence across input chunks.
*
* The pattern must be non-empty, its first byte must be unique, and the anchor
* index must point inside the pattern.
*/
export type ByteMatcherState = {
readonly pattern: Uint8Array
readonly anchorIndex: number
matched: number
}
/** Advance matcher state and return the local offset after a complete match. */
export function advanceByteMatcher(
matcher: ByteMatcherState,
value: Uint8Array,
startIndex = 0,
findLast = false,
) {
const { pattern, anchorIndex } = matcher
let matched = matcher.matched
let lastMatchEnd: number | undefined
let index = startIndex
while (index < value.length) {
if (matched === 0) {
if (anchorIndex > 0 && index < value.length - anchorIndex) {
const anchor = value.indexOf(pattern[anchorIndex]!, index + anchorIndex)
if (anchor < 0) {
index = value.length - anchorIndex
continue
}
index = anchor - anchorIndex
} else {
index = value.indexOf(pattern[0]!, index)
if (index < 0) {
matcher.matched = matched
return lastMatchEnd
}
}
}
const byte = value[index]!
if (byte === pattern[matched]) {
matched++
} else {
matched = byte === pattern[0] ? 1 : 0
}
index++
if (matched === pattern.length) {
matched = 0
if (!findLast) {
matcher.matched = matched
return index
}
lastMatchEnd = index
}
}
matcher.matched = matched
return lastMatchEnd
}
/** Find a complete fixed sequence that is contained in one byte chunk. */
export function findExactBytes(
value: Uint8Array,
pattern: Uint8Array,
startIndex = 0,
anchorIndex = 0,
) {
let anchor = value.indexOf(pattern[anchorIndex]!, startIndex + anchorIndex)
while (anchor >= 0) {
const candidate = anchor - anchorIndex
if (candidate + pattern.length > value.length) {
return -1
}
let patternIndex = 0
while (
patternIndex < pattern.length &&
value[candidate + patternIndex] === pattern[patternIndex]
) {
patternIndex++
}
if (patternIndex === pattern.length) {
return candidate
}
anchor = value.indexOf(pattern[anchorIndex]!, anchor + 1)
}
return -1
}
/**
* Find the longest suffix that can become the fixed sequence in the next
* chunk. The returned index starts that suffix.
*/
export function getExactBytesPrefixAtEnd(
value: Uint8Array,
pattern: Uint8Array,
startIndex = 0,
) {
candidate: for (
let length = Math.min(pattern.length - 1, value.length - startIndex);
length > 0;
length--
) {
const candidateStart = value.length - length
for (let index = 0; index < length; index++) {
if (value[candidateStart + index] !== pattern[index]) {
continue candidate
}
}
return candidateStart
}
return undefined
}
+689
View File
@@ -0,0 +1,689 @@
/* eslint-disable @typescript-eslint/triple-slash-reference */
/// <reference path="../vite-env.d.ts" />
import { getCrossReferenceHeader } from 'seroval'
import { invariant } from '../invariant'
import minifiedTsrBootStrapScript from './tsrScript?script-string'
import { GLOBAL_TSR } from './constants'
import { encodeIntoBoundedChunk } from './htmlBoundaryScanner'
import type { RouterManagedTag } from '../manifest'
export const SSR_SERIALIZATION_SCOPE_ID = 'tsr'
const HYDRATION_SCRIPT_BOUNDARY_TAIL = ';/*$tsr-stream-boundary*/'
const encoder = new TextEncoder()
const SOURCE_SEPARATOR = ';'
const MAX_INITIAL_SOURCE_CODE_UNITS = 16 * 1024
const MAX_BACKLOG_CODE_UNITS = 16 * 1024 * 1024
const MAX_BACKLOG_SOURCES = 4_096
const MIN_OUTPUT_BYTES = 256
const MAX_DIRECT_CODE_UNITS = 16 * 1024
export const MAX_HYDRATION_OUTPUT_CHUNK_BYTES = 64 * 1024
const MAX_DYNAMIC_RECORD_CODE_UNITS = MAX_HYDRATION_OUTPUT_CHUNK_BYTES
const STREAM_PART_ATTRIBUTE = 'data-tsr-stream-part'
const INITIAL_CLEANUP_SOURCE = `{let s=document.currentScript,p;while((p=s.previousElementSibling)&&p.hasAttribute('${STREAM_PART_ATTRIBUTE}'))p.remove();s.remove()}`
const INITIAL_CLEANUP_SUFFIX = SOURCE_SEPARATOR + INITIAL_CLEANUP_SOURCE
const DYNAMIC_CLOSE_SOURCE = 'document.currentScript.remove()</script>'
const HYDRATION_SCRIPT_BOUNDARY_SOURCE =
`document.currentScript.remove()` + HYDRATION_SCRIPT_BOUNDARY_TAIL
const HYDRATION_SCRIPT_BOUNDARY_SUFFIX =
HYDRATION_SCRIPT_BOUNDARY_TAIL + '</script>'
export const HYDRATION_SCRIPT_BOUNDARY_ANCHOR_INDEX =
HYDRATION_SCRIPT_BOUNDARY_SUFFIX.lastIndexOf('*')
export const HYDRATION_SCRIPT_BOUNDARY_BYTES = encoder.encode(
HYDRATION_SCRIPT_BOUNDARY_SUFFIX,
)
const ROUTER_PREFIX = GLOBAL_TSR + '.router='
const PROMISE_PREFIX = GLOBAL_TSR + '.p(()=>'
const DEFAULT_INITIAL_SOURCES = [
getCrossReferenceHeader(SSR_SERIALIZATION_SCOPE_ID),
minifiedTsrBootStrapScript,
]
export const HydrationScriptOutputState = {
Waiting: 0,
Ready: 1,
Active: 2,
Done: 3,
Failed: 4,
} as const
export type HydrationScriptOutputState =
(typeof HydrationScriptOutputState)[keyof typeof HydrationScriptOutputState]
/** A request-local, single-consumer stream of complete records. */
export type HydrationScriptOutput = {
readonly state: HydrationScriptOutputState
readonly error: unknown
pullChunk: () => Uint8Array
subscribe: (onChange: () => void) => () => void
}
type ConsumerOwnership =
| HydrationScriptOutput
| 'fast-path'
| 'cleaned'
| undefined
/** The one-time initial `<Scripts>` take: hydration tags plus the boundary. */
export type InitialHydrationScriptTags = {
before: Array<RouterManagedTag>
boundary: RouterManagedTag
}
function escapeAttribute(value: string) {
return value.replace(/[&"'<>]/g, (char) => `&#${char.charCodeAt(0)};`)
}
function createInitialTags(
sources: ReadonlyArray<string>,
nonce: string | undefined,
): InitialHydrationScriptTags {
const before: Array<RouterManagedTag> = []
for (const source of sources) {
if (!source) {
continue
}
const previous = before[before.length - 1]
if (
previous?.children &&
previous.children.length + SOURCE_SEPARATOR.length + source.length <=
MAX_INITIAL_SOURCE_CODE_UNITS
) {
previous.children += SOURCE_SEPARATOR + source
} else {
before.push({
tag: 'script',
attrs: { nonce, [STREAM_PART_ATTRIBUTE]: '' },
children: source,
})
}
}
// Cleanup runs before route and asset scripts. If hydration code fails, its
// transport tags can remain because that page cannot hydrate successfully.
const lastHydrationTag = before[before.length - 1]
if (lastHydrationTag) {
const lastSource = lastHydrationTag.children!
if (
lastSource.length + INITIAL_CLEANUP_SUFFIX.length <=
MAX_INITIAL_SOURCE_CODE_UNITS
) {
lastHydrationTag.children = lastSource + INITIAL_CLEANUP_SUFFIX
} else {
// Do not concatenate onto a large source. A renderer could flatten the
// result and temporarily retain a second copy of the hydration payload.
before.push({
tag: 'script',
attrs: { nonce, [STREAM_PART_ATTRIBUTE]: '' },
children: INITIAL_CLEANUP_SOURCE,
})
}
}
return {
before,
boundary: {
tag: 'script',
attrs: { nonce },
children: HYDRATION_SCRIPT_BOUNDARY_SOURCE,
} satisfies RouterManagedTag,
}
}
type HydrationScripts = {
pushSerializedSource: (
data: string,
initial: boolean,
wrap: boolean,
) => boolean
pushSource: (nextSource: string) => boolean
fail: (reason: unknown) => void
finish: () => void
takeInitialHydrationScriptTags: () => InitialHydrationScriptTags | undefined
disableHydration: () => void
isInitialTaken: () => boolean
skipInitialTake: () => void
liftBarrier: () => void
claimOutput: () => HydrationScriptOutput
reserveFastPath: (output?: HydrationScriptOutput) => boolean
startSerializationTimeout: (timeoutMs: number) => void
cleanup: () => void
}
class HydrationScriptsOwner implements HydrationScriptOutput {
private queuedSources: Array<string | undefined> = []
private queuedSourceHead = 0
private initialTaken = false
private barrierLifted = false
private producerDone = false
private consumer: ConsumerOwnership
private listener: (() => void) | undefined
private active: Array<string | undefined> | undefined
private retainedSources = 0
private regularCodeUnits = 0
private hasOversizedSource = false
private segmentIndex = 0
private closingSegmentIndex = 0
private source = ''
private sourceOffset = 0
private outputCapacity = MIN_OUTPUT_BYTES
private outputState: HydrationScriptOutputState =
HydrationScriptOutputState.Waiting
private outputError: unknown
private timeout: ReturnType<typeof setTimeout> | undefined
private opening: string | undefined
constructor(
private readonly nonce: string | undefined,
initialSources?: ReadonlyArray<string>,
) {
// ServerSsr exposes this method as a bare callback, so keep this single
// method bound while all other owner operations live on the prototype.
this.takeInitialHydrationScriptTags =
this.takeInitialHydrationScriptTags.bind(this)
const seedSources = initialSources ?? DEFAULT_INITIAL_SOURCES
for (const seedSource of seedSources) {
if (!this.account(seedSource)) {
break
}
this.queuedSources.push(seedSource)
}
}
get state() {
return this.outputState
}
get error() {
return this.outputError
}
private notify() {
try {
this.listener?.()
} catch (listenerError) {
console.error('Hydration script output listener error:', listenerError)
}
}
private refresh(notifyChange = true) {
const next =
this.outputState === HydrationScriptOutputState.Failed
? HydrationScriptOutputState.Failed
: this.active
? HydrationScriptOutputState.Active
: typeof this.consumer === 'object' &&
this.initialTaken &&
this.barrierLifted &&
!this.queueIsEmpty()
? HydrationScriptOutputState.Ready
: this.producerDone && this.initialTaken && this.queueIsEmpty()
? HydrationScriptOutputState.Done
: HydrationScriptOutputState.Waiting
if (this.outputState !== next) {
this.outputState = next
if (notifyChange) {
this.notify()
}
}
}
private clearTimeoutIfSet() {
if (this.timeout !== undefined) {
clearTimeout(this.timeout)
this.timeout = undefined
}
}
private queueIsEmpty() {
return this.queuedSourceHead === this.queuedSources.length
}
private clearQueue() {
this.queuedSources = []
this.queuedSourceHead = 0
}
private dropBufferedOutput() {
this.clearQueue()
this.active = undefined
this.retainedSources = 0
this.regularCodeUnits = 0
this.hasOversizedSource = false
this.segmentIndex = 0
this.closingSegmentIndex = 0
this.source = ''
this.sourceOffset = 0
this.outputCapacity = MIN_OUTPUT_BYTES
this.opening = undefined
}
fail(reason: unknown) {
if (
this.consumer === 'cleaned' ||
this.outputState === HydrationScriptOutputState.Failed
) {
return
}
this.outputError = reason
this.clearTimeoutIfSet()
this.dropBufferedOutput()
this.outputState = HydrationScriptOutputState.Failed
this.notify()
}
private rejectBacklog(kind: 'source-part' | 'code-unit') {
this.fail(new Error(`SSR hydration backlog exceeded maximum ${kind} count`))
return false
}
private account(nextSource: string) {
if (this.retainedSources === MAX_BACKLOG_SOURCES) {
return this.rejectBacklog('source-part')
}
if (nextSource.length > MAX_BACKLOG_CODE_UNITS) {
if (this.hasOversizedSource) {
return this.rejectBacklog('code-unit')
}
this.hasOversizedSource = true
} else if (
this.regularCodeUnits + nextSource.length >
MAX_BACKLOG_CODE_UNITS
) {
return this.rejectBacklog('code-unit')
} else {
this.regularCodeUnits += nextSource.length
}
this.retainedSources++
return true
}
private releaseSource(part: string) {
this.retainedSources--
if (part.length > MAX_BACKLOG_CODE_UNITS) {
this.hasOversizedSource = false
} else {
this.regularCodeUnits -= part.length
}
}
private releaseAccounting(batch: ReadonlyArray<string | undefined>) {
for (const part of batch) {
if (part !== undefined) {
this.releaseSource(part)
}
}
}
liftBarrier() {
if (this.consumer !== 'cleaned' && !this.barrierLifted) {
this.barrierLifted = true
this.refresh()
}
}
private producerCanWrite() {
return (
this.consumer !== 'cleaned' &&
this.outputState !== HydrationScriptOutputState.Failed &&
!this.producerDone
)
}
pushSource(nextSource: string) {
if (!this.producerCanWrite()) {
return false
}
if (this.account(nextSource)) {
this.queuedSources.push(nextSource)
if (this.initialTaken) {
this.refresh()
}
} else {
return false
}
// A notification can synchronously fail or clean up this owner.
return this.producerCanWrite()
}
private takeQueuedBatch(batchLength: number) {
if (
this.queuedSourceHead === 0 &&
batchLength === this.queuedSources.length
) {
const batch = this.queuedSources
this.clearQueue()
return batch
}
const end = this.queuedSourceHead + batchLength
const batch = this.queuedSources.slice(this.queuedSourceHead, end)
for (let index = this.queuedSourceHead; index < end; index++) {
this.queuedSources[index] = undefined
}
this.queuedSourceHead = end
if (this.queueIsEmpty()) {
this.clearQueue()
} else if (
this.queuedSourceHead >= 1024 &&
this.queuedSourceHead >= this.queuedSources.length - this.queuedSourceHead
) {
this.queuedSources = this.queuedSources.slice(this.queuedSourceHead)
this.queuedSourceHead = 0
}
return batch
}
private release(batch: Array<string | undefined>) {
this.releaseAccounting(batch)
this.active = undefined
this.source = ''
this.sourceOffset = 0
this.refresh(false)
}
private advanceSource() {
const batch = this.active!
if (this.segmentIndex > 0 && this.segmentIndex < this.closingSegmentIndex) {
const partIndex = (this.segmentIndex - 1) >> 1
if (this.segmentIndex % 2 === 1) {
const part = batch[partIndex]
if (part !== undefined) {
this.releaseSource(part)
batch[partIndex] = undefined
}
}
}
this.segmentIndex++
// Segment 0 is the opening tag. Sources and separators alternate until
// the closing segment. The next advance releases the complete record.
if (this.segmentIndex < this.closingSegmentIndex) {
const partIndex = (this.segmentIndex - 1) >> 1
this.source =
this.segmentIndex % 2 === 1 ? batch[partIndex]! : SOURCE_SEPARATOR
} else if (this.segmentIndex === this.closingSegmentIndex) {
this.source = DYNAMIC_CLOSE_SOURCE
} else {
this.release(batch)
}
this.sourceOffset = 0
}
private pullActive() {
const bytes = new Uint8Array(this.outputCapacity)
let offset = 0
while (this.active) {
if (this.sourceOffset === this.source.length) {
this.advanceSource()
} else if (offset === bytes.length) {
break
} else {
const result = encodeIntoBoundedChunk(
this.source,
this.sourceOffset,
bytes,
offset,
)
if (result.read === 0) {
break
}
this.sourceOffset += result.read
offset += result.written
}
}
if (offset === 0) {
throw new Error('SSR router script record produced no output')
}
if (offset === bytes.length) {
return bytes
}
// A subarray view pins the whole output buffer. Copy mostly-empty tail
// chunks (typically the final close-tag remnant) so the large buffer can
// be collected immediately.
return offset * 2 < bytes.length
? bytes.slice(0, offset)
: bytes.subarray(0, offset)
}
private pullReady() {
const scriptOpening = (this.opening ??= this.nonce
? `<script nonce="${escapeAttribute(this.nonce)}">`
: '<script>')
let codeUnits = scriptOpening.length + DYNAMIC_CLOSE_SOURCE.length
let batchLength = 0
for (
let index = this.queuedSourceHead;
index < this.queuedSources.length;
index++
) {
const part = this.queuedSources[index]!
const nextCodeUnits = codeUnits + SOURCE_SEPARATOR.length + part.length
if (batchLength > 0 && nextCodeUnits > MAX_DYNAMIC_RECORD_CODE_UNITS) {
break
}
codeUnits = nextCodeUnits
batchLength++
if (codeUnits > MAX_DYNAMIC_RECORD_CODE_UNITS) {
// A complete JavaScript source is not safely splittable across tags.
break
}
}
const batch = this.takeQueuedBatch(batchLength)
if (codeUnits <= MAX_DIRECT_CODE_UNITS) {
const joined =
batch.length === 1 ? batch[0]! : batch.join(SOURCE_SEPARATOR)
const bytes = encoder.encode(
scriptOpening + joined + SOURCE_SEPARATOR + DYNAMIC_CLOSE_SOURCE,
)
this.release(batch)
return bytes
}
this.active = batch
this.segmentIndex = 0
this.closingSegmentIndex = (batch.length << 1) + 1
this.source = scriptOpening
this.sourceOffset = 0
this.outputCapacity = Math.max(
MIN_OUTPUT_BYTES,
Math.min(MAX_HYDRATION_OUTPUT_CHUNK_BYTES, codeUnits),
)
this.outputState = HydrationScriptOutputState.Active
return this.pullActive()
}
pullChunk() {
if (
this.outputState !== HydrationScriptOutputState.Ready &&
this.outputState !== HydrationScriptOutputState.Active
) {
throw new Error('Hydration script output is not ready')
}
try {
return this.outputState === HydrationScriptOutputState.Ready
? this.pullReady()
: this.pullActive()
} catch (cause) {
this.fail(cause)
throw cause
}
}
subscribe(onChange: () => void) {
if (this.consumer === 'cleaned') {
return () => {}
}
if (this.listener) {
throw new Error('SSR hydration output already has a subscriber')
}
this.listener = onChange
return () => {
if (this.listener === onChange) {
this.listener = undefined
}
}
}
pushSerializedSource(data: string, initial: boolean, wrap: boolean) {
let serialized = initial ? ROUTER_PREFIX + data : data
if (wrap) {
serialized = PROMISE_PREFIX + serialized + ')'
}
return this.pushSource(serialized)
}
finish() {
if (!this.pushSource(GLOBAL_TSR + '.e()')) {
return
}
this.producerDone = true
this.clearTimeoutIfSet()
this.refresh()
}
takeInitialHydrationScriptTags() {
if (
this.consumer === 'cleaned' ||
this.outputState === HydrationScriptOutputState.Failed ||
this.initialTaken
) {
return undefined
}
// No source can drain before the initial take, so the queue has no
// cleared prefix. Once tags are composed, the same empty array can become
// the dynamic queue without allocating a replacement.
const sources = this.queuedSources as Array<string>
const tags = createInitialTags(sources, this.nonce)
this.initialTaken = true
this.releaseAccounting(sources)
sources.length = 0
this.queuedSourceHead = 0
this.refresh()
return tags
}
/**
* Opt this request out of hydration output entirely (for example a
* `hydrate: false` page). Drops the queued bootstrap sources, marks the
* producer done, and makes the fast pass-through path reservable without
* a rendered `<Scripts>` boundary. Must run before the initial take and
* before serialization produces output.
*/
disableHydration() {
if (
this.consumer === 'cleaned' ||
this.outputState === HydrationScriptOutputState.Failed
) {
return
}
if (this.initialTaken || this.consumer !== undefined || this.producerDone) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(
'Invariant failed: hydration output is already committed; ' +
'disableHydration() must run before <Scripts> renders and ' +
'before serialization starts.',
)
}
invariant()
}
this.releaseAccounting(this.queuedSources)
this.clearQueue()
this.initialTaken = true
this.barrierLifted = true
this.producerDone = true
this.refresh()
}
// The rendered boundary can only exist after the initial take. The merger
// uses this to skip barrier scanning for all earlier renderer bytes.
isInitialTaken() {
return this.initialTaken
}
// Application EOF without a rendered <Scripts> boundary. The initial
// sources become late records after the document so the response still
// completes instead of failing after its HTML was already delivered.
skipInitialTake() {
if (this.consumer !== 'cleaned' && !this.initialTaken) {
this.initialTaken = true
this.refresh()
}
}
claimOutput(): HydrationScriptOutput {
if (this.consumer === 'cleaned') {
throw new Error('SSR hydration script output is already cleaned up')
}
if (this.consumer !== undefined) {
throw new Error('SSR hydration script output already has a consumer')
}
this.consumer = this
this.refresh(false)
return this
}
reserveFastPath(output?: HydrationScriptOutput) {
const ownsConsumer = this.consumer === output
if (
this.outputState === HydrationScriptOutputState.Failed ||
!this.producerDone ||
!this.initialTaken ||
!this.queueIsEmpty() ||
this.active ||
!ownsConsumer
) {
return false
}
this.consumer = 'fast-path'
return true
}
// Arms the serialization deadline once the renderer finished. The
// lifecycle signal stays separate from this merge-transport concern.
startSerializationTimeout(timeoutMs: number) {
if (
this.consumer === 'cleaned' ||
this.outputState === HydrationScriptOutputState.Failed ||
this.producerDone ||
this.timeout !== undefined
) {
return
}
this.timeout = setTimeout(() => {
this.timeout = undefined
if (
this.consumer !== 'cleaned' &&
this.outputState !== HydrationScriptOutputState.Failed &&
!this.producerDone
) {
console.error('Serialization timeout after app render finished')
this.fail(new Error('Serialization timeout after app render finished'))
}
}, timeoutMs)
}
cleanup() {
if (this.consumer === 'cleaned') {
return
}
this.consumer = 'cleaned'
this.clearTimeoutIfSet()
this.dropBufferedOutput()
this.listener = undefined
this.outputError = undefined
this.producerDone = true
this.outputState = HydrationScriptOutputState.Done
}
}
/** Create the hydration-script owner for one server request. */
export function createHydrationScripts(
nonce: string | undefined,
initialSources?: ReadonlyArray<string>,
): HydrationScripts {
return new HydrationScriptsOwner(nonce, initialSources)
}
+16
View File
@@ -0,0 +1,16 @@
/**
* @deprecated Use [`Response.json`](https://developer.mozilla.org/en-US/docs/Web/API/Response/json_static) from the standard Web API directly.
*/
export interface JsonResponse<TData> extends Response {
json: () => Promise<TData>
}
/**
* @deprecated Use [`Response.json`](https://developer.mozilla.org/en-US/docs/Web/API/Response/json_static) from the standard Web API directly.
*/
export function json<TData>(
payload: TData,
init?: ResponseInit,
): JsonResponse<TData> {
return Response.json(payload, init)
}
@@ -0,0 +1,29 @@
import { getSsrStatus } from './handlerCallback'
import { transformHtmlStringWithRouter } from './transformStreamWithRouter'
import type { AnyRouter } from '../router'
export async function renderSsrHtmlResponse({
router,
responseHeaders,
render,
}: {
router: AnyRouter
responseHeaders: Headers
render: () => string | Promise<string>
}) {
try {
const html = await transformHtmlStringWithRouter(router, await render())
return new Response(html, {
status: getSsrStatus(router),
headers: responseHeaders,
})
} catch (error) {
console.error('Render to string error:', error)
return new Response('Internal Server Error', {
status: 500,
headers: responseHeaders,
})
} finally {
router.serverSsr?.cleanup()
}
}
+58
View File
@@ -0,0 +1,58 @@
import type { PluginInfo, SerovalNode } from 'seroval'
export type RawStreamHint = 'binary' | 'text'
export interface RawStreamOptions {
/**
* Encoding hint for JSON and SSR serialization.
* - 'binary' (default): Always use base64 encoding
* - 'text': Try UTF-8 first, fallback to base64 for invalid UTF-8 chunks
*/
hint?: RawStreamHint
}
/**
* Marker class for ReadableStream<Uint8Array> that should be serialized
* with base64/text encoding (JSON and SSR) or binary framing
* (server-function responses).
*
* Wrap your binary streams with this to get efficient serialization:
* ```ts
* // For binary data (files, images, etc.)
* return { data: new RawStream(file.stream()) }
*
* // For text-heavy data (RSC payloads, etc.)
* return { data: new RawStream(rscStream, { hint: 'text' }) }
* ```
*
* RawStreams returned from one server function share one ordered response.
* Arbitrary or sequential consumption can require potentially unbounded client
* buffering for unread data. Cancelling one RawStream discards it locally;
* abort the whole server-function call to cancel the response and server work.
* Consume streams concurrently, cancel unused streams promptly, or use separate
* calls when independent backpressure is required.
*/
export class RawStream {
public readonly hint: RawStreamHint
constructor(
public readonly stream: ReadableStream<Uint8Array>,
options?: RawStreamOptions,
) {
this.hint = options?.hint ?? 'binary'
}
}
export type OnRawStreamCallback = (
streamId: number,
stream: ReadableStream<Uint8Array>,
) => void
export interface RawStreamJSONNode extends PluginInfo {
text: SerovalNode
stream: SerovalNode
}
export interface RawStreamRPCNode extends PluginInfo {
streamId: SerovalNode
}
@@ -0,0 +1,64 @@
import { createPlugin } from 'seroval'
import { RawStream } from './RawStream'
import {
decodeText,
encodeText,
fromBase64,
fromEncodedStream,
pumpEncodedStream,
toBase64,
} from './rawStreamCodec'
import type { createStream } from 'seroval'
import type { RawStreamJSONNode } from './RawStream'
/**
* Serializes a RawStream into JSON requests and static-cache responses.
* The optional signal stops the source pump when the request is aborted.
*/
/* @__NO_SIDE_EFFECTS__ */
export function createRawStreamJSONPlugin(signal?: AbortSignal) {
return /* @__PURE__ */ createPlugin<RawStream, RawStreamJSONNode>({
tag: 'tss/RawStream',
test: (value) => value instanceof RawStream,
parse: {
async: async (value, ctx) => {
// Parse the hint before touching the source so a failed parse never
// locks the caller's stream.
const text = await ctx.parse(value.hint === 'text')
const [stream] = pumpEncodedStream(
value.stream,
value.hint === 'text' ? encodeText : toBase64,
signal,
)
return { text, stream: await ctx.parse(stream) }
},
},
serialize: undefined as never,
deserialize: undefined as never,
})
}
export const RawStreamJSONPlugin = /* @__PURE__ */ createRawStreamJSONPlugin()
/**
* Deserializes the JSON shape above back into a `ReadableStream<Uint8Array>`.
* `test` never matches, so this plugin is inert during serialization and can
* share a plugin list with `RawStreamJSONPlugin`.
*/
export const RawStreamJSONDeserializePlugin = /* @__PURE__ */ createPlugin<
ReadableStream<Uint8Array>,
RawStreamJSONNode
>({
tag: 'tss/RawStream',
test: () => false,
parse: {},
serialize: undefined as never,
deserialize(node, ctx) {
return fromEncodedStream(
ctx.deserialize<ReturnType<typeof createStream<string | undefined>>>(
node.stream,
),
ctx.deserialize<boolean>(node.text) ? decodeText : fromBase64,
)
},
})
@@ -0,0 +1,47 @@
import { createPlugin } from 'seroval'
import { RawStream } from './RawStream'
import type { OnRawStreamCallback, RawStreamRPCNode } from './RawStream'
/**
* Server-side RawStream plugin for multiplexed server-function responses.
* The `hint` is ignored: framed responses always carry raw bytes.
*/
/* @__NO_SIDE_EFFECTS__ */
export function createRawStreamRPCPlugin(onRawStream: OnRawStreamCallback) {
let nextStreamId = 1
return /* @__PURE__ */ createPlugin<RawStream, RawStreamRPCNode>({
tag: 'tss/RawStream',
test(value: unknown) {
return value instanceof RawStream
},
parse: {
stream(value, ctx) {
const streamId = nextStreamId++
onRawStream(streamId, value.stream)
return { streamId: ctx.parse(streamId) }
},
},
serialize: undefined as never,
deserialize: undefined as never,
})
}
/** Client-side RawStream plugin for multiplexed server-function responses. */
/* @__NO_SIDE_EFFECTS__ */
export function createRawStreamDeserializePlugin(
getStream: (id: number) => ReadableStream<Uint8Array>,
) {
return /* @__PURE__ */ createPlugin<
ReadableStream<Uint8Array>,
RawStreamRPCNode
>({
tag: 'tss/RawStream',
test: () => false,
parse: {},
serialize: undefined as never,
deserialize(node, ctx) {
return getStream(ctx.deserialize<number>(node.streamId))
},
})
}
@@ -0,0 +1,97 @@
import { createPlugin } from 'seroval'
import { RawStream } from './RawStream'
import { encodeText, pumpEncodedStream, toBase64 } from './rawStreamCodec'
import type { PluginInfo, SerovalNode } from 'seroval'
// This module is server-only. Node's Buffer encodes base64 ~25x faster than
// the web fallback; the view avoids copying the chunk first.
const nodeBuffer: typeof Buffer | undefined = (globalThis as any).Buffer
const toBase64Fast = nodeBuffer
? (bytes: Uint8Array) =>
nodeBuffer
.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)
.toString('base64')
: toBase64
const BINARY_FACTORY = () => {}
const TEXT_FACTORY = () => {}
type RawStreamFactory = typeof BINARY_FACTORY
// These factories are injected into HTML and must be self-contained. Clearing
// both captured values on terminal events releases Seroval's encoded buffer.
const FACTORY_BINARY = `((s,u=1)=>new ReadableStream({start(c,f){f=s.on({next(b){const d=atob(b),a=new Uint8Array(d.length);for(let i=0;i<d.length;i++)a[i]=d.charCodeAt(i);c.enqueue(a)},throw(e){s=u=0;c.error(e)},return(){s=u=0;c.close()}});u=u&&f},cancel(){u&&u()}}))`
const FACTORY_TEXT = `((s,u=1,e=new TextEncoder)=>new ReadableStream({start(c,f){f=s.on({next(v){const x=v.slice(1);if(v[0]==='t')c.enqueue(e.encode(x));else{const d=atob(x),a=new Uint8Array(d.length);for(let i=0;i<d.length;i++)a[i]=d.charCodeAt(i);c.enqueue(a)}},throw(x){s=u=0;c.error(x)},return(){s=u=0;c.close()}});u=u&&f},cancel(){u&&u()}}))`
function makeFactoryPlugin(
tag: string,
sentinel: RawStreamFactory,
source: string,
) {
return createPlugin<RawStreamFactory, PluginInfo>({
tag,
test(value) {
return value === sentinel
},
parse: {
stream() {
return {}
},
},
serialize() {
return source
},
deserialize: undefined as never,
})
}
const RawStreamFactoryBinaryPlugin = /* @__PURE__ */ makeFactoryPlugin(
'tss/RawStreamFactory',
BINARY_FACTORY,
FACTORY_BINARY,
)
const RawStreamFactoryTextPlugin = /* @__PURE__ */ makeFactoryPlugin(
'tss/RawStreamFactoryText',
TEXT_FACTORY,
FACTORY_TEXT,
)
interface RawStreamSSRNode extends PluginInfo {
factory: SerovalNode
stream: SerovalNode
}
/** SSR-only RawStream plugin for streaming JavaScript into HTML. */
export const RawStreamSSRPlugin = /* @__PURE__ */ createPlugin<
RawStream,
RawStreamSSRNode
>({
tag: 'tss/RawStream',
extends: [RawStreamFactoryBinaryPlugin, RawStreamFactoryTextPlugin],
test(value: unknown) {
return value instanceof RawStream
},
parse: {
stream(value, ctx) {
const text = value.hint === 'text'
const factory = ctx.parse(text ? TEXT_FACTORY : BINARY_FACTORY)
const [stream, stop] = pumpEncodedStream(
value.stream,
text ? encodeText : toBase64Fast,
)
ctx.addCleanup(stop)
return { factory, stream: ctx.parse(stream) }
},
},
serialize(node, ctx) {
return (
'(' +
ctx.serialize(node.factory) +
')(' +
ctx.serialize(node.stream) +
')'
)
},
deserialize: undefined as never,
})
@@ -0,0 +1,43 @@
import { createPlugin } from 'seroval'
import type { PluginInfo, SerovalNode } from 'seroval'
export interface ErrorNode extends PluginInfo {
message: SerovalNode
}
/**
* this plugin serializes only the `message` part of an Error
* this helps with serializing e.g. a ZodError which has functions attached that cannot be serialized
*/
export const ShallowErrorPlugin = /* @__PURE__ */ createPlugin<
Error,
ErrorNode
>({
tag: '$TSR/Error',
test(value) {
return value instanceof Error
},
parse: {
sync(value, ctx) {
return {
message: ctx.parse(value.message),
}
},
async async(value, ctx) {
return {
message: await ctx.parse(value.message),
}
},
stream(value, ctx) {
return {
message: ctx.parse(value.message),
}
},
},
serialize(node, ctx) {
return 'new Error(' + ctx.serialize(node.message) + ')'
},
deserialize(node, ctx) {
return new Error(ctx.deserialize(node.message))
},
})
@@ -0,0 +1,31 @@
import { createPlugin } from 'seroval'
import type { AdapterNode, AnySerializationAdapter } from './transformer'
import type { Plugin } from 'seroval'
/** Create a Seroval plugin for client/server symmetric (de)serialization. */
/* @__NO_SIDE_EFFECTS__ */
export function makeSerovalPlugin(
serializationAdapter: AnySerializationAdapter,
): Plugin<any, AdapterNode> {
return /* @__PURE__ */ createPlugin<any, AdapterNode>({
tag: '$TSR/t/' + serializationAdapter.key,
test: serializationAdapter.test,
parse: {
sync(value, ctx) {
return { v: ctx.parse(serializationAdapter.toSerializable(value)) }
},
async async(value, ctx) {
return {
v: await ctx.parse(serializationAdapter.toSerializable(value)),
}
},
stream(value, ctx) {
return { v: ctx.parse(serializationAdapter.toSerializable(value)) }
},
},
serialize: undefined as never,
deserialize(node, ctx) {
return serializationAdapter.fromSerializable(ctx.deserialize(node.v))
},
})
}
@@ -0,0 +1,40 @@
import { createPlugin } from 'seroval'
import { GLOBAL_TSR } from '../constants'
import type { AdapterNode, AnySerializationAdapter } from './transformer'
import type { Plugin } from 'seroval'
/**
* Create a Seroval plugin for server-side serialization only. `tracker.didRun`
* becomes true once the plugin serialized a value.
*/
/* @__NO_SIDE_EFFECTS__ */
export function makeSsrSerovalPlugin(
serializationAdapter: AnySerializationAdapter,
tracker?: { didRun: boolean },
): Plugin<any, AdapterNode> {
return /* @__PURE__ */ createPlugin<any, AdapterNode>({
tag: '$TSR/t/' + serializationAdapter.key,
test: serializationAdapter.test,
parse: {
stream(value, ctx) {
return {
v: ctx.parse(serializationAdapter.toSerializable(value)),
}
},
},
serialize(node, ctx) {
if (tracker) {
tracker.didRun = true
}
return (
GLOBAL_TSR +
'.t.get("' +
serializationAdapter.key +
'")(' +
ctx.serialize(node.v) +
')'
)
},
deserialize: undefined as never,
})
}
@@ -0,0 +1,163 @@
import { createStream } from 'seroval'
// Web-only primitives shared by the JSON and SSR RawStream plugins. This
// module is part of the client bundle: it must not reference `Buffer`, and
// the encode and decode halves must stay independently tree-shakeable.
export function toBase64(bytes: Uint8Array) {
const chunks: Array<string> = []
for (let i = 0; i < bytes.length; i += 0x8000) {
chunks.push(
String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000) as any),
)
}
return btoa(chunks.join(''))
}
export function fromBase64(value: string) {
const binary = atob(value)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i)
}
return bytes
}
const textDecoder = /* @__PURE__ */ new TextDecoder('utf-8', {
fatal: true,
ignoreBOM: true,
})
/** `'t' + utf8` for a valid UTF-8 chunk, otherwise `'b' + base64`. */
export function encodeText(value: Uint8Array) {
try {
return 't' + textDecoder.decode(value)
} catch {
return 'b' + toBase64(value)
}
}
const textEncoder = /* @__PURE__ */ new TextEncoder()
export function decodeText(value: string) {
const data = value.slice(1)
return value[0] === 't' ? textEncoder.encode(data) : fromBase64(data)
}
/**
* Pump a byte stream into a Seroval stream, one encoded chunk per read.
* Returns the Seroval stream and a `stop` function that cancels the reader
* without signalling the Seroval stream; the abort signal and read failures
* stop the pump and throw through the Seroval stream.
*/
export function pumpEncodedStream(
readable: ReadableStream<Uint8Array>,
encode: (value: Uint8Array) => string,
signal?: AbortSignal,
) {
signal?.throwIfAborted()
const stream = createStream<string | undefined>()
const reader = readable.getReader()
let active = true
const release = () => {
active = false
signal?.removeEventListener('abort', abort)
reader.releaseLock()
}
const stop = (reason?: unknown) => {
if (!active) {
return false
}
void reader.cancel(reason).catch(() => {})
release()
return true
}
const abort = () => {
if (stop(signal!.reason)) {
stream.throw(signal!.reason)
}
}
signal?.addEventListener('abort', abort)
;(async () => {
try {
while (active) {
const { done, value } = await reader.read()
if (!active) {
return
}
if (done) {
release()
stream.return(undefined)
return
}
stream.next(encode(value))
}
} catch (error) {
if (stop(error)) {
stream.throw(error)
}
}
})()
return [stream, stop] as const
}
/** Rebuild a byte stream from encoded Seroval stream chunks. */
export function fromEncodedStream(
source: ReturnType<typeof createStream<string | undefined>>,
decode: (value: string) => Uint8Array,
) {
// Dropping the disposer after a terminal event lets Seroval's buffer be
// collected while application code still holds the finished stream.
let unsubscribe: (() => void) | undefined
let done = false
return new ReadableStream<Uint8Array>({
start(controller) {
const dispose = source.on({
next(value) {
if (done) {
return
}
try {
controller.enqueue(decode(value!))
} catch (error) {
// A malformed chunk fails this stream and abandons the source.
done = true
const stop = unsubscribe
unsubscribe = undefined
stop?.()
controller.error(error)
}
},
throw(error) {
if (!done) {
done = true
unsubscribe = undefined
controller.error(error)
}
},
return() {
if (!done) {
done = true
unsubscribe = undefined
controller.close()
}
},
})
if (done) {
dispose()
} else {
unsubscribe = dispose
}
},
cancel() {
const dispose = unsubscribe
unsubscribe = undefined
dispose?.()
},
})
}
@@ -0,0 +1,11 @@
import { ReadableStreamPlugin } from 'seroval-plugins/web'
import { ShallowErrorPlugin } from './ShallowErrorPlugin'
import { RawStreamSSRPlugin } from './RawStreamSSRPlugin'
import type { Plugin } from 'seroval'
/** Server-only plugins for streaming hydration data into HTML. */
export const ssrSerovalPlugins: Array<Plugin<any, any>> = [
ShallowErrorPlugin,
RawStreamSSRPlugin,
ReadableStreamPlugin,
]
@@ -0,0 +1,37 @@
import { ReadableStreamPlugin } from 'seroval-plugins/web'
import { ShallowErrorPlugin } from './ShallowErrorPlugin'
import {
RawStreamJSONDeserializePlugin,
RawStreamJSONPlugin,
createRawStreamJSONPlugin,
} from './RawStreamJSONPlugin'
import type { Plugin } from 'seroval'
/**
* Plugins for JSON transport from a client: serializes RawStream arguments
* and reads plain JSON responses, which never carry RawStream nodes.
*/
/* @__NO_SIDE_EFFECTS__ */
export function createDefaultSerovalPlugins(
signal?: AbortSignal,
): Array<Plugin<any, any>> {
return [
ShallowErrorPlugin,
signal ? createRawStreamJSONPlugin(signal) : RawStreamJSONPlugin,
ReadableStreamPlugin,
]
}
export const defaultSerovalPlugins =
/* @__PURE__ */ createDefaultSerovalPlugins()
/**
* `defaultSerovalPlugins` plus RawStream deserialization, for JSON that may
* carry RawStream nodes: server-function request bodies and cached static
* responses. Seroval deserializes by first tag match, so the deserialize half
* precedes the serialize half; it never matches during serialization.
*/
export const defaultSerovalDeserializerPlugins: Array<Plugin<any, any>> = [
RawStreamJSONDeserializePlugin,
...defaultSerovalPlugins,
]
@@ -0,0 +1,263 @@
import type { PluginInfo, SerovalNode } from 'seroval'
import type {
RegisteredConfigType,
RegisteredSsr,
SSROption,
} from '../../router'
import type { LooseReturnType } from '../../utils'
import type { AnyRoute, ResolveAllSSR } from '../../route'
import type { RawStream } from './RawStream'
declare const TSR_SERIALIZABLE: unique symbol
export type TSR_SERIALIZABLE = typeof TSR_SERIALIZABLE
export type TsrSerializable = { [TSR_SERIALIZABLE]: true }
export interface DefaultSerializable {
number: number
string: string
boolean: boolean
null: null
undefined: undefined
bigint: bigint
Date: Date
Uint8Array: Uint8Array
RawStream: RawStream
TsrSerializable: TsrSerializable
void: void
}
export interface SerializableExtensions extends DefaultSerializable {}
export type Serializable = SerializableExtensions[keyof SerializableExtensions]
export type UnionizeSerializationAdaptersInput<
TAdapters extends ReadonlyArray<AnySerializationAdapter>,
> = TAdapters[number]['~types']['input']
/**
* Create a strongly-typed serialization adapter for SSR hydration.
* Use to register custom types with the router serializer.
*/
export function createSerializationAdapter<
TInput = unknown,
TOutput = unknown,
const TExtendsAdapters extends
| ReadonlyArray<AnySerializationAdapter>
| never = never,
>(
opts: CreateSerializationAdapterOptions<TInput, TOutput, TExtendsAdapters>,
): SerializationAdapter<TInput, TOutput, TExtendsAdapters> {
if (process.env.NODE_ENV !== 'production') {
// Seroval escapes most of these characters before plugin lookup. NUL and
// lone surrogates are transport-unstable. Reject every surrogate code unit
// to keep adapter keys and this development-only check simple.
if (
!opts.key ||
/[\0"\\<\b\t\f\r\n\u2028\u2029\uD800-\uDFFF]/.test(opts.key)
) {
throw new Error(
`createSerializationAdapter: key ${JSON.stringify(opts.key)} is ` +
'invalid. Serialization adapter keys must be non-empty and not ' +
'contain NUL, ", \\, <, backspace, tab, form feed, line ' +
'terminators, or UTF-16 surrogate code units.',
)
}
}
return opts as unknown as SerializationAdapter<
TInput,
TOutput,
TExtendsAdapters
>
}
export interface CreateSerializationAdapterOptions<
TInput,
TOutput,
TExtendsAdapters extends ReadonlyArray<AnySerializationAdapter> | never,
> {
/**
* A non-empty Seroval plugin identifier.
*
* Must not contain NUL, `"`, `\\`, `<`, backspace, tab, form feed, line
* terminators, or UTF-16 surrogate code units. Key validation runs only in
* development.
*/
key: string
extends?: TExtendsAdapters
test: (value: unknown) => value is TInput
toSerializable: (
value: TInput,
) => ValidateSerializable<
TOutput,
Serializable | UnionizeSerializationAdaptersInput<TExtendsAdapters>
>
fromSerializable: (value: TOutput) => TInput
}
export type ValidateSerializable<T, TSerializable> = T extends TSerializable
? T
: T extends (...args: Array<any>) => any
? SerializationError<'Function may not be serializable'>
: T extends RegisteredReadableStream
? SerializationError<'JSX is not be serializable'>
: T extends ReadonlyArray<any>
? ValidateSerializableArray<T, TSerializable>
: T extends Promise<any>
? ValidateSerializablePromise<T, TSerializable>
: T extends ReadableStream<any>
? ValidateReadableStream<T, TSerializable>
: T extends Set<any>
? ValidateSerializableSet<T, TSerializable>
: T extends Map<any, any>
? ValidateSerializableMap<T, TSerializable>
: T extends AsyncGenerator<any, any>
? ValidateSerializableAsyncGenerator<T, TSerializable>
: T extends object
? ValidateSerializableMapped<T, TSerializable>
: SerializationError<'Type may not be serializable'>
export type ValidateSerializableAsyncGenerator<T, TSerializable> =
T extends AsyncGenerator<infer T, infer TReturn, infer TNext>
? AsyncGenerator<
ValidateSerializable<T, TSerializable>,
ValidateSerializable<TReturn, TSerializable>,
TNext
>
: never
export type ValidateSerializablePromise<T, TSerializable> =
T extends Promise<infer TAwaited>
? Promise<ValidateSerializable<TAwaited, TSerializable>>
: never
export type ValidateReadableStream<T, TSerializable> =
T extends ReadableStream<infer TStreamed>
? ReadableStream<ValidateSerializable<TStreamed, TSerializable>>
: never
export type ValidateSerializableSet<T, TSerializable> =
T extends Set<infer TItem>
? Set<ValidateSerializable<TItem, TSerializable>>
: never
export type ValidateSerializableMap<T, TSerializable> =
T extends Map<infer TKey, infer TValue>
? Map<
ValidateSerializable<TKey, TSerializable>,
ValidateSerializable<TValue, TSerializable>
>
: never
export type ValidateSerializableArray<T, TSerializable> = T extends readonly [
any,
...Array<any>,
]
? ValidateSerializableMapped<T, TSerializable>
: T extends Array<infer U>
? Array<ValidateSerializable<U, TSerializable>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<ValidateSerializable<U, TSerializable>>
: never
export type ValidateSerializableMapped<T, TSerializable> = {
[K in keyof T]: ValidateSerializable<T[K], TSerializable>
}
const SERIALIZATION_ERROR = Symbol.for('TSR_SERIALIZATION_ERROR')
export interface SerializationError<in out TMessage extends string> {
[SERIALIZATION_ERROR]: TMessage
}
export interface SerializationAdapter<
TInput,
TOutput,
TExtendsAdapters extends ReadonlyArray<AnySerializationAdapter>,
> {
'~types': SerializationAdapterTypes<TInput, TOutput, TExtendsAdapters>
key: string
extends?: TExtendsAdapters
test: (value: unknown) => value is TInput
toSerializable: (value: TInput) => TOutput
fromSerializable: (value: TOutput) => TInput
}
export interface SerializationAdapterTypes<
TInput,
TOutput,
TExtendsAdapters extends ReadonlyArray<AnySerializationAdapter>,
> {
input: TInput | UnionizeSerializationAdaptersInput<TExtendsAdapters>
output: TOutput
extends: TExtendsAdapters
}
export type AnySerializationAdapter = SerializationAdapter<any, any, any>
export interface AdapterNode extends PluginInfo {
v: SerovalNode
}
export type ValidateSerializableInput<TRegister, T> = ValidateSerializable<
T,
RegisteredSerializableInput<TRegister>
>
export type RegisteredSerializableInput<TRegister> =
| (unknown extends RegisteredSerializationAdapters<TRegister>
? never
: RegisteredSerializationAdapters<TRegister> extends ReadonlyArray<AnySerializationAdapter>
? RegisteredSerializationAdapters<TRegister>[number]['~types']['input']
: never)
| Serializable
export type RegisteredSerializationAdapters<TRegister> = RegisteredConfigType<
TRegister,
'serializationAdapters'
>
export type RegisteredSSROption<TRegister> =
unknown extends RegisteredConfigType<TRegister, 'defaultSsr'>
? SSROption
: RegisteredConfigType<TRegister, 'defaultSsr'>
export type ValidateSerializableLifecycleResult<
TRegister,
TParentRoute extends AnyRoute,
TSSR,
TFn,
> =
false extends RegisteredSsr<TRegister>
? any
: ValidateSerializableLifecycleResultSSR<
TRegister,
TParentRoute,
TSSR,
TFn
> extends infer TInput
? TInput
: never
export type ValidateSerializableLifecycleResultSSR<
TRegister,
TParentRoute extends AnyRoute,
TSSR,
TFn,
> =
ResolveAllSSR<TParentRoute, TSSR> extends false
? any
: RegisteredSSROption<TRegister> extends false
? any
: ValidateSerializableInput<TRegister, LooseReturnType<TFn>>
export type RegisteredReadableStream =
unknown extends SerializerExtensions['ReadableStream']
? never
: SerializerExtensions['ReadableStream']
export interface DefaultSerializerExtensions {
ReadableStream: unknown
}
export interface SerializerExtensions extends DefaultSerializerExtensions {}
+33
View File
@@ -0,0 +1,33 @@
export { createRequestHandler, waitForRequest } from './createRequestHandler'
export type { RequestHandler } from './createRequestHandler'
export {
bindSsrResponseToRequest,
createSsrStreamResponse,
defineHandlerCallback,
disposeSsrResponse,
getSsrStatus,
isSsrResponse,
normalizeSsrResponse,
replaceSsrResponse,
stripSsrResponseBody,
} from './handlerCallback'
export type {
HandlerCallback,
HandlerCallbackResult,
SsrResponse,
} from './handlerCallback'
export {
transformPipeableStreamWithRouter,
transformHtmlStringWithRouter,
transformReadableStreamWithRouter,
} from './transformStreamWithRouter'
export type { TransformStreamWithRouterOptions } from './transformStreamWithRouter'
export { renderSsrHtmlResponse } from './renderSsrHtmlResponse'
export {
attachRouterServerSsrUtils,
getNormalizedURL,
getOrigin,
} from './ssr-server'
export { defaultSerovalDeserializerPlugins } from './serializer/seroval-plugins'
export { createRawStreamRPCPlugin } from './serializer/RawStreamRPCPlugin'
export { makeSsrSerovalPlugin } from './serializer/makeSsrSerovalPlugin'
+1
View File
@@ -0,0 +1 @@
export { hydrate } from '../load-client'
+16
View File
@@ -0,0 +1,16 @@
export function dehydrateSsrMatchId(id: string): string {
return id
.replaceAll('~', '~~')
.replaceAll('\0', '~0')
.replaceAll('\uFFFD', '~r')
.replaceAll('/', '\0')
}
export function hydrateSsrMatchId(id: string): string {
return id
.replaceAll('\0', '/')
.replaceAll('\uFFFD', '/')
.replace(/~([~0r])/g, (_, code) =>
code === '0' ? '\0' : code === 'r' ? '\uFFFD' : code,
)
}
+701
View File
@@ -0,0 +1,701 @@
import { crossSerializeStream } from 'seroval'
import { invariant } from '../invariant'
import {
createInlineCssPlaceholderAsset,
createInlineCssStyleAsset,
getStylesheetHref,
} from '../manifest'
import { decodePath } from '../utils'
import { createSieveCache } from '../sieve-cache'
import { rootRouteId } from '../root'
import { _getRenderedMatches } from '../load-client'
import { waitForReason } from '../await-signal'
import {
SSR_SERIALIZATION_SCOPE_ID,
createHydrationScripts,
} from './hydrationScripts'
import { dehydrateSsrMatchId } from './ssr-match-id'
import { ssrSerovalPlugins } from './serializer/seroval-plugins.ssr'
import { makeSsrSerovalPlugin } from './serializer/makeSsrSerovalPlugin'
import type { SieveCache } from '../sieve-cache'
import type { DehydratedMatch, DehydratedRouter } from './types'
import type { AnyRouter, ServerSsr } from '../router'
import type { AnyRouteMatch } from '../Matches'
import type {
Manifest,
ManifestRoute,
ManifestRouteAssets,
ServerManifest,
} from '../manifest'
type DehydrationPhase = 'idle' | 'started' | 'disabled'
export function dehydrateMatch(match: AnyRouteMatch): DehydratedMatch {
const dehydratedMatch: DehydratedMatch = {
i: dehydrateSsrMatchId(match.id),
u: match.updatedAt,
s: match.status,
}
const properties = [
['__beforeLoadContext', 'b'],
['loaderData', 'l'],
['error', 'e'],
['ssr', 'ssr'],
] as const
for (const [key, shorthand] of properties) {
if (match[key] !== undefined) {
dehydratedMatch[shorthand] = match[key]
}
}
if (match._notFound) {
dehydratedMatch.g = true
}
return dehydratedMatch
}
function disposeSerializationSafely(dispose?: () => void) {
try {
dispose?.()
} catch (err) {
console.error('Error disposing SSR serialization:', err)
}
}
function notifyAndClearListeners<T>(
listeners: Array<(arg: T) => void>,
errorMessage: string,
arg: T,
) {
const pending = listeners.slice()
listeners.length = 0
for (const listener of pending) {
try {
listener(arg)
} catch (error) {
console.error(errorMessage, error)
}
}
}
const isProd = process.env.NODE_ENV === 'production'
type FilteredRoutes = Manifest['routes']
type PreparedMatchedManifestRoutes = {
routes: FilteredRoutes
hasStrippedRoutes: boolean
inlineCssHrefs?: Array<string>
}
type ManifestCache = SieveCache<string, PreparedMatchedManifestRoutes>
const MANIFEST_CACHE_SIZE = 100
const manifestCaches = new WeakMap<ServerManifest, ManifestCache>()
function getManifestCache(manifest: ServerManifest): ManifestCache {
const cache = manifestCaches.get(manifest)
if (cache) {
return cache
}
const newCache = createSieveCache<string, PreparedMatchedManifestRoutes>(
MANIFEST_CACHE_SIZE,
)
manifestCaches.set(manifest, newCache)
return newCache
}
function getInlineCssForPreparedRoutes(
manifest: ServerManifest,
preparedRoutes: PreparedMatchedManifestRoutes,
) {
const styles = manifest.inlineCss?.styles
const hrefs = preparedRoutes.inlineCssHrefs
if (!styles || !hrefs?.length) {
return undefined
}
// Joined once per matched route set and request. Retaining the joined copy
// on the module cache entry would permanently duplicate shared CSS across
// up to MANIFEST_CACHE_SIZE route combinations.
let css = ''
for (const href of hrefs) {
css += styles[href]!
}
return css
}
function getInlineCssAssetForPreparedRoutes(
manifest: ServerManifest,
preparedRoutes: PreparedMatchedManifestRoutes,
) {
const css = getInlineCssForPreparedRoutes(manifest, preparedRoutes)
return css === undefined ? undefined : createInlineCssStyleAsset(css)
}
function getMatchedRoutesCacheKey(matches: Array<AnyRouteMatch>) {
let cacheKey = ''
for (let i = 0; i < matches.length; i++) {
cacheKey += (i === 0 ? '' : '\0') + matches[i]!.routeId
}
return cacheKey
}
function getPreparedMatchedManifestRoutes(
manifest: ServerManifest,
matches: Array<AnyRouteMatch>,
cacheKey: string,
) {
if (isProd) {
const cached = getManifestCache(manifest).get(cacheKey)
if (cached) {
return cached
}
}
const preparedRoutes = prepareMatchedManifestRoutes(manifest, matches)
if (isProd) {
getManifestCache(manifest).set(cacheKey, preparedRoutes)
}
return preparedRoutes
}
function prepareMatchedManifestRoutes(
manifest: ServerManifest,
matches: Array<AnyRouteMatch>,
): PreparedMatchedManifestRoutes {
const inlineStyles = manifest.inlineCss?.styles
const routes: FilteredRoutes = {}
if (!inlineStyles) {
for (const match of matches) {
const route = manifest.routes[match.routeId]
if (route) {
routes[match.routeId] = route
}
}
return { routes, hasStrippedRoutes: false }
}
const inlineCssHrefs: Array<string> = []
const seenInlineCssHrefs = new Set<string>()
let hasStrippedRoutes = false
for (const match of matches) {
const routeId = match.routeId
const route = manifest.routes[routeId]
if (!route) {
continue
}
const nextRoute = stripInlinedStylesheetAssetsFromRoute(
inlineStyles,
route,
inlineCssHrefs,
seenInlineCssHrefs,
)
if (nextRoute !== route) {
hasStrippedRoutes = true
}
routes[routeId] = nextRoute
}
return {
routes,
hasStrippedRoutes,
...(inlineCssHrefs.length ? { inlineCssHrefs } : {}),
}
}
function stripInlinedStylesheetAssetsFromRoute(
inlineStyles: Record<string, string>,
route: ManifestRoute,
inlineCssHrefs: Array<string>,
seenInlineCssHrefs: Set<string>,
): ManifestRoute {
const css = route.css
if (!css) {
return route
}
if (css.length === 0) {
const nextRoute = { ...route }
delete nextRoute.css
return nextRoute
}
let cssLinks: typeof css | undefined
for (let i = 0; i < css.length; i++) {
const link = css[i]!
const href = getStylesheetHref(link)
if (inlineStyles[href] === undefined) {
if (cssLinks) {
cssLinks.push(link)
}
continue
}
if (!seenInlineCssHrefs.has(href)) {
seenInlineCssHrefs.add(href)
inlineCssHrefs.push(href)
}
if (!cssLinks) {
cssLinks = css.slice(0, i)
}
}
if (!cssLinks) {
return route
}
if (cssLinks.length > 0) {
return { ...route, css: cssLinks }
}
const nextRoute = { ...route }
delete nextRoute.css
return nextRoute
}
function hasRouteAssets(route: ManifestRoute) {
return !!route.scripts?.length || !!route.css?.length
}
function hasRequestAssets(assets: ManifestRouteAssets | undefined) {
return !!assets && (!!assets.preloads?.length || hasRouteAssets(assets))
}
function mergeRequestAssetsIntoRootRoute(
rootRoute: ManifestRoute | undefined,
requestAssets: ManifestRouteAssets | undefined,
): ManifestRoute {
const preloads = requestAssets?.preloads?.length
? [...requestAssets.preloads, ...(rootRoute?.preloads ?? [])]
: rootRoute?.preloads
const scripts = requestAssets?.scripts?.length
? [...requestAssets.scripts, ...(rootRoute?.scripts ?? [])]
: rootRoute?.scripts
const cssLinks = requestAssets?.css?.length
? [...requestAssets.css, ...(rootRoute?.css ?? [])]
: rootRoute?.css
return {
...(rootRoute ?? {}),
...(preloads?.length ? { preloads } : {}),
...(scripts?.length ? { scripts } : {}),
...(cssLinks?.length ? { css: cssLinks } : {}),
}
}
/**
* Compose a client-facing manifest from prepared routes, an optional inline
* style, and optional request-scoped assets merged into the root route.
* Shared by the `router.ssr.manifest` getter and `dehydrate()` so the two
* compositions cannot drift.
*/
function composeManifest(
scriptFormat: ServerManifest['scriptFormat'],
inlineStyle: Manifest['inlineStyle'],
routes: FilteredRoutes,
requestAssets: ManifestRouteAssets | undefined,
): Manifest {
const base: Manifest = {
...(scriptFormat ? { scriptFormat } : {}),
...(inlineStyle ? { inlineStyle } : {}),
routes,
}
if (!hasRequestAssets(requestAssets)) {
return base
}
// Merge request-scoped assets into the root route without mutating any
// cached route map.
return {
...base,
routes: {
...routes,
[rootRouteId]: mergeRequestAssetsIntoRootRoute(
routes[rootRouteId],
requestAssets,
),
},
}
}
export function attachRouterServerSsrUtils({
router,
manifest,
getRequestAssets,
}: {
router: AnyRouter
manifest: ServerManifest | undefined
getRequestAssets?: () => ManifestRouteAssets | undefined
}) {
// Inline CSS joining and route filtering depend only on matched route ids,
// so keep that immutable preparation request-local. Request assets can be
// discovered between head and Scripts reads and may mutate in place; always
// compose their current contents instead of caching by object identity.
let memoizedPreparedManifest:
| {
cacheKey: string
inlineCssAsset: Manifest['inlineStyle'] | undefined
routes: FilteredRoutes
}
| undefined
router.ssr = {
get manifest() {
if (!manifest) {
return manifest
}
const requestAssets = getRequestAssets?.()
const hasAssets = hasRequestAssets(requestAssets)
if (!hasAssets && !manifest.inlineCss) {
return manifest
}
let inlineCssAsset: Manifest['inlineStyle'] | undefined
let routes = manifest.routes
if (manifest.inlineCss) {
const matches = _getRenderedMatches(router.stores.matches.get())
const cacheKey = getMatchedRoutesCacheKey(matches)
if (memoizedPreparedManifest?.cacheKey === cacheKey) {
inlineCssAsset = memoizedPreparedManifest.inlineCssAsset
routes = memoizedPreparedManifest.routes
} else {
const preparedManifest = getPreparedMatchedManifestRoutes(
manifest,
matches,
cacheKey,
)
inlineCssAsset = getInlineCssAssetForPreparedRoutes(
manifest,
preparedManifest,
)
if (preparedManifest.hasStrippedRoutes) {
routes = { ...manifest.routes, ...preparedManifest.routes }
}
memoizedPreparedManifest = { cacheKey, inlineCssAsset, routes }
}
}
return composeManifest(
manifest.scriptFormat,
inlineCssAsset,
routes,
hasAssets ? requestAssets : undefined,
)
},
}
let dehydrationPhase: DehydrationPhase = 'idle'
let renderFinished = false
const renderFinishedListeners: Array<() => void> = []
const cleanupListeners: Array<(settled: boolean) => void> = []
let cleanupStarted = false
// Every value the router dehydrated has settled: nothing it started can
// still be pending when the response ends.
let settled = false
let disposeSerialization: (() => void) | undefined
const hydrationScripts = createHydrationScripts(router.options.ssr?.nonce)
const serverSsr: ServerSsr = {
hydrationScripts,
dehydrate: async (opts?: {
requestAssets?: ManifestRouteAssets
signal?: AbortSignal
}) => {
// Guard synchronously before the first await: a concurrent second call
// would double-serialize and corrupt the hydration payload.
if (dehydrationPhase !== 'idle') {
if (process.env.NODE_ENV !== 'production') {
throw new Error(
dehydrationPhase === 'disabled'
? 'Invariant failed: hydration is disabled for this request!'
: 'Invariant failed: router is already dehydrated!',
)
}
invariant()
}
opts?.signal?.throwIfAborted()
dehydrationPhase = 'started'
let matchesToDehydrate = _getRenderedMatches(router.stores.matches.get())
const isShell = router.isShell()
if (isShell) {
// In SPA mode we only want to dehydrate the root match
matchesToDehydrate = matchesToDehydrate.slice(0, 1)
}
const matches = matchesToDehydrate.map(dehydrateMatch)
let manifestToDehydrate: Manifest | undefined = undefined
// Only currently matched routes are dehydrated. Other route assets are
// loaded through dynamic imports when those routes become active.
if (manifest) {
const cacheKey = getMatchedRoutesCacheKey(matchesToDehydrate)
const preparedManifest = getPreparedMatchedManifestRoutes(
manifest,
matchesToDehydrate,
cacheKey,
)
manifestToDehydrate = composeManifest(
manifest.scriptFormat,
preparedManifest.inlineCssHrefs
? createInlineCssPlaceholderAsset()
: undefined,
preparedManifest.routes,
opts?.requestAssets,
)
}
const dehydratedRouter: DehydratedRouter = {
manifest: manifestToDehydrate,
matches,
}
const dehydrate = router.options.dehydrate
const dehydratedData = dehydrate
? opts?.signal
? await waitForReason(dehydrate.call(router.options), opts.signal)
: await dehydrate.call(router.options)
: undefined
opts?.signal?.throwIfAborted()
if (cleanupStarted) {
return
}
if (dehydratedData !== undefined) {
dehydratedRouter.dehydratedData = dehydratedData
}
const trackPlugins = { didRun: false }
const serializationAdapters = router.options.serializationAdapters
const plugins = serializationAdapters
? [
...serializationAdapters.map((adapter) =>
makeSsrSerovalPlugin(adapter, trackPlugins),
),
...ssrSerovalPlugins,
]
: ssrSerovalPlugins
let serializationCompleteSignaled = false
let initialSerialized = false
const completeScriptSerialization = (
result: boolean | { error: unknown },
) => {
if (serializationCompleteSignaled || cleanupStarted) {
return
}
serializationCompleteSignaled = true
const dispose = disposeSerialization
disposeSerialization = undefined
if (result === true) {
settled = true
hydrationScripts.finish()
} else if (result) {
hydrationScripts.fail(result.error)
}
if (dispose) {
// Seroval invokes completion callbacks before it marks its stream as
// inactive. Clear ownership before notifying the hydration consumer,
// which can synchronously clean up this request, then dispose later.
queueMicrotask(() => disposeSerializationSafely(dispose))
}
}
let synchronousFailure: { error: unknown } | undefined
const dispose = crossSerializeStream(dehydratedRouter, {
refs: new Map(),
plugins,
onSerialize: (data, initial) => {
if (serializationCompleteSignaled || cleanupStarted) {
return
}
initialSerialized ||= initial
if (
!hydrationScripts.pushSerializedSource(
data,
initial,
trackPlugins.didRun,
)
) {
// Rejected output stops the producer while deferred work may remain.
completeScriptSerialization(false)
}
},
onError: (err: unknown) => {
if (serializationCompleteSignaled || cleanupStarted) {
return
}
console.error('Serialization error:', err)
synchronousFailure = { error: err }
completeScriptSerialization({ error: err })
},
scopeId: SSR_SERIALIZATION_SCOPE_ID,
onDone: () => {
if (initialSerialized) {
completeScriptSerialization(true)
}
},
})
// Seroval can call onDone synchronously before it returns dispose().
if (cleanupStarted || serializationCompleteSignaled) {
disposeSerializationSafely(dispose)
} else {
disposeSerialization = dispose
}
if (synchronousFailure) {
throw synchronousFailure.error
}
},
onRenderFinished: (listener) => {
if (cleanupStarted) {
return
}
if (renderFinished) {
try {
listener()
} catch (error) {
console.error('Error in render finished listener:', error)
}
return
}
renderFinishedListeners.push(listener)
},
onCleanup: (listener) => {
if (cleanupStarted) {
// Cleanup already happened (or is running). Invoke immediately so
// late registrants can still release their resources instead of
// silently retaining them (standard disposer convention).
try {
listener(settled)
} catch (error) {
console.error('Error in SSR cleanup listener:', error)
}
return
}
cleanupListeners.push(listener)
},
setRenderFinished: () => {
if (cleanupStarted || renderFinished) {
return
}
renderFinished = true
hydrationScripts.liftBarrier()
notifyAndClearListeners(
renderFinishedListeners,
'Error in render finished listener:',
undefined,
)
},
disableHydration: () => {
if (cleanupStarted || dehydrationPhase === 'disabled') {
return
}
if (dehydrationPhase !== 'idle') {
if (process.env.NODE_ENV !== 'production') {
throw new Error(
'Invariant failed: cannot disable hydration after dehydrate()!',
)
}
invariant()
}
// The owner rejects later takes/claims; guard order matters so a
// throwing owner does not leave the phase half-set.
hydrationScripts.disableHydration()
dehydrationPhase = 'disabled'
},
takeInitialHydrationScriptTags:
hydrationScripts.takeInitialHydrationScriptTags,
cleanup() {
// Guard against multiple/reentrant cleanup calls. A listener could call
// cleanup() again indirectly; snapshot + clear before invoking so each
// listener runs exactly once and reentry is a no-op.
if (cleanupStarted) {
return
}
cleanupStarted = true
hydrationScripts.cleanup()
const dispose = disposeSerialization
disposeSerialization = undefined
disposeSerializationSafely(dispose)
notifyAndClearListeners(
cleanupListeners,
'Error in SSR cleanup listener:',
settled,
)
renderFinishedListeners.length = 0
router.ssr = undefined
router.serverSsr = undefined
},
}
router.serverSsr = serverSsr
for (const listener of router.serverSsrLifecycle?.onServerSsrAttach ?? []) {
try {
listener(serverSsr)
} catch (err) {
console.error('SSR attach listener error:', err)
}
}
}
/**
* Get the origin for the request.
*
* SECURITY: We intentionally do NOT trust the Origin header for determining
* the router's origin. The Origin header can be spoofed by attackers, which
* could lead to SSRF-like vulnerabilities where redirects are constructed
* using a malicious origin (CVE-2024-34351).
*
* Instead, we derive the origin from request.url, which is typically set by
* the server infrastructure (not client-controlled headers).
*
* For applications behind proxies that need to trust forwarded headers,
* use the router's `origin` option to explicitly configure a trusted origin.
*/
export function getOrigin(request: Request) {
try {
return new URL(request.url).origin
} catch {}
return 'http://localhost'
}
// server and browser can decode/encode characters differently in paths and search params.
// Server generally strictly follows the WHATWG URL Standard, while browsers may differ for legacy reasons.
// 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.
// Another anomaly is that in Node new URLSearchParams and new URL also decode/encode characters differently.
// new URLSearchParams() encodes "|" while new URL() does not, and in this instance
// chromium treats search params differently than paths, i.e. "|" is not encoded in search params.
export function getNormalizedURL(url: string | URL, base?: string | URL) {
// ensure backslashes are encoded correctly in the URL
if (typeof url === 'string') {
url = url.replace('\\', '%5C')
}
const rawUrl = new URL(url, base)
// URL parsing has already handled backslashes and ignored controls. A pathname
// like "//evil.example" would become a protocol-relative URL when rebuilt below.
const handledProtocolRelativeURL = rawUrl.pathname.startsWith('//')
const decodedPathname = decodePath(
handledProtocolRelativeURL
? rawUrl.pathname.replace(/^\/+/, '/')
: rawUrl.pathname,
)
const searchParams = new URLSearchParams(rawUrl.search)
const normalizedHref =
decodedPathname +
(searchParams.size > 0 ? '?' : '') +
searchParams.toString() +
rawUrl.hash
return {
url: new URL(normalizedHref, rawUrl.origin),
handledProtocolRelativeURL,
}
}
@@ -0,0 +1,967 @@
import { Readable } from 'node:stream'
import {
DOCUMENT_CLOSE_ANCHOR_INDEX,
DOCUMENT_CLOSE_BYTES,
SCRIPT_CLOSE_ANCHOR_INDEX,
SCRIPT_CLOSE_BYTES,
advanceByteMatcher,
encodeIntoBoundedChunk,
findExactBytes,
getExactBytesPrefixAtEnd,
} from './htmlBoundaryScanner'
import {
HYDRATION_SCRIPT_BOUNDARY_ANCHOR_INDEX,
HYDRATION_SCRIPT_BOUNDARY_BYTES,
HydrationScriptOutputState,
} from './hydrationScripts'
import type { ReadableStream as NodeReadableStream } from 'node:stream/web'
import type { AnyRouter } from '../router'
import type { ByteMatcherState } from './htmlBoundaryScanner'
import type { HydrationScriptOutput } from './hydrationScripts'
export type TransformStreamWithRouterOptions = {
/** Timeout for serialization to complete after app render finishes (default: 60000ms) */
timeoutMs?: number
/** Maximum lifetime of the stream transform. Defaults to twice timeoutMs. */
lifetimeMs?: number
/** Cancels the transform and releases SSR state when the request ends. */
signal?: AbortSignal
/**
* Additional point after which the renderer guarantees that a router script
* can be inserted. This is an adapter contract, not a user streaming policy.
* The router boundary, canonical document close, and EOF are always safe.
*/
rendererSafePoint?: 'script-close' | 'record-end'
/**
* Called exactly once when the stream is torn down due to abort/error/
* cancel/timeout — NOT on natural successful completion. Use this to
* abort a hidden producer upstream of any stream passed to this transform.
* Errors thrown from this callback are swallowed.
*/
onAbort?: (reason?: unknown) => void
}
type AppStreamValue = Uint8Array | string
/** Renderer output: UTF-8 bytes, or string records from a Node pipeable. */
type AppStream =
| ReadableStream<Uint8Array>
| ReadableStream<string>
| ReadableStream<AppStreamValue>
| NodeReadableStream<AppStreamValue>
export function transformPipeableStreamWithRouter(
router: AnyRouter,
routerStream: Readable,
opts?: TransformStreamWithRouterOptions,
) {
return Readable.fromWeb(
transformReadableStreamWithRouter(
router,
Readable.toWeb(routerStream) as AppStream,
opts,
) as NodeReadableStream<Uint8Array>,
)
}
export async function transformHtmlStringWithRouter(
router: AnyRouter,
html: string,
opts?: TransformStreamWithRouterOptions,
) {
const serverSsr = router.serverSsr
if (!serverSsr) {
throw new Error('Invariant failed: router.serverSsr is required')
}
const hydrationScripts = serverSsr.hydrationScripts
if (hydrationScripts.reserveFastPath()) {
try {
opts?.signal?.throwIfAborted()
serverSsr.setRenderFinished()
return '<!DOCTYPE html>' + html
} catch (error) {
try {
opts?.onAbort?.(error)
} catch {
// User cleanup must not block SSR cleanup.
}
throw error
} finally {
serverSsr.cleanup()
}
}
// The merge path chunks string records itself.
const appStream = new ReadableStream<string>({
start(controller) {
controller.enqueue('<!DOCTYPE html>')
controller.enqueue(html)
controller.close()
},
})
const output = transformReadableStreamWithRouter(router, appStream, opts)
return readUtf8Stream(output)
}
async function readUtf8Stream(stream: ReadableStream<Uint8Array>) {
const reader = stream.getReader()
const decoder = new TextDecoder()
let text = ''
try {
for (;;) {
const { done, value } = await reader.read()
if (done) {
break
}
text += decoder.decode(value, { stream: true })
}
return text + decoder.decode()
} finally {
reader.releaseLock()
}
}
const DEFAULT_SERIALIZATION_TIMEOUT_MS = 60_000
const MIN_APPLICATION_STRING_CHUNK_BYTES = 256
const MAX_APPLICATION_STRING_CHUNK_BYTES = 64 * 1024
const ApplicationPhase = {
BeforeBoundary: 0,
Merge: 1,
HeldClose: 2,
PassThrough: 3,
} as const
type ApplicationPhase = (typeof ApplicationPhase)[keyof typeof ApplicationPhase]
type Termination = 'complete' | 'cancel' | 'failure'
type AppStreamReader = ReadableStreamDefaultReader<AppStreamValue>
function releaseReader(reader: AppStreamReader) {
try {
reader.releaseLock()
} catch {
// A nonstandard reader may still reject lock release.
}
}
function cancelReader(reader: AppStreamReader, reason?: unknown) {
const cancelled = reader.cancel(reason).catch(() => {})
// Native readers close synchronously when cancel() starts. Release the lock
// before an arbitrary underlying cancel promise has a chance to park.
releaseReader(reader)
return cancelled
}
function finalizeSsrStream(
kind: Termination,
reason: unknown,
controller: ReadableStreamDefaultController<Uint8Array>,
reader: AppStreamReader,
serverSsr: NonNullable<AnyRouter['serverSsr']>,
onAbort?: (reason?: unknown) => void,
) {
try {
if (kind === 'complete') {
controller.close()
} else if (kind === 'failure') {
controller.error(reason)
}
} catch {
// The stream already reached a terminal state.
}
const aborted = kind !== 'complete'
if (aborted) {
try {
onAbort?.(reason)
} catch {
// User cleanup must not block SSR cleanup.
}
}
const readerDone = aborted
? cancelReader(reader, reason)
: releaseReader(reader)
serverSsr.cleanup()
return readerDone
}
function getLifetimeMs(opts?: TransformStreamWithRouterOptions) {
return (
opts?.lifetimeMs ??
(opts?.timeoutMs ?? DEFAULT_SERIALIZATION_TIMEOUT_MS) * 2
)
}
// External serverSsr.cleanup() severs router ownership. The transform must
// release the renderer, timers, listeners, and buffers immediately instead of
// retaining them until the lifetime backstop fires. AbortError identifies this
// intentional cancellation to downstream consumers.
function createCleanupAbortError() {
const error = new Error('SSR stream transform aborted by router SSR cleanup')
error.name = 'AbortError'
return error
}
function listenForAbort(
signal: AbortSignal | undefined,
onAbort: (reason: unknown) => void,
) {
if (!signal) {
return undefined
}
const listener = () => onAbort(signal.reason)
signal.addEventListener('abort', listener, { once: true })
return () => signal.removeEventListener('abort', listener)
}
/**
* Create a timer that does not keep the Node.js process alive when this
* last-resort stream backstop is the only remaining work.
*
* Node's global `setTimeout()` returns a `Timeout` object with `unref()`.
* Web-standard runtimes return a numeric timer ID instead. Cloudflare Workers
* retain that Web behavior for global timers even when `nodejs_compat` is
* enabled. Accessing an optional property on a numeric ID is safe, so timer
* creation can normalize the Node-only capability without allocating a
* wrapper object. The native handle is returned unchanged for `clearTimeout`.
*/
function setUnrefTimeout(callback: () => void, timeoutMs: number) {
const handle = setTimeout(callback, timeoutMs)
const portableHandle = handle as typeof handle & { unref?: () => void }
portableHandle.unref?.()
return handle
}
/**
* Arm the shared teardown triggers of a transform stream: the lifetime
* backstop timer, the request-abort listener, and the external-cleanup
* listener. Returns a disarm function that `terminate()` calls exactly once;
* teardown ordering must stay identical between the fast and merge paths.
*/
function armStreamLifecycle(
serverSsr: NonNullable<AnyRouter['serverSsr']>,
opts: TransformStreamWithRouterOptions | undefined,
isTerminal: () => boolean,
terminate: (kind: Termination, reason?: unknown) => unknown,
) {
const signal = opts?.signal
let lifetimeTimeoutHandle: ReturnType<typeof setTimeout> | undefined
let stopAbortListener: (() => void) | undefined
const disarm = () => {
stopAbortListener?.()
stopAbortListener = undefined
if (signal && serverSsr.hydrationScripts.requestSignal === signal) {
serverSsr.hydrationScripts.requestSignal = undefined
}
if (lifetimeTimeoutHandle !== undefined) {
clearTimeout(lifetimeTimeoutHandle)
lifetimeTimeoutHandle = undefined
}
}
const lifetimeMs = getLifetimeMs(opts)
lifetimeTimeoutHandle = setUnrefTimeout(() => {
if (isTerminal()) {
return
}
const error = new Error('Stream lifetime exceeded')
console.warn(
`SSR stream transform exceeded maximum lifetime (${lifetimeMs}ms), forcing cleanup`,
)
terminate('failure', error)
}, lifetimeMs)
stopAbortListener = listenForAbort(signal, (reason) => {
terminate('failure', reason)
})
if (signal) {
serverSsr.hydrationScripts.requestSignal = signal
}
// External serverSsr.cleanup() must release the reader, renderer, timer,
// and buffers promptly — a parked pump only wakes through its own
// subscriptions, and a discarded response never pulls at all.
serverSsr.onCleanup(() => {
if (!isTerminal()) {
terminate('failure', createCleanupAbortError())
}
})
return disarm
}
function cleanupFailedStreamCreation(
serverSsr: NonNullable<AnyRouter['serverSsr']>,
onAbort: TransformStreamWithRouterOptions['onAbort'],
error: unknown,
) {
try {
onAbort?.(error)
} catch {
// User cleanup must not block SSR cleanup.
}
serverSsr.cleanup()
}
function encodeStringSource(value: string, offset: number) {
const remaining = value.length - offset
const capacity = Math.min(
MAX_APPLICATION_STRING_CHUNK_BYTES,
Math.max(
MIN_APPLICATION_STRING_CHUNK_BYTES,
Math.min(value.length, remaining * 3),
),
)
const output = new Uint8Array(capacity)
const { read, written } = encodeIntoBoundedChunk(value, offset, output)
return {
bytes: written === output.length ? output : output.subarray(0, written),
read,
}
}
export function transformReadableStreamWithRouter(
router: AnyRouter,
appStream: AppStream,
opts?: TransformStreamWithRouterOptions,
) {
const serverSsr = router.serverSsr
if (!serverSsr) {
throw new Error('Invariant failed: router.serverSsr is required')
}
const hydrationScripts = serverSsr.hydrationScripts
let reader: AppStreamReader
try {
reader = appStream.getReader() as AppStreamReader
} catch (error) {
cleanupFailedStreamCreation(serverSsr, opts?.onAbort, error)
throw error
}
try {
opts?.signal?.throwIfAborted()
if (hydrationScripts.reserveFastPath()) {
// Hydration already drained: pass application output through from the
// first byte. The merge stream handles this with the same pass-through
// it uses after hydration finishes mid-stream.
return makeMergeStream(serverSsr, reader, undefined, opts)
}
const hydrationOutput = hydrationScripts.claimOutput()
if (hydrationOutput.state === HydrationScriptOutputState.Failed) {
throw hydrationOutput.error
}
return makeMergeStream(serverSsr, reader, hydrationOutput, opts)
} catch (error) {
void cancelReader(reader, error)
cleanupFailedStreamCreation(serverSsr, opts?.onAbort, error)
throw error
}
}
// The merge path searches only router- and renderer-owned ASCII delimiters.
// Application bytes otherwise leave through zero-copy subarray views.
// Without a hydration output the stream starts in pass-through.
function makeMergeStream(
serverSsr: NonNullable<AnyRouter['serverSsr']>,
reader: AppStreamReader,
hydrationOutput: HydrationScriptOutput | undefined,
opts?: TransformStreamWithRouterOptions,
) {
const hydrationScripts = serverSsr.hydrationScripts
let controller!: ReadableStreamDefaultController<Uint8Array>
let terminal = false
let appDone = false
let applicationPhase: ApplicationPhase = hydrationOutput
? ApplicationPhase.BeforeBoundary
: ApplicationPhase.PassThrough
let insertionBoundary = false
let stopHydrationOutputListener: (() => void) | undefined
let appReadPending = false
let settledAppRead: ReadableStreamReadValueResult<AppStreamValue> | undefined
let appBytes: Uint8Array | undefined
let appOffset = 0
let documentCloseIndex: number | undefined
let appString: string | undefined
let appStringOffset = 0
const useScriptCloseSafePoints = opts?.rendererSafePoint === 'script-close'
const useRecordEndSafePoints = opts?.rendererSafePoint === 'record-end'
// Both matchers are created on first use; pass-through never needs them.
let barrierMatcher: ByteMatcherState | undefined
let safePointMatcher: ByteMatcherState | undefined
// Split document closes carry at most 13 bytes across chunks. This uses
// findExactBytes + getExactBytesPrefixAtEnd instead of advanceByteMatcher
// because `</body></html>` repeats its first byte (`<` at 0 and 7), which
// violates the matcher's unique-first-byte resync precondition.
let closeCarry: Uint8Array | undefined
let wakeResolve: (() => void) | undefined
// Assigned after the stream exists; `terminate` can run before that when an
// already-cleaned owner fires its cleanup listener synchronously.
let disarmLifecycle = (): void => {}
function waitForWake() {
return new Promise<void>((resolve) => {
wakeResolve = resolve
})
}
function wakePump() {
const resolve = wakeResolve
wakeResolve = undefined
resolve?.()
}
// Returns true when a chunk was enqueued. Every process* function
// propagates this boolean so pump() emits at most one chunk per downstream
// pull — the backpressure contract of this transform.
function enqueueAppBytes(value: Uint8Array) {
if (value.length === 0) {
return false
}
controller.enqueue(value)
return true
}
function finishAppChunk() {
appBytes = undefined
documentCloseIndex = undefined
if (
appString === undefined &&
useRecordEndSafePoints &&
closeCarry === undefined
) {
insertionBoundary = true
}
}
function emitAppRange(
end: number,
safePoint: boolean,
finishCurrentChunk = end === appBytes!.length,
) {
const value = appBytes!
const output =
appOffset === 0 && end === value.length
? value
: value.subarray(appOffset, end)
appOffset = end
if (safePoint) {
insertionBoundary = true
}
if (finishCurrentChunk) {
finishAppChunk()
}
return enqueueAppBytes(output)
}
function loadNextAppStringChunk() {
const value = appString!
const encoded = encodeStringSource(value, appStringOffset)
appStringOffset += encoded.read
appBytes = encoded.bytes
appOffset = 0
if (appStringOffset === value.length) {
appString = undefined
}
}
function processUntilBarrier() {
const value = appBytes!
if (!hydrationScripts.isInitialTaken()) {
// The rendered boundary can only exist after the initial script take,
// so earlier renderer bytes pass through without scanning. This skips
// the barrier scan for the whole pre-<Scripts> document and prevents
// barrier-lookalike bytes in application content from lifting the
// barrier early.
return emitAppRange(value.length, false)
}
const matchEnd = advanceByteMatcher(
(barrierMatcher ??= {
pattern: HYDRATION_SCRIPT_BOUNDARY_BYTES,
anchorIndex: HYDRATION_SCRIPT_BOUNDARY_ANCHOR_INDEX,
matched: 0,
}),
value,
appOffset,
)
if (matchEnd === undefined) {
return emitAppRange(value.length, false)
}
applicationPhase = ApplicationPhase.Merge
hydrationScripts.liftBarrier()
return emitAppRange(matchEnd, true)
}
// Advance past a canonical close that ends `consumed` bytes into the current
// chunk and hold it until the transform completes.
function enterHeldClose(consumed: number, prefix: Uint8Array | undefined) {
appOffset = consumed
applicationPhase = ApplicationPhase.HeldClose
if (safePointMatcher) {
// The removed close breaks byte continuity with later renderer bytes.
safePointMatcher.matched = 0
}
insertionBoundary = true
if (appOffset === appBytes!.length) {
finishAppChunk()
}
return prefix ? enqueueAppBytes(prefix) : false
}
function holdDocumentClose(matchStart: number) {
const value = appBytes!
return enterHeldClose(
matchStart + DOCUMENT_CLOSE_BYTES.length,
matchStart === appOffset
? undefined
: value.subarray(appOffset, matchStart),
)
}
function processUntilSafePoint(endIndex: number) {
const value = appBytes!
const matchEnd = findSafePointEnd(value, appOffset, endIndex)
if (matchEnd === undefined) {
return false
}
return emitAppRange(matchEnd, true)
}
function findSafePointEnd(
value: Uint8Array,
startIndex: number,
endIndex: number,
) {
// Merge-only: pass-through never scans for safe points.
const hydrationState = hydrationOutput!.state
if (
endIndex === startIndex ||
hydrationState === HydrationScriptOutputState.Done
) {
return undefined
}
const scanValue =
endIndex === value.length ? value : value.subarray(0, endIndex)
const matcher = (safePointMatcher ??= {
pattern: SCRIPT_CLOSE_BYTES,
anchorIndex: SCRIPT_CLOSE_ANCHOR_INDEX,
matched: 0,
})
// Active drains before app bytes, Done is excluded above, and Failed
// terminates through the subscriber; only Ready and Waiting reach here.
const waiting = hydrationState === HydrationScriptOutputState.Waiting
const matchEnd = advanceByteMatcher(matcher, scanValue, startIndex, waiting)
if (matchEnd === undefined) {
return undefined
}
if (waiting) {
// Bytes after the last match are processed again on the next pull.
matcher.matched = 0
}
return matchEnd
}
function processCloseCarry() {
const value = appBytes!
const carry = closeCarry!
const headLength = Math.min(
value.length - appOffset,
DOCUMENT_CLOSE_BYTES.length,
)
const combined = new Uint8Array(carry.length + headLength)
combined.set(carry)
combined.set(
value.subarray(appOffset, appOffset + headLength),
carry.length,
)
const matchStart = findExactBytes(
combined,
DOCUMENT_CLOSE_BYTES,
0,
DOCUMENT_CLOSE_ANCHOR_INDEX,
)
const partial =
matchStart < 0
? getExactBytesPrefixAtEnd(combined, DOCUMENT_CLOSE_BYTES)
: undefined
const safeEnd = matchStart >= 0 ? matchStart : (partial ?? combined.length)
if (useScriptCloseSafePoints) {
const safePointEnd = findSafePointEnd(combined, 0, safeEnd)
if (safePointEnd !== undefined) {
appOffset += safePointEnd - carry.length
closeCarry = undefined
insertionBoundary = true
if (appOffset === value.length) {
finishAppChunk()
}
return enqueueAppBytes(combined.subarray(0, safePointEnd))
}
}
if (matchStart >= 0) {
closeCarry = undefined
return enterHeldClose(
appOffset + matchStart + DOCUMENT_CLOSE_BYTES.length - carry.length,
matchStart === 0 ? undefined : combined.subarray(0, matchStart),
)
}
closeCarry = partial === undefined ? undefined : combined.slice(partial)
appOffset += headLength
return enqueueAppBytes(
safeEnd === combined.length ? combined : combined.subarray(0, safeEnd),
)
}
function processUntilDocumentClose() {
const value = appBytes!
if (closeCarry) {
if (processCloseCarry()) {
return true
}
if (applicationPhase === ApplicationPhase.HeldClose) {
return false
}
if (appOffset >= value.length) {
finishAppChunk()
return false
}
}
// Safe points only advance within this chunk, so keep its close or miss.
const matchStart = (documentCloseIndex ??= findExactBytes(
value,
DOCUMENT_CLOSE_BYTES,
appOffset,
DOCUMENT_CLOSE_ANCHOR_INDEX,
))
if (matchStart >= 0) {
if (useScriptCloseSafePoints && processUntilSafePoint(matchStart)) {
return true
}
return holdDocumentClose(matchStart)
}
const partial = getExactBytesPrefixAtEnd(
value,
DOCUMENT_CLOSE_BYTES,
appOffset,
)
const safeEnd = partial ?? value.length
if (useScriptCloseSafePoints && processUntilSafePoint(safeEnd)) {
return true
}
closeCarry = partial === undefined ? undefined : value.slice(partial)
return emitAppRange(safeEnd, false, true)
}
function processAppChunk() {
if (appOffset >= appBytes!.length) {
finishAppChunk()
return false
}
insertionBoundary = false
if (applicationPhase === ApplicationPhase.BeforeBoundary) {
return processUntilBarrier()
}
if (applicationPhase === ApplicationPhase.Merge) {
return processUntilDocumentClose()
}
const value = appBytes!
if (useScriptCloseSafePoints && processUntilSafePoint(value.length)) {
return true
}
return emitAppRange(value.length, false)
}
function terminate(kind: Termination, reason?: unknown) {
if (terminal) {
return
}
terminal = true
stopHydrationOutputListener?.()
stopHydrationOutputListener = undefined
disarmLifecycle()
settledAppRead = undefined
appBytes = undefined
documentCloseIndex = undefined
appString = undefined
closeCarry = undefined
wakePump()
return finalizeSsrStream(
kind,
reason,
controller,
reader,
serverSsr,
opts?.onAbort,
)
}
function startAppRead() {
if (appReadPending || settledAppRead || terminal) {
return
}
appReadPending = true
void reader.read().then(
(result) => {
appReadPending = false
if (!terminal) {
if (result.done) {
acceptAppRead(result)
} else {
settledAppRead = result
}
wakePump()
}
},
(error) => {
appReadPending = false
if (!terminal) {
handlePumpError(error)
}
},
)
}
function acceptAppRead(result: ReadableStreamReadResult<AppStreamValue>) {
if (result.done) {
appDone = true
insertionBoundary = closeCarry === undefined
// The serialization deadline is a transport concern of this merge
// path; the lifecycle signal below stays a plain notification.
hydrationScripts.startSerializationTimeout(
opts?.timeoutMs ?? DEFAULT_SERIALIZATION_TIMEOUT_MS,
)
serverSsr.setRenderFinished()
return
}
const value = result.value
if (typeof value === 'string') {
if (value.length === 0) {
return
}
appString = value
appStringOffset = 0
insertionBoundary = false
loadNextAppStringChunk()
return
}
if (value.byteLength === 0) {
return
}
appBytes = value
appOffset = 0
insertionBoundary = false
}
async function loadNextAppChunk() {
if (appString !== undefined) {
loadNextAppStringChunk()
return
}
if (settledAppRead) {
const settled = settledAppRead
settledAppRead = undefined
acceptAppRead(settled)
return
}
const scriptsCanInterruptRead =
applicationPhase !== ApplicationPhase.BeforeBoundary &&
insertionBoundary &&
hydrationOutput!.state !== HydrationScriptOutputState.Done
if (!scriptsCanInterruptRead && !appReadPending) {
const result = await reader.read()
if (terminal) {
return
}
acceptAppRead(result)
return
}
const wake = waitForWake()
startAppRead()
await wake
}
// Pass-through forwards application records unchanged and only encodes
// string records; it skips the merge bookkeeping entirely.
async function pumpPassThrough() {
try {
for (;;) {
if (appBytes) {
const remainder =
appOffset === 0 ? appBytes : appBytes.subarray(appOffset)
appBytes = undefined
if (enqueueAppBytes(remainder)) {
return
}
continue
}
if (appString !== undefined) {
loadNextAppStringChunk()
continue
}
if (appDone) {
terminate('complete')
return
}
if (appReadPending) {
// A merge-phase prefetch is still in flight; it wakes the pump.
await waitForWake()
continue
}
let result: ReadableStreamReadResult<AppStreamValue> | undefined =
settledAppRead
if (result) {
settledAppRead = undefined
} else {
result = await reader.read()
if (terminal) {
return
}
}
if (result.done || typeof result.value === 'string') {
acceptAppRead(result)
continue
}
if (result.value.byteLength > 0) {
controller.enqueue(result.value)
return
}
}
} catch (error) {
handlePumpError(error)
}
}
async function pump() {
const output = hydrationOutput!
while (!terminal) {
const hydrationState = output.state
if (hydrationState === HydrationScriptOutputState.Active) {
controller.enqueue(output.pullChunk())
return
}
if (
applicationPhase !== ApplicationPhase.BeforeBoundary &&
insertionBoundary &&
hydrationState === HydrationScriptOutputState.Ready
) {
if (!appDone && !appBytes && appString === undefined) {
startAppRead()
}
controller.enqueue(output.pullChunk())
return
}
if (
applicationPhase === ApplicationPhase.Merge &&
hydrationState === HydrationScriptOutputState.Done &&
closeCarry === undefined &&
hydrationScripts.reserveFastPath(output)
) {
applicationPhase = ApplicationPhase.PassThrough
stopHydrationOutputListener?.()
stopHydrationOutputListener = undefined
return pumpPassThrough()
}
if (appBytes) {
if (processAppChunk()) {
return
}
continue
}
if (appDone) {
if (applicationPhase === ApplicationPhase.BeforeBoundary) {
// No <Scripts> boundary was rendered. The document is already
// delivered, so emit the hydration sources after it instead of
// failing the response.
hydrationScripts.skipInitialTake()
applicationPhase = ApplicationPhase.Merge
insertionBoundary = true
continue
}
if (closeCarry) {
// A close prefix that never completed is ordinary content, exactly
// like a document without a canonical close.
const carry = closeCarry
closeCarry = undefined
insertionBoundary = true
if (enqueueAppBytes(carry)) {
return
}
continue
}
if (hydrationState === HydrationScriptOutputState.Waiting) {
await waitForWake()
continue
}
if (applicationPhase === ApplicationPhase.HeldClose) {
controller.enqueue(DOCUMENT_CLOSE_BYTES.slice())
terminate('complete')
return
}
terminate('complete')
return
}
await loadNextAppChunk()
}
}
function handlePumpError(error: unknown) {
if (terminal) {
return
}
console.error('Error processing appStream:', error)
terminate('failure', error)
}
const stream = new ReadableStream<Uint8Array>({
start(c) {
controller = c
},
pull() {
// One async frame per pull: pass-through must stay as cheap as a plain
// read-and-forward loop.
return applicationPhase === ApplicationPhase.PassThrough
? pumpPassThrough()
: pump().catch(handlePumpError)
},
cancel(reason) {
return terminate('cancel', reason)
},
})
if (hydrationOutput) {
stopHydrationOutputListener = hydrationOutput.subscribe(() => {
if (hydrationOutput.state === HydrationScriptOutputState.Failed) {
terminate('failure', hydrationOutput.error)
return
}
wakePump()
})
}
disarmLifecycle = armStreamLifecycle(
serverSsr,
opts,
() => terminal,
terminate,
)
return stream
}
+20
View File
@@ -0,0 +1,20 @@
self.$_TSR = {
h() {
this.hydrated = true
this.c()
},
e() {
this.streamEnded = true
this.c()
},
c() {
if (this.hydrated && this.streamEnded) {
delete self.$_TSR
delete self.$R['tsr']
}
},
p(script) {
!this.initialized ? this.buffer.push(script) : script()
},
buffer: [],
}
+41
View File
@@ -0,0 +1,41 @@
import type { Manifest } from '../manifest'
import type { MakeRouteMatch } from '../Matches'
export interface DehydratedMatch {
i: MakeRouteMatch['id']
/** @internal */
b?: MakeRouteMatch['__beforeLoadContext']
l?: MakeRouteMatch['loaderData']
e?: MakeRouteMatch['error']
u: MakeRouteMatch['updatedAt']
s: MakeRouteMatch['status']
ssr?: MakeRouteMatch['ssr']
g?: true
}
export interface DehydratedRouter {
manifest: Manifest | undefined
dehydratedData?: any
matches: Array<DehydratedMatch>
}
export interface TsrSsrGlobal {
router?: DehydratedRouter
// Signal that router hydration is complete
h: () => void
// Signal that stream has ended
e: () => void
// Cleanup all hydration resources and scripts
c: () => void
// p: Push script into buffer or execute immediately
p: (script: () => void) => void
buffer: Array<() => void>
// custom transformers, shortened since this is sent for each streamed value that needs a custom transformer
t?: Map<string, (value: any) => any>
// this flag indicates whether the transformers were initialized
initialized?: boolean
// router is hydrated and doesnt need the streamed values anymore
hydrated?: boolean
// stream has ended
streamEnded?: boolean
}
+180
View File
@@ -0,0 +1,180 @@
import { arraysEqual, functionalUpdate } from './utils'
import type { AnyRoute } from './route'
import type { RouterState } from './router'
import type { FullSearchSchema } from './routeInfo'
import type { ParsedLocation } from './location'
import type { AnyRouteMatch } from './Matches'
export interface RouterReadableStore<TValue> {
get: () => TValue
}
export interface RouterWritableStore<
TValue,
> extends RouterReadableStore<TValue> {
set: ((updater: (prev: TValue) => TValue) => void) & ((value: TValue) => void)
}
export type RouterBatchFn = (fn: () => void) => void
export type MutableStoreFactory = <TValue>(
initialValue: TValue,
) => RouterWritableStore<TValue>
export type ReadonlyStoreFactory = <TValue>(
read: () => TValue,
) => RouterReadableStore<TValue>
export type GetStoreConfig = (opts: { isServer?: boolean }) => StoreConfig
export type StoreConfig = {
createMutableStore: MutableStoreFactory
createReadonlyStore: ReadonlyStoreFactory
batch: RouterBatchFn
}
type MatchStore = RouterWritableStore<AnyRouteMatch | undefined>
type ReadableStore<TValue> = RouterReadableStore<TValue>
/** SSR non-reactive createMutableStore */
export function createNonReactiveMutableStore<TValue>(
initialValue: TValue,
): RouterWritableStore<TValue> {
let value = initialValue
return {
get() {
return value
},
set(nextOrUpdater: TValue | ((prev: TValue) => TValue)) {
value = functionalUpdate(nextOrUpdater, value)
},
}
}
/** SSR non-reactive createReadonlyStore */
export function createNonReactiveReadonlyStore<TValue>(
read: () => TValue,
): RouterReadableStore<TValue> {
return {
get() {
return read()
},
}
}
export interface RouterStores<in out TRouteTree extends AnyRoute> {
status: RouterWritableStore<RouterState<TRouteTree>['status']>
location: RouterWritableStore<ParsedLocation<FullSearchSchema<TRouteTree>>>
resolvedLocation: RouterWritableStore<
ParsedLocation<FullSearchSchema<TRouteTree>> | undefined
>
ids: RouterWritableStore<Array<string>>
matches: ReadableStore<Array<AnyRouteMatch>>
__store: RouterReadableStore<RouterState<TRouteTree>>
byRoute: Map<string, MatchStore>
/**
* Get the stable atom for a route's presented match. The atom remains in the
* pool when the route leaves and contains `undefined` until it re-enters.
*/
getMatchStore: (
routeId: string,
) => RouterReadableStore<AnyRouteMatch | undefined>
setMatches: (nextMatches: Array<AnyRouteMatch>) => void
}
export function createRouterStores<TRouteTree extends AnyRoute>(
initialLocation: RouterState<TRouteTree>['location'],
config: StoreConfig,
): RouterStores<TRouteTree> {
const { createMutableStore, createReadonlyStore, batch } = config
// non reactive utilities
const byRoute = new Map<string, MatchStore>()
// atoms
const status = createMutableStore<RouterState<TRouteTree>['status']>('idle')
const location = createMutableStore(initialLocation)
const resolvedLocation =
createMutableStore<RouterState<TRouteTree>['resolvedLocation']>(undefined)
const ids = createMutableStore<Array<string>>([])
// 1st order derived stores
const matches = createReadonlyStore(() =>
ids.get().map((id) => byRoute.get(id)!.get()!),
)
// compatibility "big" state store
const __store = createReadonlyStore(() => ({
status: status.get(),
isLoading: status.get() === 'pending',
matches: matches.get(),
location: location.get(),
resolvedLocation: resolvedLocation.get(),
}))
function getMatchStore(routeId: string): MatchStore {
let matchStore = byRoute.get(routeId)
if (!matchStore) {
matchStore = createMutableStore<AnyRouteMatch | undefined>(undefined)
byRoute.set(routeId, matchStore)
}
return matchStore
}
const store = {
// atoms
status,
location,
resolvedLocation,
ids,
// derived
matches,
// non-reactive state
byRoute,
// compatibility "big" state
__store,
// stable per-route presentation atoms
getMatchStore,
// methods
setMatches,
}
// setters to update non-reactive utilities in sync with the reactive stores
function setMatches(nextMatches: Array<AnyRouteMatch>) {
const previousIds = ids.get()
const nextIds = nextMatches.map((match) => match.routeId)
batch(() => {
// Publish lane membership first so framework trees reconcile departures
// before observers of a leaving route receive its tombstone.
if (!arraysEqual(previousIds, nextIds)) {
ids.set(nextIds)
}
for (const id of previousIds) {
if (!nextIds.includes(id)) {
byRoute.get(id)!.set(() => undefined)
}
}
for (const nextMatch of nextMatches) {
const matchStore = getMatchStore(nextMatch.routeId)
if (matchStore.get() !== nextMatch) {
matchStore.set(nextMatch)
}
}
})
}
return store
}
+7
View File
@@ -0,0 +1,7 @@
import type { Constrain } from './utils'
export interface OptionalStructuralSharing<TStructuralSharing, TConstraint> {
readonly structuralSharing?:
| Constrain<TStructuralSharing, TConstraint>
| undefined
}
+181
View File
@@ -0,0 +1,181 @@
import type {
FromPathOption,
NavigateOptions,
PathParamOptions,
SearchParamOptions,
ToPathOption,
} from './link'
import type { RedirectOptions } from './redirect'
import type { RouteIds } from './routeInfo'
import type { AnyRouter, RegisteredRouter } from './router'
import type { UseParamsResult } from './useParams'
import type { UseSearchResult } from './useSearch'
import type { Constrain, ConstrainLiteral } from './utils'
export type ValidateFromPath<
TRouter extends AnyRouter = RegisteredRouter,
TFrom = string,
> = FromPathOption<TRouter, TFrom>
export type ValidateToPath<
TRouter extends AnyRouter = RegisteredRouter,
TTo extends string | undefined = undefined,
TFrom extends string = string,
> = ToPathOption<TRouter, TFrom, TTo>
export type ValidateSearch<
TRouter extends AnyRouter = RegisteredRouter,
TTo extends string | undefined = undefined,
TFrom extends string = string,
> = SearchParamOptions<TRouter, TFrom, TTo>
export type ValidateParams<
TRouter extends AnyRouter = RegisteredRouter,
TTo extends string | undefined = undefined,
TFrom extends string = string,
> = PathParamOptions<TRouter, TFrom, TTo>
/**
* @private
*/
export type InferFrom<
TOptions,
TDefaultFrom extends string = string,
> = TOptions extends {
from: infer TFrom extends string
}
? TFrom
: TDefaultFrom
/**
* @private
*/
export type InferTo<TOptions> = TOptions extends {
to: infer TTo extends string
}
? TTo
: undefined
/**
* @private
*/
export type InferMaskTo<TOptions> = TOptions extends {
mask: { to: infer TTo extends string }
}
? TTo
: ''
export type InferMaskFrom<TOptions> = TOptions extends {
mask: { from: infer TFrom extends string }
}
? TFrom
: string
export type ValidateNavigateOptions<
TRouter extends AnyRouter = RegisteredRouter,
TOptions = unknown,
TDefaultFrom extends string = string,
> = Constrain<
TOptions,
NavigateOptions<
TRouter,
InferFrom<TOptions, TDefaultFrom>,
InferTo<TOptions>,
InferMaskFrom<TOptions>,
InferMaskTo<TOptions>
>
>
export type ValidateNavigateOptionsArray<
TRouter extends AnyRouter = RegisteredRouter,
TOptions extends ReadonlyArray<any> = ReadonlyArray<unknown>,
TDefaultFrom extends string = string,
> = {
[K in keyof TOptions]: ValidateNavigateOptions<
TRouter,
TOptions[K],
TDefaultFrom
>
}
export type ValidateRedirectOptions<
TRouter extends AnyRouter = RegisteredRouter,
TOptions = unknown,
TDefaultFrom extends string = string,
> = Constrain<
TOptions,
RedirectOptions<
TRouter,
InferFrom<TOptions, TDefaultFrom>,
InferTo<TOptions>,
InferMaskFrom<TOptions>,
InferMaskTo<TOptions>
>
>
export type ValidateRedirectOptionsArray<
TRouter extends AnyRouter = RegisteredRouter,
TOptions extends ReadonlyArray<any> = ReadonlyArray<unknown>,
TDefaultFrom extends string = string,
> = {
[K in keyof TOptions]: ValidateRedirectOptions<
TRouter,
TOptions[K],
TDefaultFrom
>
}
export type ValidateId<
TRouter extends AnyRouter = RegisteredRouter,
TId extends string = string,
> = ConstrainLiteral<TId, RouteIds<TRouter['routeTree']>>
/**
* @private
*/
export type InferStrict<TOptions> = TOptions extends {
strict: infer TStrict extends boolean
}
? TStrict
: true
/**
* @private
*/
export type InferShouldThrow<TOptions> = TOptions extends {
shouldThrow: infer TShouldThrow extends boolean
}
? TShouldThrow
: true
/**
* @private
*/
export type InferSelected<TOptions> = TOptions extends {
select: (...args: Array<any>) => infer TSelected
}
? TSelected
: unknown
export type ValidateUseSearchResult<
TOptions,
TRouter extends AnyRouter = RegisteredRouter,
> = UseSearchResult<
TRouter,
InferFrom<TOptions>,
InferStrict<TOptions>,
InferSelected<TOptions>
>
export type ValidateUseParamsResult<
TOptions,
TRouter extends AnyRouter = RegisteredRouter,
> = Constrain<
TOptions,
UseParamsResult<
TRouter,
InferFrom<TOptions>,
InferStrict<TOptions>,
InferSelected<TOptions>
>
>
+20
View File
@@ -0,0 +1,20 @@
import type { AllLoaderData, RouteById } from './routeInfo'
import type { AnyRouter } from './router'
import type { Expand } from './utils'
export type ResolveUseLoaderData<
TRouter extends AnyRouter,
TFrom,
TStrict extends boolean,
> = TStrict extends false
? AllLoaderData<TRouter['routeTree']>
: Expand<RouteById<TRouter['routeTree'], TFrom>['types']['loaderData']>
export type UseLoaderDataResult<
TRouter extends AnyRouter,
TFrom,
TStrict extends boolean,
TSelected,
> = unknown extends TSelected
? ResolveUseLoaderData<TRouter, TFrom, TStrict>
: TSelected
+13
View File
@@ -0,0 +1,13 @@
import type { RouteById } from './routeInfo'
import type { AnyRouter } from './router'
import type { Expand } from './utils'
export type ResolveUseLoaderDeps<TRouter extends AnyRouter, TFrom> = Expand<
RouteById<TRouter['routeTree'], TFrom>['types']['loaderDeps']
>
export type UseLoaderDepsResult<
TRouter extends AnyRouter,
TFrom,
TSelected,
> = unknown extends TSelected ? ResolveUseLoaderDeps<TRouter, TFrom> : TSelected
+13
View File
@@ -0,0 +1,13 @@
import type { NavigateOptions } from './link'
import type { RegisteredRouter } from './router'
export type UseNavigateResult<TDefaultFrom extends string> = <
TRouter extends RegisteredRouter,
TTo extends string | undefined,
TFrom extends string = TDefaultFrom,
TMaskFrom extends string = TFrom,
TMaskTo extends string = '',
>({
from,
...rest
}: NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>) => Promise<void>
+20
View File
@@ -0,0 +1,20 @@
import type { AllParams, RouteById } from './routeInfo'
import type { AnyRouter } from './router'
import type { Expand } from './utils'
export type ResolveUseParams<
TRouter extends AnyRouter,
TFrom,
TStrict extends boolean,
> = TStrict extends false
? AllParams<TRouter['routeTree']>
: Expand<RouteById<TRouter['routeTree'], TFrom>['types']['allParams']>
export type UseParamsResult<
TRouter extends AnyRouter,
TFrom,
TStrict extends boolean,
TSelected,
> = unknown extends TSelected
? ResolveUseParams<TRouter, TFrom, TStrict>
: TSelected
+39
View File
@@ -0,0 +1,39 @@
import type { AllContext, RouteById } from './routeInfo'
import type { AnyRouter } from './router'
import type { Expand, StrictOrFrom } from './utils'
export interface UseRouteContextBaseOptions<
TRouter extends AnyRouter,
TFrom,
TStrict extends boolean,
TSelected,
> {
select?: (
search: ResolveUseRouteContext<TRouter, TFrom, TStrict>,
) => TSelected
}
export type UseRouteContextOptions<
TRouter extends AnyRouter,
TFrom extends string | undefined,
TStrict extends boolean,
TSelected,
> = StrictOrFrom<TRouter, TFrom, TStrict> &
UseRouteContextBaseOptions<TRouter, TFrom, TStrict, TSelected>
export type ResolveUseRouteContext<
TRouter extends AnyRouter,
TFrom,
TStrict extends boolean,
> = TStrict extends false
? AllContext<TRouter['routeTree']>
: Expand<RouteById<TRouter['routeTree'], TFrom>['types']['allContext']>
export type UseRouteContextResult<
TRouter extends AnyRouter,
TFrom,
TStrict extends boolean,
TSelected,
> = unknown extends TSelected
? ResolveUseRouteContext<TRouter, TFrom, TStrict>
: TSelected
+20
View File
@@ -0,0 +1,20 @@
import type { FullSearchSchema, RouteById } from './routeInfo'
import type { AnyRouter } from './router'
import type { Expand } from './utils'
export type UseSearchResult<
TRouter extends AnyRouter,
TFrom,
TStrict extends boolean,
TSelected,
> = unknown extends TSelected
? ResolveUseSearch<TRouter, TFrom, TStrict>
: TSelected
export type ResolveUseSearch<
TRouter extends AnyRouter,
TFrom,
TStrict extends boolean,
> = TStrict extends false
? FullSearchSchema<TRouter['routeTree']>
: Expand<RouteById<TRouter['routeTree'], TFrom>['types']['fullSearchSchema']>
+761
View File
@@ -0,0 +1,761 @@
import { isServer } from '@tanstack/router-core/isServer'
import type { RouteIds } from './routeInfo'
import type { AnyRouter } from './router'
export type Awaitable<T> = T | Promise<T>
export type NoInfer<T> = [T][T extends any ? 0 : never]
export type IsAny<TValue, TYesResult, TNoResult = TValue> = 1 extends 0 & TValue
? TYesResult
: TNoResult
export type PickAsRequired<TValue, TKey extends keyof TValue> = Omit<
TValue,
TKey
> &
Required<Pick<TValue, TKey>>
export type PickRequired<T> = {
[K in keyof T as undefined extends T[K] ? never : K]: T[K]
}
export type PickOptional<T> = {
[K in keyof T as undefined extends T[K] ? K : never]: T[K]
}
// from https://stackoverflow.com/a/76458160
export type WithoutEmpty<T> = T extends any ? ({} extends T ? never : T) : never
export type Expand<T> = T extends object
? T extends infer O
? O extends Function
? O
: { [K in keyof O]: O[K] }
: never
: T
export type DeepPartial<T> = T extends object
? {
[P in keyof T]?: DeepPartial<T[P]>
}
: T
export type MakeDifferenceOptional<TLeft, TRight> = keyof TLeft &
keyof TRight extends never
? TRight
: Omit<TRight, keyof TLeft & keyof TRight> & {
[K in keyof TLeft & keyof TRight]?: TRight[K]
}
// from https://stackoverflow.com/a/53955431
// eslint-disable-next-line @typescript-eslint/naming-convention
export type IsUnion<T, U extends T = T> = (
T extends any ? (U extends T ? false : true) : never
) extends false
? false
: true
export type IsNonEmptyObject<T> = T extends object
? keyof T extends never
? false
: true
: false
export type Assign<TLeft, TRight> = TLeft extends any
? TRight extends any
? IsNonEmptyObject<TLeft> extends false
? TRight
: IsNonEmptyObject<TRight> extends false
? TLeft
: keyof TLeft & keyof TRight extends never
? TLeft & TRight
: Omit<TLeft, keyof TRight> & TRight
: never
: never
export type IntersectAssign<TLeft, TRight> = TLeft extends any
? TRight extends any
? IsNonEmptyObject<TLeft> extends false
? TRight
: IsNonEmptyObject<TRight> extends false
? TLeft
: TRight & TLeft
: never
: never
export type Timeout = ReturnType<typeof setTimeout>
export type Updater<TPrevious, TResult = TPrevious> =
| TResult
| ((prev?: TPrevious) => TResult)
export type NonNullableUpdater<TPrevious, TResult = TPrevious> =
| TResult
| ((prev: TPrevious) => TResult)
export type ExtractObjects<TUnion> = TUnion extends MergeAllPrimitive
? never
: TUnion
export type PartialMergeAllObject<TUnion> =
ExtractObjects<TUnion> extends infer TObj
? [TObj] extends [never]
? never
: {
[TKey in TObj extends any ? keyof TObj : never]?: TObj extends any
? TKey extends keyof TObj
? TObj[TKey]
: never
: never
}
: never
export type MergeAllPrimitive =
| ReadonlyArray<any>
| number
| string
| bigint
| boolean
| symbol
| undefined
| null
export type ExtractPrimitives<TUnion> = TUnion extends MergeAllPrimitive
? TUnion
: TUnion extends object
? never
: TUnion
export type PartialMergeAll<TUnion> =
| ExtractPrimitives<TUnion>
| PartialMergeAllObject<TUnion>
export type Constrain<T, TConstraint, TDefault = TConstraint> =
| (T extends TConstraint ? T : never)
| TDefault
export type ConstrainLiteral<T, TConstraint, TDefault = TConstraint> =
| (T & TConstraint)
| TDefault
/**
* To be added to router types
*/
export type UnionToIntersection<T> = (
T extends any ? (arg: T) => any : never
) extends (arg: infer T) => any
? T
: never
/**
* Merges everything in a union into one object.
* This mapped type is homomorphic which means it preserves stuff! :)
*/
export type MergeAllObjects<
TUnion,
TIntersected = UnionToIntersection<ExtractObjects<TUnion>>,
> = [keyof TIntersected] extends [never]
? never
: {
[TKey in keyof TIntersected]: TUnion extends any
? TUnion[TKey & keyof TUnion]
: never
}
export type MergeAll<TUnion> =
| MergeAllObjects<TUnion>
| ExtractPrimitives<TUnion>
export type ValidateJSON<T> = ((...args: Array<any>) => any) extends T
? unknown extends T
? never
: 'Function is not serializable'
: { [K in keyof T]: ValidateJSON<T[K]> }
export type LooseReturnType<T> = T extends (
...args: Array<any>
) => infer TReturn
? TReturn
: never
export type LooseAsyncReturnType<T> = T extends (
...args: Array<any>
) => infer TReturn
? TReturn extends Promise<infer TReturn>
? TReturn
: TReturn
: never
/**
* Return the last element of an array.
* Intended for non-empty arrays used within router internals.
*/
export function last<T>(arr: ReadonlyArray<T>) {
return arr[arr.length - 1]
}
/**
* Apply a value-or-updater to a previous value.
* Accepts either a literal value or a function of the previous value.
*/
export function functionalUpdate<TPrevious, TResult = TPrevious>(
updater: Updater<TPrevious, TResult> | NonNullableUpdater<TPrevious, TResult>,
previous: TPrevious,
): TResult {
if (typeof updater === 'function') {
return (updater as Function)(previous)
}
return updater
}
export const hasOwn = Object.prototype.hasOwnProperty
export function hasKeys(obj: Record<string, unknown>) {
for (const key in obj) {
if (hasOwn.call(obj, key)) return true
}
return false
}
export const createNull = () => Object.create(null)
// Search and params objects use null prototypes so keys like `__proto__` stay data.
export const nullReplaceEqualDeep: typeof replaceEqualDeep = (prev, next) =>
replaceEqualDeep(prev, next, true)
/**
* Reuse equal children between immutable plain objects and dense arrays.
* Return `prev` for deeply equal values; otherwise return an object already
* containing the resolved children or create a copy with the shared children.
* Getters and own `__proto__` keys in ordinary object copies are unsupported.
* Do not use this with signals.
*/
export function replaceEqualDeep<T>(
prev: any,
next: T,
_nullProto?: boolean,
_depth?: number,
): T
export function replaceEqualDeep(
prev: any,
next: any,
_nullProto?: boolean,
_depth = 0,
): any {
if (isServer) {
return next
}
if (prev === next) {
return prev
}
if (_depth++ > 500) {
return next
}
const array = Array.isArray(prev) && Array.isArray(next)
if (!array && !(isPlainObject(prev) && isPlainObject(next))) {
return next
}
const prevKeys: Array<any> = Object.keys(prev)
const previousCount = prevKeys.length
const nextKeys: Array<any> = Object.keys(next)
const length = nextKeys.length
// Hidden object keys and symbols on next make the value opaque. Arrays
// must have only dense enumerable indices: a hole and an extra key can
// cancel out in the count, so also check the last key of both arrays.
if (
array
? previousCount !== prev.length ||
length !== next.length ||
(previousCount && last(prevKeys) !== `${previousCount - 1}`) ||
(length && last(nextKeys) !== `${length - 1}`)
: previousCount !== Object.getOwnPropertyNames(prev).length ||
length !== Object.getOwnPropertyNames(next).length ||
Object.getOwnPropertySymbols(next).length
) {
return next
}
let i = 0
let child: any
let previous: any
let key: any
if (array) {
// Entries before the first difference already resolve to prev.
for (; i < length; i++) {
key = i
previous = prev[key]
child = next[key]
child =
previous === child
? previous
: typeof previous === 'object'
? replaceEqualDeep(previous, child, _nullProto, _depth)
: child
if (child !== previous) {
break
}
}
if (i === length && previousCount === length) {
return prev
}
} else {
let equal = previousCount === length
let unchanged = true
for (; i < length; i++) {
key = nextKeys[i]!
previous = prev[key]
const incoming = next[key]
child =
previous === incoming
? previous
: typeof previous === 'object'
? replaceEqualDeep(previous, incoming, _nullProto, _depth)
: incoming
equal &&=
child === previous && (prevKeys[i] === key || hasOwn.call(prev, key))
unchanged &&= Object.is(child, incoming)
// This key has been checked; its private slot can hold the result.
prevKeys[i] = child
}
if (equal) {
return Object.getOwnPropertySymbols(prev).length ? next : prev
}
if (unchanged) {
return next
}
}
// Reuse the validated array key list; it is private and has the right length.
const copy: any = array ? nextKeys.fill(0) : _nullProto ? createNull() : {}
for (let j = 0; j < length; j++) {
key = array ? j : nextKeys[j]!
if (array) {
previous = prev[key]
if (j > i) {
child = next[key]
child =
previous === child
? previous
: typeof previous === 'object'
? replaceEqualDeep(previous, child, _nullProto, _depth)
: child
}
copy[key] = j < i ? previous : child
} else {
copy[key] = prevKeys[j]
}
}
return copy
}
export function isPlainObject(o: unknown): boolean {
if (!o || typeof o !== 'object') {
return false
}
// An own constructor is data, so classify the actual prototype.
return (Object.getPrototypeOf(o)?.constructor ?? Object) === Object
}
/**
* Check if a value is a "plain" array (no extra enumerable keys).
*/
export function isPlainArray(value: unknown): value is Array<unknown> {
return Array.isArray(value) && value.length === Object.keys(value).length
}
/**
* Perform a deep equality check optimized for router state comparisons.
*
* - `partial`: `b` may omit keys that `a` has (arrays stay length-exact).
* - `explicitUndefined`: keys holding `undefined` take part in the comparison
* instead of being ignored.
*
* Internal: the flags are positional so hot callers pass no options object.
*/
export function deepEqual(
a: any,
b: any,
partial?: boolean,
explicitUndefined?: boolean,
): boolean {
if (a === b) {
return true
}
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) return false
for (let i = 0, l = a.length; i < l; i++) {
const av = a[i]
const bv = b[i]
if (av !== bv && !deepEqual(av, bv, partial, explicitUndefined)) {
return false
}
}
return true
}
if (isPlainObject(a) && isPlainObject(b)) {
if (partial) {
for (const k in b) {
if (explicitUndefined || b[k] !== undefined) {
if (!deepEqual(a[k], b[k], partial, explicitUndefined)) return false
}
}
return true
}
let aCount = 0
if (explicitUndefined) {
aCount = Object.keys(a).length
} else {
for (const k in a) {
if (a[k] !== undefined) aCount++
}
}
for (const k in b) {
if (explicitUndefined || b[k] !== undefined) {
if (
aCount-- === 0 ||
!deepEqual(a[k], b[k], partial, explicitUndefined)
) {
return false
}
}
}
return aCount === 0
}
return false
}
export type StringLiteral<T> = T extends string
? string extends T
? string
: T
: never
export type ThrowOrOptional<T, TThrow extends boolean> = TThrow extends true
? T
: T | undefined
export type StrictOrFrom<
TRouter extends AnyRouter,
TFrom,
TStrict extends boolean = true,
> = TStrict extends false
? {
from?: never
strict: TStrict
}
: {
from: ConstrainLiteral<TFrom, RouteIds<TRouter['routeTree']>>
strict?: TStrict
}
export type ThrowConstraint<
TStrict extends boolean,
TThrow extends boolean,
> = TStrict extends false ? (TThrow extends true ? never : TThrow) : TThrow
export type ControlledPromise<T> = Promise<T> & {
resolve: (value: T) => void
reject: (value: any) => void
status: 'pending' | 'resolved' | 'rejected'
value?: T
}
/**
* Create a promise with exposed resolve/reject and status fields.
* Useful for coordinating async router lifecycle operations.
*/
export function createControlledPromise<T>(onResolve?: (value: T) => void) {
let resolveLoadPromise!: (value: T) => void
let rejectLoadPromise!: (value: any) => void
const controlledPromise = new Promise<T>((resolve, reject) => {
resolveLoadPromise = resolve
rejectLoadPromise = reject
}) as ControlledPromise<T>
controlledPromise.status = 'pending'
controlledPromise.resolve = (value: T) => {
controlledPromise.status = 'resolved'
controlledPromise.value = value
resolveLoadPromise(value)
onResolve?.(value)
}
controlledPromise.reject = (e) => {
controlledPromise.status = 'rejected'
rejectLoadPromise(e)
}
return controlledPromise
}
/**
* Heuristically detect dynamic import "module not found" errors
* across major browsers for lazy route component handling.
*/
export function isModuleNotFoundError(error: any): boolean {
// chrome: "Failed to fetch dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split"
// firefox: "error loading dynamically imported module: http://localhost:5173/src/routes/posts.index.tsx?tsr-split"
// safari: "Importing a module script failed."
if (typeof error?.message !== 'string') return false
return (
error.message.startsWith('Failed to fetch dynamically imported module') ||
error.message.startsWith('error loading dynamically imported module') ||
error.message.startsWith('Importing a module script failed')
)
}
export function isPromise<T>(
value: Promise<Awaited<T>> | T,
): value is Promise<Awaited<T>> {
return Boolean(
value &&
typeof value === 'object' &&
typeof (value as Promise<T>).then === 'function',
)
}
export function findLast<T>(
array: ReadonlyArray<T>,
predicate: (item: T) => boolean,
): T | undefined {
for (let i = array.length - 1; i >= 0; i--) {
const item = array[i]!
if (predicate(item)) return item
}
return undefined
}
/**
* Re-encode characters that are unsafe in URL paths.
* Includes ASCII control characters (0x00-0x1F, 0x7F) and a subset of the
* WHATWG URL "path percent-encode set" (", <, >, `, {, }).
*
* Space (0x20) is intentionally excluded — decodeURI decodes %20 to space
* and the router stores decoded spaces in location.pathname. The existing
* encodePathLikeUrl already handles re-encoding spaces for outgoing URLs.
*
* These characters are decoded by decodeURI but must remain percent-encoded
* in paths to match how upstream layers (CDNs, edge middleware, browsers)
* interpret the URL, preventing infinite redirect loops and path mismatches.
*/
// eslint-disable-next-line no-control-regex
const PATH_UNSAFE_RE = /[\x00-\x1f\x7f"<>`{}]/g
function sanitizePathSegment(segment: string): string {
return segment.replace(
PATH_UNSAFE_RE,
(ch) => '%' + ch.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0'),
)
}
function decodeSegment(segment: string): string {
let decoded: string
try {
decoded = decodeURI(segment)
} catch {
// if the decoding fails, try to decode the various parts leaving the malformed tags in place
decoded = segment.replaceAll(/%[0-9A-F]{2}/gi, (match) => {
try {
return decodeURI(match)
} catch {
return match
}
})
}
return sanitizePathSegment(decoded)
}
/**
* Default list of URL protocols to allow in links, redirects, and navigation.
* Any absolute URL protocol not in this list is treated as dangerous by default.
*/
export const DEFAULT_PROTOCOL_ALLOWLIST = [
// Standard web navigation
'http:',
'https:',
// Common browser-safe actions
'mailto:',
'tel:',
]
/**
* Extract the explicit URL scheme, including its colon, using WHATWG
* normalization rules. This does not validate the rest of the URL.
*
* Returning `undefined` means "no explicit scheme", not "safe URL";
* protocol-relative URLs such as "//evil.example" require a separate check.
*/
export function getUrlScheme(url: string): string | undefined {
if (url[0] === '/') {
return undefined
}
if (!url.includes(':')) {
return undefined
}
// WHATWG strips leading C0/space and TAB/LF/CR within a scheme.
// Match the prefix first so relative paths and URL bodies need no copying.
// eslint-disable-next-line no-control-regex
return /^[\x00-\x20]*([a-z][a-z\d+.\t\n\r-]*:)/i
.exec(url)?.[1]
?.replace(/[\t\n\r]/g, '')
.toLowerCase()
}
// Match protocol-relative URLs such as "//evil.example", including backslash
// and control-character variants. Stop at the second separator so validation
// does not scan or normalize the URL body.
// eslint-disable-next-line no-control-regex
export const protocolRelativePrefixRegex = /^[\x00-\x20]*[\\/][\t\n\r]*[\\/]/
/**
* Check if a URL string uses a protocol that is not in the allowlist or is
* protocol-relative (e.g. "//evil.example"), which can navigate to another host.
* Returns true for blocked protocols like javascript:, blob:, and data:, as
* well as slash/backslash variants of protocol-relative URLs.
*
* Scheme parsing normalizes:
* - Mixed case (JavaScript: → javascript:)
* - Whitespace/control characters (java\nscript: → javascript:)
* - Leading whitespace
*
* For relative URLs without a protocol-relative prefix, returns false.
*
* @param url - The URL string to check
* @param allowlist - Set of protocols to allow
* @returns true if the URL uses a protocol that is not allowed or can escape
* the current origin through a protocol-relative URL
*/
export function isDangerousProtocol(
url: string,
allowlist: Set<string>,
): boolean {
if (!url) return false
// Inputs like "/\evil.example" can navigate to another host just like
// "//evil.example", even with leading whitespace or ignored control characters.
if (protocolRelativePrefixRegex.test(url)) {
return true
}
const scheme = getUrlScheme(url)
return scheme ? !allowlist.has(scheme) : false
}
// This utility is based on https://github.com/zertosh/htmlescape
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
const HTML_ESCAPE_LOOKUP: { [match: string]: string } = {
'&': '\\u0026',
'>': '\\u003e',
'<': '\\u003c',
'\u2028': '\\u2028',
'\u2029': '\\u2029',
}
const HTML_ESCAPE_REGEX = /[&><\u2028\u2029]/g
/**
* Escape HTML special characters in a string to prevent XSS attacks
* when embedding strings in script tags during SSR.
*
* This is essential for preventing XSS vulnerabilities when user-controlled
* content is embedded in inline scripts.
*/
export function escapeHtml(str: string): string {
return str.replace(HTML_ESCAPE_REGEX, (match) => HTML_ESCAPE_LOOKUP[match]!)
}
// Decode component data only. Leave protocol-relative URL handling to callers;
// this decoder also receives fragments, where slashes and backslashes are data.
export function decodePath(path: string) {
if (!path) {
return path
}
let result = path
// eslint-disable-next-line no-control-regex
if (/[%\\\x00-\x1f\x7f]/.test(path)) {
const re = /%25|%5C/gi
let cursor = 0
let match
result = ''
while (null !== (match = re.exec(path))) {
result += decodeSegment(path.slice(cursor, match.index)) + match[0]
cursor = re.lastIndex
}
result += decodeSegment(cursor ? path.slice(cursor) : path)
}
return result
}
/**
* Encodes a path the same way `new URL()` would, but without the overhead of full URL parsing.
*
* This function encodes:
* - Whitespace characters (spaces → %20, tabs → %09, etc.)
* - Non-ASCII/Unicode characters (emojis, accented characters, etc.)
*
* It preserves:
* - Already percent-encoded sequences (won't double-encode %2F, %25, etc.)
* - ASCII special characters valid in URL paths (@, $, &, +, etc.)
* - Forward slashes as path separators
*
* Used to generate proper href values for SSR without constructing URL objects.
*
* @example
* encodePathLikeUrl('/path/file name.pdf') // '/path/file%20name.pdf'
* encodePathLikeUrl('/path/日本語') // '/path/%E6%97%A5%E6%9C%AC%E8%AA%9E'
* encodePathLikeUrl('/path/already%20encoded') // '/path/already%20encoded' (preserved)
*/
export function encodePathLikeUrl(path: string): string {
// Encode whitespace and non-ASCII characters that browsers encode in URLs.
// The test uses one character class: it matches the same code units as the
// replacement pattern below and is cheaper than the alternation.
if (!/[\s\u0080-\uFFFF]/.test(path)) {
return path
}
// biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ASCII range check
// eslint-disable-next-line no-control-regex
return path.replace(/\s|[^\u0000-\u007F]/gu, encodeURIComponent)
}
/**
* Builds the dev-mode CSS styles URL for route-scoped CSS collection.
* Used by HeadContent components in all framework implementations to construct
* the URL for the `/@tanstack-start/styles.css` endpoint.
*
* @param basepath - The router's basepath (may or may not have leading slash)
* @param routeIds - Array of matched route IDs to include in the CSS collection
* @returns The full URL path for the dev styles CSS endpoint
*/
export function buildDevStylesUrl(
basepath: string,
routeIds: Array<string>,
): string {
// Trim all leading and trailing slashes from basepath
const trimmedBasepath = basepath.replace(/^\/+|\/+$/g, '')
// Build normalized basepath: empty string for root, or '/path' for non-root
const normalizedBasepath = trimmedBasepath === '' ? '' : `/${trimmedBasepath}`
return `${normalizedBasepath}/@tanstack-start/styles.css?routes=${encodeURIComponent(routeIds.join(','))}`
}
export function arraysEqual<T>(a: Array<T>, b: Array<T>) {
if (a === b) return true
if (a.length !== b.length) return false
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false
}
return true
}
+121
View File
@@ -0,0 +1,121 @@
import type { SearchSchemaInput } from './route'
export interface StandardSchemaValidatorProps<TInput, TOutput> {
readonly types?: StandardSchemaValidatorTypes<TInput, TOutput> | undefined
readonly validate: AnyStandardSchemaValidate
}
export interface StandardSchemaValidator<TInput, TOutput> {
readonly '~standard': StandardSchemaValidatorProps<TInput, TOutput>
}
export type AnyStandardSchemaValidator = StandardSchemaValidator<any, any>
export interface StandardSchemaValidatorTypes<TInput, TOutput> {
readonly input: TInput
readonly output: TOutput
}
export interface AnyStandardSchemaValidateSuccess {
readonly value: any
readonly issues?: undefined
}
export interface AnyStandardSchemaValidateFailure {
readonly issues: ReadonlyArray<AnyStandardSchemaValidateIssue>
}
export interface AnyStandardSchemaValidateIssue {
readonly message: string
}
export interface AnyStandardSchemaValidateInput {
readonly value: any
}
export type AnyStandardSchemaValidate = (
value: unknown,
) =>
| (AnyStandardSchemaValidateSuccess | AnyStandardSchemaValidateFailure)
| Promise<AnyStandardSchemaValidateSuccess | AnyStandardSchemaValidateFailure>
export interface ValidatorObj<TInput, TOutput> {
parse: ValidatorFn<TInput, TOutput>
}
export type AnyValidatorObj = ValidatorObj<any, any>
export interface ValidatorAdapter<TInput, TOutput> {
types: {
input: TInput
output: TOutput
}
parse: (input: unknown) => TOutput
}
export type AnyValidatorAdapter = ValidatorAdapter<any, any>
export type AnyValidatorFn = ValidatorFn<any, any>
export type ValidatorFn<TInput, TOutput> = (input: TInput) => TOutput
export type Validator<TInput, TOutput> =
| ValidatorObj<TInput, TOutput>
| ValidatorFn<TInput, TOutput>
| ValidatorAdapter<TInput, TOutput>
| StandardSchemaValidator<TInput, TOutput>
| undefined
export type AnyValidator = Validator<any, any>
export type AnySchema = {}
export type DefaultValidator = Validator<Record<string, unknown>, AnySchema>
export type ResolveSearchValidatorInputFn<TValidator> = TValidator extends (
input: infer TSchemaInput,
) => any
? TSchemaInput extends SearchSchemaInput
? Omit<TSchemaInput, keyof SearchSchemaInput>
: ResolveValidatorOutputFn<TValidator>
: AnySchema
export type ResolveSearchValidatorInput<TValidator> =
TValidator extends AnyStandardSchemaValidator
? NonNullable<TValidator['~standard']['types']>['input']
: TValidator extends AnyValidatorAdapter
? TValidator['types']['input']
: TValidator extends AnyValidatorObj
? ResolveSearchValidatorInputFn<TValidator['parse']>
: ResolveSearchValidatorInputFn<TValidator>
export type ResolveValidatorInputFn<TValidator> = TValidator extends (
input: infer TInput,
) => any
? TInput
: undefined
export type ResolveValidatorInput<TValidator> =
TValidator extends AnyStandardSchemaValidator
? NonNullable<TValidator['~standard']['types']>['input']
: TValidator extends AnyValidatorAdapter
? TValidator['types']['input']
: TValidator extends AnyValidatorObj
? ResolveValidatorInputFn<TValidator['parse']>
: ResolveValidatorInputFn<TValidator>
export type ResolveValidatorOutputFn<TValidator> = TValidator extends (
...args: any
) => infer TSchema
? TSchema
: AnySchema
export type ResolveValidatorOutput<TValidator> = unknown extends TValidator
? TValidator
: TValidator extends AnyStandardSchemaValidator
? NonNullable<TValidator['~standard']['types']>['output']
: TValidator extends AnyValidatorAdapter
? TValidator['types']['output']
: TValidator extends AnyValidatorObj
? ResolveValidatorOutputFn<TValidator['parse']>
: ResolveValidatorOutputFn<TValidator>
+4
View File
@@ -0,0 +1,4 @@
declare module '*?script-string' {
const content: string
export default content
}