Server: Phase 2 (REVIEW not respected yet)
This commit is contained in:
1 parent
5d16ded553
commit
142b47674d
4271 files changed
+1203269
No files matched your search
+17
@@ -0,0 +1,17 @@
|
||||
//#region src/Matches.ts
|
||||
/**
|
||||
* Narrows matches based on a path
|
||||
* @experimental
|
||||
*/
|
||||
const isMatch = (match, path) => {
|
||||
const parts = path.split(".");
|
||||
let part;
|
||||
let i = 0;
|
||||
let value = match;
|
||||
while ((part = parts[i++]) != null && value != null) value = value[part];
|
||||
return value != null;
|
||||
};
|
||||
//#endregion
|
||||
exports.isMatch = isMatch;
|
||||
|
||||
//# sourceMappingURL=Matches.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"Matches.cjs","names":[],"sources":["../../src/Matches.ts"],"sourcesContent":["import type { AnyRoute, StaticDataRouteOption } from './route'\nimport type {\n AllContext,\n AllLoaderData,\n AllParams,\n FullSearchSchema,\n ParseRoute,\n RouteById,\n RouteIds,\n} from './routeInfo'\nimport type { AnyRouter, RegisteredRouter, SSROption } from './router'\nimport type { Constrain } from './utils'\n\nexport type AnyMatchAndValue = { match: any; value: any }\n\nexport type FindValueByIndex<\n TKey,\n TValue extends ReadonlyArray<any>,\n> = TKey extends `${infer TIndex extends number}` ? TValue[TIndex] : never\n\nexport type FindValueByKey<TKey, TValue> =\n TValue extends ReadonlyArray<any>\n ? FindValueByIndex<TKey, TValue>\n : TValue[TKey & keyof TValue]\n\nexport type CreateMatchAndValue<TMatch, TValue> = TValue extends any\n ? {\n match: TMatch\n value: TValue\n }\n : never\n\nexport type NextMatchAndValue<\n TKey,\n TMatchAndValue extends AnyMatchAndValue,\n> = TMatchAndValue extends any\n ? CreateMatchAndValue<\n TMatchAndValue['match'],\n FindValueByKey<TKey, TMatchAndValue['value']>\n >\n : never\n\nexport type IsMatchKeyOf<TValue> =\n TValue extends ReadonlyArray<any>\n ? number extends TValue['length']\n ? `${number}`\n : keyof TValue & `${number}`\n : TValue extends object\n ? keyof TValue & string\n : never\n\nexport type IsMatchPath<\n TParentPath extends string,\n TMatchAndValue extends AnyMatchAndValue,\n> = `${TParentPath}${IsMatchKeyOf<TMatchAndValue['value']>}`\n\nexport type IsMatchResult<\n TKey,\n TMatchAndValue extends AnyMatchAndValue,\n> = TMatchAndValue extends any\n ? TKey extends keyof TMatchAndValue['value']\n ? TMatchAndValue['match']\n : never\n : never\n\nexport type IsMatchParse<\n TPath,\n TMatchAndValue extends AnyMatchAndValue,\n TParentPath extends string = '',\n> = TPath extends `${string}.${string}`\n ? TPath extends `${infer TFirst}.${infer TRest}`\n ? IsMatchParse<\n TRest,\n NextMatchAndValue<TFirst, TMatchAndValue>,\n `${TParentPath}${TFirst}.`\n >\n : never\n : {\n path: IsMatchPath<TParentPath, TMatchAndValue>\n result: IsMatchResult<TPath, TMatchAndValue>\n }\n\nexport type IsMatch<TMatch, TPath> = IsMatchParse<\n TPath,\n TMatch extends any ? { match: TMatch; value: TMatch } : never\n>\n\n/**\n * Narrows matches based on a path\n * @experimental\n */\nexport const isMatch = <TMatch, TPath extends string>(\n match: TMatch,\n path: Constrain<TPath, IsMatch<TMatch, TPath>['path']>,\n): match is IsMatch<TMatch, TPath>['result'] => {\n const parts = (path as string).split('.')\n let part\n let i = 0\n let value: any = match\n\n while ((part = parts[i++]) != null && value != null) {\n value = value[part]\n }\n\n return value != null\n}\n\nexport interface DefaultRouteMatchExtensions {\n scripts?: unknown\n links?: unknown\n headScripts?: unknown\n meta?: unknown\n styles?: unknown\n}\n\nexport interface RouteMatchExtensions extends DefaultRouteMatchExtensions {}\n\nexport interface RouteMatch<\n out TRouteId,\n out TFullPath,\n out TAllParams,\n out TFullSearchSchema,\n out TLoaderData,\n out TAllContext,\n out TLoaderDeps,\n> extends RouteMatchExtensions {\n id: string\n routeId: TRouteId\n fullPath: TFullPath\n index: number\n pathname: string\n params: TAllParams\n _strictParams: TAllParams\n status: 'pending' | 'success' | 'error' | 'notFound'\n isFetching: false | 'beforeLoad' | 'loader'\n error: unknown\n paramsError: unknown\n searchError: unknown\n updatedAt: number\n loaderData?: TLoaderData\n /** @internal Exclusive end of the SSR-verified asset prefix. */\n _assetEnd?: number\n /** @internal */\n _ctx?: Record<string, unknown>\n /** @internal */\n __beforeLoadContext?: Record<string, unknown>\n context: TAllContext\n search: TFullSearchSchema\n _strictSearch: TFullSearchSchema\n abortController: AbortController\n cause: 'preload' | 'enter' | 'stay'\n loaderDeps: TLoaderDeps\n preload: boolean\n invalid: boolean\n headers?: Record<string, string>\n _notFound?: boolean\n staticData: StaticDataRouteOption\n /** This attribute is not reactive */\n ssr?: SSROption\n}\n\nexport interface PreValidationErrorHandlingRouteMatch<\n TRouteId,\n TFullPath,\n TAllParams,\n TFullSearchSchema,\n> {\n id: string\n routeId: TRouteId\n fullPath: TFullPath\n index: number\n pathname: string\n search:\n | { status: 'success'; value: TFullSearchSchema }\n | { status: 'error'; error: unknown }\n params:\n | { status: 'success'; value: TAllParams }\n | { status: 'error'; error: unknown }\n staticData: StaticDataRouteOption\n ssr?: boolean | 'data-only'\n}\n\nexport type MakePreValidationErrorHandlingRouteMatchUnion<\n TRouter extends AnyRouter = RegisteredRouter,\n TRoute extends AnyRoute = ParseRoute<TRouter['routeTree']>,\n> = TRoute extends any\Line truncated
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
import { AnyRoute, StaticDataRouteOption } from './route.cjs';
|
||||
import { AllContext, AllLoaderData, AllParams, FullSearchSchema, ParseRoute, RouteById, RouteIds } from './routeInfo.cjs';
|
||||
import { AnyRouter, RegisteredRouter, SSROption } from './router.cjs';
|
||||
import { Constrain } from './utils.cjs';
|
||||
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 declare const isMatch: <TMatch, TPath extends string>(match: TMatch, path: Constrain<TPath, IsMatch<TMatch, TPath>["path"]>) => match is IsMatch<TMatch, TPath>["result"];
|
||||
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;
|
||||
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;
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
import { NavigateOptions, ToOptions } from './link.cjs';
|
||||
import { ParsedLocation } from './location.cjs';
|
||||
import { RoutePaths } from './routeInfo.cjs';
|
||||
import { RegisteredRouter, ViewTransitionOptions } from './router.cjs';
|
||||
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;
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
//#region src/await-signal.ts
|
||||
function observeLate(callback, value) {
|
||||
if (!callback) return;
|
||||
try {
|
||||
const result = callback(value);
|
||||
if (result !== void 0) 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.
|
||||
*/
|
||||
function waitForReason(value, signal, onLate, onLateError) {
|
||||
const promise = Promise.resolve(value);
|
||||
if (signal.aborted) {
|
||||
promise.then((result) => observeLate(onLate, result), (error) => observeLate(onLateError, error));
|
||||
return Promise.reject(signal.reason);
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const abort = () => reject(signal.reason);
|
||||
signal.addEventListener("abort", abort, { once: true });
|
||||
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);
|
||||
});
|
||||
});
|
||||
}
|
||||
//#endregion
|
||||
exports.waitForReason = waitForReason;
|
||||
|
||||
//# sourceMappingURL=await-signal.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"await-signal.cjs","names":[],"sources":["../../src/await-signal.ts"],"sourcesContent":["function observeLate<T>(\n callback: ((value: T) => unknown) | undefined,\n value: T,\n) {\n if (!callback) {\n return\n }\n\n try {\n const result = callback(value)\n if (result !== undefined) {\n void Promise.resolve(result).catch(() => {})\n }\n } catch {}\n}\n\n/**\n * Await `value` unless `signal` aborts first. A result that settles after the\n * abort is passed to `onLate` / `onLateError` instead.\n *\n * One abort listener per wait: SSR requests nest at most a few waits on one\n * signal, so pooling them was measurably slower than this.\n */\nexport function waitForReason<T>(\n value: T | PromiseLike<T>,\n signal: AbortSignal,\n onLate?: (value: T) => unknown,\n onLateError?: (reason: unknown) => unknown,\n): Promise<T> {\n const promise = Promise.resolve(value)\n if (signal.aborted) {\n void promise.then(\n (result) => observeLate(onLate, result),\n (error) => observeLate(onLateError, error),\n )\n return Promise.reject(signal.reason)\n }\n\n return new Promise<T>((resolve, reject) => {\n const abort = () => reject(signal.reason)\n signal.addEventListener('abort', abort, { once: true })\n void promise.then(\n (result) => {\n signal.removeEventListener('abort', abort)\n if (signal.aborted) {\n observeLate(onLate, result)\n } else {\n resolve(result)\n }\n },\n (error) => {\n signal.removeEventListener('abort', abort)\n if (signal.aborted) {\n observeLate(onLateError, error)\n } else {\n reject(error)\n }\n },\n )\n })\n}\n"],"mappings":";AAAA,SAAS,YACP,UACA,OACA;CACA,IAAI,CAAC,UACH;CAGF,IAAI;EACF,MAAM,SAAS,SAAS,KAAK;EAC7B,IAAI,WAAW,KAAA,GACb,QAAa,QAAQ,MAAM,EAAE,YAAY,CAAC,CAAC;CAE/C,QAAQ,CAAC;AACX;;;;;;;;AASA,SAAgB,cACd,OACA,QACA,QACA,aACY;CACZ,MAAM,UAAU,QAAQ,QAAQ,KAAK;CACrC,IAAI,OAAO,SAAS;EAClB,QAAa,MACV,WAAW,YAAY,QAAQ,MAAM,IACrC,UAAU,YAAY,aAAa,KAAK,CAC3C;EACA,OAAO,QAAQ,OAAO,OAAO,MAAM;CACrC;CAEA,OAAO,IAAI,SAAY,SAAS,WAAW;EACzC,MAAM,cAAc,OAAO,OAAO,MAAM;EACxC,OAAO,iBAAiB,SAAS,OAAO,EAAE,MAAM,KAAK,CAAC;EACtD,QAAa,MACV,WAAW;GACV,OAAO,oBAAoB,SAAS,KAAK;GACzC,IAAI,OAAO,SACT,YAAY,QAAQ,MAAM;QAE1B,QAAQ,MAAM;EAElB,IACC,UAAU;GACT,OAAO,oBAAoB,SAAS,KAAK;GACzC,IAAI,OAAO,SACT,YAAY,aAAa,KAAK;QAE9B,OAAO,KAAK;EAEhB,CACF;CACF,CAAC;AACH"}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* 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 declare function waitForReason<T>(value: T | PromiseLike<T>, signal: AbortSignal, onLate?: (value: T) => unknown, onLateError?: (reason: unknown) => unknown): Promise<T>;
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
//#region src/config.ts
|
||||
const createRouterConfig = (options) => {
|
||||
return {
|
||||
serializationAdapters: options.serializationAdapters,
|
||||
defaultSsr: options.defaultSsr
|
||||
};
|
||||
};
|
||||
//#endregion
|
||||
exports.createRouterConfig = createRouterConfig;
|
||||
|
||||
//# sourceMappingURL=config.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"config.cjs","names":[],"sources":["../../src/config.ts"],"sourcesContent":["import type { SSROption } from './router'\nimport type { AnySerializationAdapter } from './ssr/serializer/transformer'\n\nexport interface RouterConfigOptions<\n in out TSerializationAdapters,\n in out TDefaultSsr,\n> {\n serializationAdapters?: TSerializationAdapters\n defaultSsr?: TDefaultSsr\n}\n\nexport interface RouterConfig<\n in out TSerializationAdapters,\n in out TDefaultSsr,\n> {\n '~types': RouterConfigTypes<TSerializationAdapters, TDefaultSsr>\n serializationAdapters: TSerializationAdapters\n defaultSsr: TDefaultSsr | undefined\n}\n\nexport interface RouterConfigTypes<\n in out TSerializationAdapters,\n in out TDefaultSsr,\n> {\n serializationAdapters: TSerializationAdapters\n defaultSsr: TDefaultSsr\n}\n\nexport const createRouterConfig = <\n const TSerializationAdapters extends ReadonlyArray<AnySerializationAdapter> =\n [],\n TDefaultSsr extends SSROption = SSROption,\n>(\n options: RouterConfigOptions<TSerializationAdapters, TDefaultSsr>,\n): RouterConfig<TSerializationAdapters, TDefaultSsr> => {\n return {\n serializationAdapters: options.serializationAdapters,\n defaultSsr: options.defaultSsr,\n } as RouterConfig<TSerializationAdapters, TDefaultSsr>\n}\n\nexport type AnyRouterConfig = RouterConfig<any, any>\n"],"mappings":";AA4BA,MAAa,sBAKX,YACsD;CACtD,OAAO;EACL,uBAAuB,QAAQ;EAC/B,YAAY,QAAQ;CACtB;AACF"}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { SSROption } from './router.cjs';
|
||||
import { AnySerializationAdapter } from './ssr/serializer/transformer.cjs';
|
||||
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 declare const createRouterConfig: <const TSerializationAdapters extends ReadonlyArray<AnySerializationAdapter> = [], TDefaultSsr extends SSROption = SSROption>(options: RouterConfigOptions<TSerializationAdapters, TDefaultSsr>) => RouterConfig<TSerializationAdapters, TDefaultSsr>;
|
||||
export type AnyRouterConfig = RouterConfig<any, any>;
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
const require_router = require("./router.cjs");
|
||||
//#region src/defer.ts
|
||||
/**
|
||||
* 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`.
|
||||
*/
|
||||
const TSR_DEFERRED_PROMISE = Symbol.for("TSR_DEFERRED_PROMISE");
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
function defer(_promise, options) {
|
||||
const promise = _promise;
|
||||
if (promise[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].error = {
|
||||
data: (options?.serializeError ?? require_router.defaultSerializeError)(error),
|
||||
__isServerError: true
|
||||
};
|
||||
});
|
||||
return promise;
|
||||
}
|
||||
//#endregion
|
||||
exports.TSR_DEFERRED_PROMISE = TSR_DEFERRED_PROMISE;
|
||||
exports.defer = defer;
|
||||
|
||||
//# sourceMappingURL=defer.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"defer.cjs","names":[],"sources":["../../src/defer.ts"],"sourcesContent":["import { defaultSerializeError } from './router'\n\n/**\n * Well-known symbol used by {@link defer} to tag a promise with\n * its deferred state. Consumers can read `promise[TSR_DEFERRED_PROMISE]`\n * to access `status`, `data`, or `error`.\n */\nexport const TSR_DEFERRED_PROMISE = Symbol.for('TSR_DEFERRED_PROMISE')\n\nexport type DeferredPromiseState<T> =\n | {\n status: 'pending'\n data?: T\n error?: unknown\n }\n | {\n status: 'success'\n data: T\n }\n | {\n status: 'error'\n data?: T\n error: unknown\n }\n\nexport type DeferredPromise<T> = Promise<T> & {\n [TSR_DEFERRED_PROMISE]: DeferredPromiseState<T>\n}\n\n/**\n * Wrap a promise with a deferred state for use with `<Await>` and `useAwaited`.\n *\n * The returned promise is augmented with internal state (status/data/error)\n * so UI can read progress or suspend until it settles.\n *\n * @param _promise The promise to wrap.\n * @param options Optional config. Provide `serializeError` to customize how\n * errors are serialized for transfer.\n * @returns The same promise with attached deferred metadata.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/deferFunction\n */\nexport function defer<T>(\n _promise: Promise<T>,\n options?: {\n serializeError?: typeof defaultSerializeError\n },\n) {\n const promise = _promise as DeferredPromise<T>\n // this is already deferred promise\n if ((promise as any)[TSR_DEFERRED_PROMISE]) {\n return promise\n }\n promise[TSR_DEFERRED_PROMISE] = { status: 'pending' }\n\n promise\n .then((data) => {\n promise[TSR_DEFERRED_PROMISE].status = 'success'\n promise[TSR_DEFERRED_PROMISE].data = data\n })\n .catch((error) => {\n promise[TSR_DEFERRED_PROMISE].status = 'error'\n ;(promise[TSR_DEFERRED_PROMISE] as any).error = {\n data: (options?.serializeError ?? defaultSerializeError)(error),\n __isServerError: true,\n }\n })\n\n return promise\n}\n"],"mappings":";;;;;;;AAOA,MAAa,uBAAuB,OAAO,IAAI,sBAAsB;;;;;;;;;;;;;AAkCrE,SAAgB,MACd,UACA,SAGA;CACA,MAAM,UAAU;CAEhB,IAAK,QAAgB,uBACnB,OAAO;CAET,QAAQ,wBAAwB,EAAE,QAAQ,UAAU;CAEpD,QACG,MAAM,SAAS;EACd,QAAQ,sBAAsB,SAAS;EACvC,QAAQ,sBAAsB,OAAO;CACvC,CAAC,EACA,OAAO,UAAU;EAChB,QAAQ,sBAAsB,SAAS;EACtC,QAAS,sBAA8B,QAAQ;GAC9C,OAAO,SAAS,kBAAkB,eAAA,uBAAuB,KAAK;GAC9D,iBAAiB;EACnB;CACF,CAAC;CAEH,OAAO;AACT"}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import { defaultSerializeError } from './router.cjs';
|
||||
/**
|
||||
* 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 declare const TSR_DEFERRED_PROMISE: unique symbol;
|
||||
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 declare function defer<T>(_promise: Promise<T>, options?: {
|
||||
serializeError?: typeof defaultSerializeError;
|
||||
}): DeferredPromise<T>;
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
import { Register } from './router.cjs';
|
||||
import { AnyContext, AnyPathParams, AnyRoute, FileBaseRouteOptions, ResolveParams, Route, RouteConstraints, UpdatableRouteOptions } from './route.cjs';
|
||||
import { AnyValidator } from './validators.cjs';
|
||||
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 {
|
||||
}
|
||||
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>;
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import { AnyRouter } from './router.cjs';
|
||||
declare global {
|
||||
interface Window {
|
||||
__TSR_ROUTER__?: AnyRouter;
|
||||
}
|
||||
}
|
||||
export {};
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
declare module '@tanstack/history' {
|
||||
interface HistoryState {
|
||||
__tempLocation?: HistoryLocation;
|
||||
__tempKey?: string;
|
||||
__hashScrollIntoViewOptions?: boolean | ScrollIntoViewOptions;
|
||||
}
|
||||
}
|
||||
export {};
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_utils = require("./utils.cjs");
|
||||
const require_invariant = require("./invariant.cjs");
|
||||
const require_path = require("./path.cjs");
|
||||
const require_not_found = require("./not-found.cjs");
|
||||
const require_scroll_restoration = require("./scroll-restoration.cjs");
|
||||
const require_qss = require("./qss.cjs");
|
||||
const require_searchParams = require("./searchParams.cjs");
|
||||
const require_root = require("./root.cjs");
|
||||
const require_redirect = require("./redirect.cjs");
|
||||
const require_load_client = require("./load-client.cjs");
|
||||
const require_rewrite = require("./rewrite.cjs");
|
||||
const require_stores = require("./stores.cjs");
|
||||
const require_router = require("./router.cjs");
|
||||
const require_defer = require("./defer.cjs");
|
||||
const require_link = require("./link.cjs");
|
||||
const require_manifest = require("./manifest.cjs");
|
||||
const require_Matches = require("./Matches.cjs");
|
||||
const require_bodyScripts = require("./ssr/bodyScripts.cjs");
|
||||
const require_route = require("./route.cjs");
|
||||
const require_config = require("./config.cjs");
|
||||
const require_searchMiddleware = require("./searchMiddleware.cjs");
|
||||
const require_transformer = require("./ssr/serializer/transformer.cjs");
|
||||
const require_makeSerovalPlugin = require("./ssr/serializer/makeSerovalPlugin.cjs");
|
||||
const require_RawStream = require("./ssr/serializer/RawStream.cjs");
|
||||
exports.BaseRootRoute = require_route.BaseRootRoute;
|
||||
exports.BaseRoute = require_route.BaseRoute;
|
||||
exports.BaseRouteApi = require_route.BaseRouteApi;
|
||||
exports.DEFAULT_PROTOCOL_ALLOWLIST = require_utils.DEFAULT_PROTOCOL_ALLOWLIST;
|
||||
exports.DEV_STYLES_ATTR = require_manifest.DEV_STYLES_ATTR;
|
||||
exports.PathParamError = require_router.PathParamError;
|
||||
exports.RawStream = require_RawStream.RawStream;
|
||||
exports.RouterCore = require_router.RouterCore;
|
||||
exports.SearchParamError = require_router.SearchParamError;
|
||||
exports.TSR_DEFERRED_PROMISE = require_defer.TSR_DEFERRED_PROMISE;
|
||||
exports._getAssetMatches = require_load_client._getAssetMatches;
|
||||
exports._getRenderedMatches = require_load_client._getRenderedMatches;
|
||||
exports.appendUniqueUserTags = require_manifest.appendUniqueUserTags;
|
||||
exports.buildDevStylesUrl = require_utils.buildDevStylesUrl;
|
||||
exports.cleanPath = require_path.cleanPath;
|
||||
exports.composeRewrites = require_rewrite.composeRewrites;
|
||||
exports.composeSsrBodyScripts = require_bodyScripts.composeSsrBodyScripts;
|
||||
exports.createControlledPromise = require_utils.createControlledPromise;
|
||||
exports.createInlineCssStyleAsset = require_manifest.createInlineCssStyleAsset;
|
||||
exports.createNonReactiveMutableStore = require_stores.createNonReactiveMutableStore;
|
||||
exports.createNonReactiveReadonlyStore = require_stores.createNonReactiveReadonlyStore;
|
||||
exports.createRouterConfig = require_config.createRouterConfig;
|
||||
exports.createSerializationAdapter = require_transformer.createSerializationAdapter;
|
||||
exports.decode = require_qss.decode;
|
||||
exports.deepEqual = require_utils.deepEqual;
|
||||
exports.defaultGetScrollRestorationKey = require_scroll_restoration.defaultGetScrollRestorationKey;
|
||||
exports.defaultParseSearch = require_searchParams.defaultParseSearch;
|
||||
exports.defaultSerializeError = require_router.defaultSerializeError;
|
||||
exports.defaultStringifySearch = require_searchParams.defaultStringifySearch;
|
||||
exports.defer = require_defer.defer;
|
||||
exports.encode = require_qss.encode;
|
||||
exports.escapeHtml = require_utils.escapeHtml;
|
||||
exports.exactPathTest = require_path.exactPathTest;
|
||||
exports.executeRewriteInput = require_rewrite.executeRewriteInput;
|
||||
exports.functionalUpdate = require_utils.functionalUpdate;
|
||||
exports.getAssetCrossOrigin = require_manifest.getAssetCrossOrigin;
|
||||
exports.getElementScrollRestorationEntry = require_scroll_restoration.getElementScrollRestorationEntry;
|
||||
exports.getInitialRouterState = require_router.getInitialRouterState;
|
||||
exports.getLocationChangeInfo = require_router.getLocationChangeInfo;
|
||||
exports.getManifestScriptFormat = require_manifest.getManifestScriptFormat;
|
||||
exports.getRouteSegments = require_path.getRouteSegments;
|
||||
exports.getScriptPreloadAttrs = require_manifest.getScriptPreloadAttrs;
|
||||
exports.getSsrBodyScriptParts = require_bodyScripts.getSsrBodyScriptParts;
|
||||
exports.getStylesheetHref = require_manifest.getStylesheetHref;
|
||||
exports.getUrlScheme = require_utils.getUrlScheme;
|
||||
exports.hasKeys = require_utils.hasKeys;
|
||||
exports.hasMissingPathParams = require_path.hasMissingPathParams;
|
||||
exports.interpolatePath = require_path.interpolatePath;
|
||||
exports.invariant = require_invariant.invariant;
|
||||
exports.isDangerousProtocol = require_utils.isDangerousProtocol;
|
||||
exports.isMatch = require_Matches.isMatch;
|
||||
exports.isModuleNotFoundError = require_utils.isModuleNotFoundError;
|
||||
exports.isNotFound = require_not_found.isNotFound;
|
||||
exports.isPromise = require_utils.isPromise;
|
||||
exports.isRedirect = require_redirect.isRedirect;
|
||||
exports.isResolvedRedirect = require_redirect.isResolvedRedirect;
|
||||
exports.joinPaths = require_path.joinPaths;
|
||||
exports.lazyFn = require_router.lazyFn;
|
||||
exports.makeSerovalPlugin = require_makeSerovalPlugin.makeSerovalPlugin;
|
||||
exports.notFound = require_not_found.notFound;
|
||||
exports.parseRedirect = require_redirect.parseRedirect;
|
||||
exports.parseSearchWith = require_searchParams.parseSearchWith;
|
||||
exports.preloadWarning = require_link.preloadWarning;
|
||||
exports.redirect = require_redirect.redirect;
|
||||
exports.removeTrailingSlash = require_path.removeTrailingSlash;
|
||||
exports.replaceEqualDeep = require_utils.replaceEqualDeep;
|
||||
exports.resolveManifestAssetLink = require_manifest.resolveManifestAssetLink;
|
||||
exports.resolveManifestCssLink = require_manifest.resolveManifestCssLink;
|
||||
exports.resolvePath = require_path.resolvePath;
|
||||
exports.retainSearchParams = require_searchMiddleware.retainSearchParams;
|
||||
exports.rootRouteId = require_root.rootRouteId;
|
||||
exports.setupScrollRestoration = require_scroll_restoration.setupScrollRestoration;
|
||||
exports.storageKey = require_scroll_restoration.storageKey;
|
||||
exports.stringifySearchWith = require_searchParams.stringifySearchWith;
|
||||
exports.stripSearchParams = require_searchMiddleware.stripSearchParams;
|
||||
exports.trailingSlashOptions = require_router.trailingSlashOptions;
|
||||
exports.trimPath = require_path.trimPath;
|
||||
exports.trimPathLeft = require_path.trimPathLeft;
|
||||
exports.trimPathRight = require_path.trimPathRight;
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
export * from './global.cjs';
|
||||
export { TSR_DEFERRED_PROMISE, defer } from './defer.cjs';
|
||||
export type { DeferredPromiseState, DeferredPromise } from './defer.cjs';
|
||||
export { invariant } from './invariant.cjs';
|
||||
export { preloadWarning } from './link.cjs';
|
||||
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.cjs';
|
||||
export type { RouteToPath, TrailingSlashOptionByRouter, ParseRoute, CodeRouteToPath, RouteIds, FullSearchSchema, FullSearchSchemaInput, AllParams, RouteById, AllContext, RoutePaths, RoutesById, RoutesByPath, AllLoaderData, RouteByPath, } from './routeInfo.cjs';
|
||||
export type { InferFileRouteTypes, FileRouteTypes, FileRoutesByPath, CreateFileRoute, LazyRoute, LazyRouteOptions, CreateLazyFileRoute, } from './fileRoute.cjs';
|
||||
export type { ParsedLocation } from './location.cjs';
|
||||
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.cjs';
|
||||
export { DEV_STYLES_ATTR, appendUniqueUserTags, createInlineCssStyleAsset, getAssetCrossOrigin, getManifestScriptFormat, getScriptPreloadAttrs, getStylesheetHref, resolveManifestAssetLink, resolveManifestCssLink, } from './manifest.cjs';
|
||||
export { isMatch } from './Matches.cjs';
|
||||
export { _getAssetMatches, _getRenderedMatches } from './load-client.cjs';
|
||||
export { composeSsrBodyScripts, getSsrBodyScriptParts } from './ssr/bodyScripts.cjs';
|
||||
export type { AnyMatchAndValue, FindValueByIndex, FindValueByKey, CreateMatchAndValue, NextMatchAndValue, IsMatchKeyOf, IsMatchPath, IsMatchResult, IsMatchParse, IsMatch, RouteMatch, RouteMatchExtensions, MakeRouteMatchUnion, MakeRouteMatch, AnyRouteMatch, MakeRouteMatchFromRoute, MatchRouteOptions, } from './Matches.cjs';
|
||||
export { joinPaths, cleanPath, trimPathLeft, trimPathRight, trimPath, removeTrailingSlash, exactPathTest, resolvePath, interpolatePath, getRouteSegments, hasMissingPathParams, } from './path.cjs';
|
||||
export { encode, decode } from './qss.cjs';
|
||||
export { rootRouteId } from './root.cjs';
|
||||
export type { RootRouteId } from './root.cjs';
|
||||
export { BaseRoute, BaseRouteApi, BaseRootRoute } from './route.cjs';
|
||||
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.cjs';
|
||||
export { createNonReactiveMutableStore, createNonReactiveReadonlyStore, } from './stores.cjs';
|
||||
export type { RouterBatchFn, RouterReadableStore, GetStoreConfig, RouterStores, RouterWritableStore, } from './stores.cjs';
|
||||
export { defaultSerializeError, getLocationChangeInfo, RouterCore, lazyFn, SearchParamError, PathParamError, getInitialRouterState, trailingSlashOptions, } from './router.cjs';
|
||||
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.cjs';
|
||||
export * from './config.cjs';
|
||||
export type { MatchLocation, CommitLocationOptions, NavigateFn, BuildLocationFn, } from './RouterProvider.cjs';
|
||||
export { retainSearchParams, stripSearchParams } from './searchMiddleware.cjs';
|
||||
export { defaultParseSearch, defaultStringifySearch, parseSearchWith, stringifySearchWith, } from './searchParams.cjs';
|
||||
export type { SearchSerializer, SearchParser } from './searchParams.cjs';
|
||||
export type { OptionalStructuralSharing } from './structuralSharing.cjs';
|
||||
export { functionalUpdate, hasKeys, replaceEqualDeep, deepEqual, createControlledPromise, isPromise, isModuleNotFoundError, DEFAULT_PROTOCOL_ALLOWLIST, escapeHtml, getUrlScheme, isDangerousProtocol, buildDevStylesUrl, } from './utils.cjs';
|
||||
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.cjs';
|
||||
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.cjs';
|
||||
export type { UseRouteContextBaseOptions, UseRouteContextOptions, UseRouteContextResult, } from './useRouteContext.cjs';
|
||||
export type { UseSearchResult, ResolveUseSearch } from './useSearch.cjs';
|
||||
export type { UseParamsResult, ResolveUseParams } from './useParams.cjs';
|
||||
export type { UseNavigateResult } from './useNavigate.cjs';
|
||||
export type { UseLoaderDepsResult, ResolveUseLoaderDeps } from './useLoaderDeps.cjs';
|
||||
export type { UseLoaderDataResult, ResolveUseLoaderData } from './useLoaderData.cjs';
|
||||
export type { Redirect, RedirectOptions, RedirectOptionsRoute, RedirectFnRoute, ResolvedRedirect, AnyRedirect, } from './redirect.cjs';
|
||||
export { redirect, isRedirect, isResolvedRedirect, parseRedirect, } from './redirect.cjs';
|
||||
export type { NotFoundError } from './not-found.cjs';
|
||||
export { isNotFound, notFound } from './not-found.cjs';
|
||||
export { defaultGetScrollRestorationKey, getElementScrollRestorationEntry, storageKey, setupScrollRestoration, } from './scroll-restoration.cjs';
|
||||
export type { ScrollRestorationOptions, ScrollRestorationEntry, } from './scroll-restoration.cjs';
|
||||
export type { ValidateFromPath, ValidateToPath, ValidateSearch, ValidateParams, InferFrom, InferTo, InferMaskTo, InferMaskFrom, ValidateNavigateOptions, ValidateNavigateOptionsArray, ValidateRedirectOptions, ValidateRedirectOptionsArray, ValidateId, InferStrict, InferShouldThrow, InferSelected, ValidateUseSearchResult, ValidateUseParamsResult, } from './typePrimitives.cjs';
|
||||
export type { AnySerializationAdapter, SerializationAdapter, ValidateSerializableInput, SerializerExtensions, ValidateSerializable, RegisteredSerializableInput, SerializableExtensions, DefaultSerializable, Serializable, TSR_SERIALIZABLE, TsrSerializable, SerializationError, } from './ssr/serializer/transformer.cjs';
|
||||
export { createSerializationAdapter } from './ssr/serializer/transformer.cjs';
|
||||
export { makeSerovalPlugin } from './ssr/serializer/makeSerovalPlugin.cjs';
|
||||
export { RawStream } from './ssr/serializer/RawStream.cjs';
|
||||
export type { OnRawStreamCallback, RawStreamHint, RawStreamOptions, } from './ssr/serializer/RawStream.cjs';
|
||||
export { composeRewrites, executeRewriteInput } from './rewrite.cjs';
|
||||
export type { LocationRewrite, LocationRewriteFunction } from './router.cjs';
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
//#region src/invariant.ts
|
||||
function invariant() {
|
||||
throw new Error("Invariant failed");
|
||||
}
|
||||
//#endregion
|
||||
exports.invariant = invariant;
|
||||
|
||||
//# sourceMappingURL=invariant.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"invariant.cjs","names":[],"sources":["../../src/invariant.ts"],"sourcesContent":["export function invariant(): never {\n throw new Error('Invariant failed')\n}\n"],"mappings":";AAAA,SAAgB,YAAmB;CACjC,MAAM,IAAI,MAAM,kBAAkB;AACpC"}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export declare function invariant(): never;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
//#region src/isServer/client.ts
|
||||
const isServer = false;
|
||||
const loadServerRoute = void 0;
|
||||
//#endregion
|
||||
exports.isServer = isServer;
|
||||
exports.loadServerRoute = loadServerRoute;
|
||||
|
||||
//# sourceMappingURL=client.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"client.cjs","names":[],"sources":["../../../src/isServer/client.ts"],"sourcesContent":["export const isServer = false\nexport const loadServerRoute: never = undefined as never\n"],"mappings":";;AAAA,MAAa,WAAW;AACxB,MAAa,kBAAyB,KAAA"}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export declare const isServer = false;
|
||||
export declare const loadServerRoute: never;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_load_server = require("../load-server.cjs");
|
||||
//#region src/isServer/development.ts
|
||||
const isServer = void 0;
|
||||
//#endregion
|
||||
exports.isServer = isServer;
|
||||
exports.loadServerRoute = require_load_server.loadServerRoute;
|
||||
|
||||
//# sourceMappingURL=development.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"development.cjs","names":[],"sources":["../../../src/isServer/development.ts"],"sourcesContent":["// Development/test mode - returns undefined so fallback to router.isServer is used\nexport const isServer: boolean | undefined = undefined\nexport { loadServerRoute } from '../load-server'\n"],"mappings":";;;AACA,MAAa,WAAgC,KAAA"}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export declare const isServer: boolean | undefined;
|
||||
export { loadServerRoute } from '../load-server.cjs';
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_load_server = require("../load-server.cjs");
|
||||
//#region src/isServer/server.ts
|
||||
const isServer = process.env.NODE_ENV === "test" ? void 0 : true;
|
||||
//#endregion
|
||||
exports.isServer = isServer;
|
||||
exports.loadServerRoute = require_load_server.loadServerRoute;
|
||||
|
||||
//# sourceMappingURL=server.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"server.cjs","names":[],"sources":["../../../src/isServer/server.ts"],"sourcesContent":["export const isServer = process.env.NODE_ENV === 'test' ? undefined : true\nexport { loadServerRoute } from '../load-server'\n"],"mappings":";;;AAAA,MAAa,WAAA,QAAA,IAAA,aAAoC,SAAS,KAAA,IAAY"}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export declare const isServer: boolean | undefined;
|
||||
export { loadServerRoute } from '../load-server.cjs';
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
//#region src/link.ts
|
||||
const preloadWarning = "Error preloading route! ☝️";
|
||||
//#endregion
|
||||
exports.preloadWarning = preloadWarning;
|
||||
|
||||
//# sourceMappingURL=link.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"link.cjs","names":[],"sources":["../../src/link.ts"],"sourcesContent":["import type { HistoryState, ParsedHistoryState } from '@tanstack/history'\nimport type {\n AllParams,\n CatchAllPaths,\n CurrentPath,\n FullSearchSchema,\n FullSearchSchemaInput,\n ParentPath,\n RouteByPath,\n RouteByToPath,\n RoutePaths,\n RouteToPath,\n ToPath,\n} from './routeInfo'\nimport type {\n AnyRouter,\n RegisteredRouter,\n ViewTransitionOptions,\n} from './router'\nimport type {\n ConstrainLiteral,\n Expand,\n MakeDifferenceOptional,\n NoInfer,\n NonNullableUpdater,\n Updater,\n} from './utils'\nimport type { ParsedLocation } from './location'\n\nexport type IsRequiredParams<TParams> =\n Record<never, never> extends TParams ? never : true\n\nexport interface ParsePathParamsResult<\n in out TRequired,\n in out TOptional,\n in out TRest,\n> {\n required: TRequired\n optional: TOptional\n rest: TRest\n}\n\nexport type AnyParsePathParamsResult = ParsePathParamsResult<\n string,\n string,\n string\n>\n\nexport type ParsePathParamsBoundaryStart<T extends string> =\n T extends `${infer TLeft}{-${infer TRight}`\n ? ParsePathParamsResult<\n ParsePathParams<TLeft>['required'],\n | ParsePathParams<TLeft>['optional']\n | ParsePathParams<TRight>['required']\n | ParsePathParams<TRight>['optional'],\n ParsePathParams<TRight>['rest']\n >\n : T extends `${infer TLeft}{${infer TRight}`\n ? ParsePathParamsResult<\n | ParsePathParams<TLeft>['required']\n | ParsePathParams<TRight>['required'],\n | ParsePathParams<TLeft>['optional']\n | ParsePathParams<TRight>['optional'],\n ParsePathParams<TRight>['rest']\n >\n : never\n\nexport type ParsePathParamsSymbol<T extends string> =\n T extends `${string}$${infer TRight}`\n ? TRight extends `${string}/${string}`\n ? TRight extends `${infer TParam}/${infer TRest}`\n ? TParam extends ''\n ? ParsePathParamsResult<\n ParsePathParams<TRest>['required'],\n '_splat' | ParsePathParams<TRest>['optional'],\n ParsePathParams<TRest>['rest']\n >\n : ParsePathParamsResult<\n TParam | ParsePathParams<TRest>['required'],\n ParsePathParams<TRest>['optional'],\n ParsePathParams<TRest>['rest']\n >\n : never\n : TRight extends ''\n ? ParsePathParamsResult<never, '_splat', never>\n : ParsePathParamsResult<TRight, never, never>\n : never\n\nexport type ParsePathParamsBoundaryEnd<T extends string> =\n T extends `${infer TLeft}}${infer TRight}`\n ? ParsePathParamsResult<\n | ParsePathParams<TLeft>['required']\n | ParsePathParams<TRight>['required'],\n | ParsePathParams<TLeft>['optional']\n | ParsePathParams<TRight>['optional'],\n ParsePathParams<TRight>['rest']\n >\n : never\n\nexport type ParsePathParamsEscapeStart<T extends string> =\n T extends `${infer TLeft}[${infer TRight}`\n ? ParsePathParamsResult<\n | ParsePathParams<TLeft>['required']\n | ParsePathParams<TRight>['required'],\n | ParsePathParams<TLeft>['optional']\n | ParsePathParams<TRight>['optional'],\n ParsePathParams<TRight>['rest']\n >\n : never\n\nexport type ParsePathParamsEscapeEnd<T extends string> =\n T extends `${string}]${infer TRight}` ? ParsePathParams<TRight> : never\n\nexport type ParsePathParams<T extends string> = T extends `${string}[${string}`\n ? ParsePathParamsEscapeStart<T>\n : T extends `${string}]${string}`\n ? ParsePathParamsEscapeEnd<T>\n : T extends `${string}}${string}`\n ? ParsePathParamsBoundaryEnd<T>\n : T extends `${string}{${string}`\n ? ParsePathParamsBoundaryStart<T>\n : T extends `${string}$${string}`\n ? ParsePathParamsSymbol<T>\n : never\n\nexport type AddTrailingSlash<T> = T extends `${string}/` ? T : `${T & string}/`\n\nexport type RemoveTrailingSlashes<T> = T & `${string}/` extends never\n ? T\n : T extends `${infer R}/`\n ? R\n : T\n\nexport type AddLeadingSlash<T> = T & `/${string}` extends never\n ? `/${T & string}`\n : T\n\nexport type RemoveLeadingSlashes<T> = T & `/${string}` extends never\n ? T\n : T extends `/${infer R}`\n ? R\n : T\n\ntype JoinPath<TLeft extends string, TRight extends string> = TRight extends ''\n ? TLeft\n : TLeft extends ''\n ? TRight\n : `${RemoveTrailingSlashes<TLeft>}/${RemoveLeadingSlashes<TRight>}`\n\ntype RemoveLastSegment<\n T extends string,\n TAcc extends string = '',\n> = T extends `${infer TSegment}/${infer TRest}`\n ? TRest & `${string}/${string}` extends never\n ? TRest extends ''\n ? TAcc\n : `${TAcc}${TSegment}`\n : RemoveLastSegment<TRest, `${TAcc}${TSegment}/`>\n : TAcc\n\nexport type ResolveCurrentPath<\n TFrom extends string,\n TTo extends string,\n> = TTo extends '.'\n ? Line truncated
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
import { HistoryState, ParsedHistoryState } from '@tanstack/history';
|
||||
import { AllParams, CatchAllPaths, CurrentPath, FullSearchSchema, FullSearchSchemaInput, ParentPath, RouteByPath, RouteByToPath, RoutePaths, RouteToPath, ToPath } from './routeInfo.cjs';
|
||||
import { AnyRouter, RegisteredRouter, ViewTransitionOptions } from './router.cjs';
|
||||
import { ConstrainLiteral, Expand, MakeDifferenceOptional, NoInfer, NonNullableUpdater, Updater } from './utils.cjs';
|
||||
import { ParsedLocation } from './location.cjs';
|
||||
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;
|
||||
}
|
||||
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 declare const preloadWarning = "Error preloading route! \u261D\uFE0F";
|
||||
export {};
|
||||
+1303
File diff suppressed because it is too large.
Load diff
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"load-client.cjs","names":[],"sources":["../../src/load-client.ts"],"sourcesContent":["// Keep this filename free of a secondary extension so declaration generation\n// can rewrite relative imports for both ESM and CJS.\nimport { isNotFound } from './not-found'\nimport { isRedirect } from './redirect'\nimport {\n getLocationChangeInfo,\n lifecycleEnd,\n runRouteLifecycle,\n} from './router'\nimport { hydrateSsrMatchId } from './ssr/ssr-match-id'\nimport type { GLOBAL_SEROVAL, GLOBAL_TSR } from './ssr/constants'\nimport type { TsrSsrGlobal } from './ssr/types'\nimport type { ParsedLocation } from './location'\nimport type { NavigateOptions } from './link'\nimport type { AnyRouteMatch } from './Matches'\nimport type { NotFoundError } from './not-found'\nimport type {\n AnyRoute,\n LoaderFnContext,\n RouteContextOptions,\n RouteLoaderFn,\n} from './route'\nimport type { AnyRedirect } from './redirect'\nimport type { AnyRouter, RouterCore, TrailingSlashOption } from './router'\nimport type { RoutePaths } from './routeInfo'\nimport type { RouterHistory } from '@tanstack/history'\n\ntype RouteComponentType =\n | 'component'\n | 'pendingComponent'\n | 'errorComponent'\n | 'notFoundComponent'\n\nexport function replaceRouteChunk(\n route: AnyRoute,\n lazyFn: AnyRoute['lazyFn'],\n): void {\n route.lazyFn = lazyFn ?? route.lazyFn\n route._lazy = undefined\n}\n\nfunction preloadComponent(\n route: AnyRoute,\n type: RouteComponentType,\n): Promise<void> | undefined {\n return (route.options[type] as any)?.preload?.()\n}\n\nfunction loadComponents(\n route: AnyRoute,\n onPendingReady?: () => void,\n): Promise<void> | undefined {\n const component = preloadComponent(route, 'component')\n let pending = preloadComponent(route, 'pendingComponent')\n if (onPendingReady) {\n if (pending) {\n pending = pending.then(onPendingReady)\n } else {\n onPendingReady()\n }\n }\n if (component && pending) {\n return Promise.all([component, pending]).then(() => {})\n }\n return component ?? pending\n}\n\nexport function loadRouteChunk(\n route: AnyRoute,\n // `false` waits only for lazy route options, before a boundary is selected.\n componentType?: 'errorComponent' | 'notFoundComponent' | false,\n onPendingReady?: () => void,\n): Promise<void> | undefined {\n const afterLazy = () =>\n componentType === false\n ? undefined\n : componentType\n ? preloadComponent(route, componentType)\n : loadComponents(route, onPendingReady)\n const current = route._lazy\n if (current) {\n return current === true ? afterLazy() : current.then(afterLazy)\n }\n if (!route.lazyFn) {\n return afterLazy()\n }\n\n const promise = route.lazyFn().then(\n (lazyRoute) => {\n // HMR clears the owner before an obsolete import can settle.\n if (process.env.NODE_ENV === 'production' || route._lazy === promise) {\n const { id: _id, ...options } = lazyRoute.options\n Object.assign(route.options, options)\n route._lazy = true\n }\n },\n (error) => {\n if (process.env.NODE_ENV === 'production' || route._lazy === promise) {\n route._lazy = undefined\n }\n throw error\n },\n )\n route._lazy = promise\n return promise.then(afterLazy)\n}\n\n/** Return the structural lane through the first terminal render boundary. */\nexport function _getRenderedMatches(\n matches: Array<AnyRouteMatch>,\n): Array<AnyRouteMatch> {\n const end =\n matches.findIndex(\n (match) => match.status !== 'success' || match._notFound,\n ) + 1\n return end && end < matches.length ? matches.slice(0, end) : matches\n}\n\n/** Return the lane whose document assets belong to the current presentation. */\nexport function _getAssetMatches(\n matches: Array<AnyRouteMatch>,\n): Array<AnyRouteMatch> {\n let end = matches.length\n for (let index = 0; index < end; index++) {\n const match = matches[index]!\n // `_assetEnd` is only ever set on hydration presentation clones that are\n // `status: 'pending'`, `ssr: 'data-only'`, error-free, and not not-found\n // (see hydrate.ts), and commits clear it — so its presence alone is the guard.\n if (match._assetEnd !== undefined) {\n end = Math.min(end, Math.max(index + 1, match._assetEnd))\n continue\n }\n if (match.status !== 'success' || match._notFound) {\n end = index + 1\n break\n }\n }\n // `end` only ever shrinks to `index + 1 >= 1`, so no zero guard is needed.\n return end < matches.length ? matches.slice(0, end) : matches\n}\n\ndeclare const lanePhase: unique symbol\n\ntype LanePhase = 'matched' | 'contextualized' | 'reduced' | 'projected'\n\n/**\n * Lane matches carry their lane's phase so functions can demand evidence of\n * pipeline position (e.g. `commitMatches` only accepts a projected lane's\n * matches). The brand is phantom — it never exists at runtime.\n */\ntype LaneMatches<TPhase extends LanePhase> = ArrayLine truncated
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
import { GLOBAL_SEROVAL, GLOBAL_TSR } from './ssr/constants.cjs';
|
||||
import { TsrSsrGlobal } from './ssr/types.cjs';
|
||||
import { ParsedLocation } from './location.cjs';
|
||||
import { NavigateOptions } from './link.cjs';
|
||||
import { AnyRouteMatch } from './Matches.cjs';
|
||||
import { NotFoundError } from './not-found.cjs';
|
||||
import { AnyRoute } from './route.cjs';
|
||||
import { AnyRedirect } from './redirect.cjs';
|
||||
import { AnyRouter, RouterCore, TrailingSlashOption } from './router.cjs';
|
||||
import { RoutePaths } from './routeInfo.cjs';
|
||||
import { RouterHistory } from '@tanstack/history';
|
||||
export declare function replaceRouteChunk(route: AnyRoute, lazyFn: AnyRoute['lazyFn']): void;
|
||||
export declare function loadRouteChunk(route: AnyRoute, componentType?: 'errorComponent' | 'notFoundComponent' | false, onPendingReady?: () => void): Promise<void> | undefined;
|
||||
/** Return the structural lane through the first terminal render boundary. */
|
||||
export declare function _getRenderedMatches(matches: Array<AnyRouteMatch>): Array<AnyRouteMatch>;
|
||||
/** Return the lane whose document assets belong to the current presentation. */
|
||||
export declare function _getAssetMatches(matches: Array<AnyRouteMatch>): Array<AnyRouteMatch>;
|
||||
declare const lanePhase: unique symbol;
|
||||
type LanePhase = 'matched' | 'contextualized' | 'reduced' | 'projected';
|
||||
/**
|
||||
* Lane matches carry their lane's phase so functions can demand evidence of
|
||||
* pipeline position (e.g. `commitMatches` only accepts a projected lane's
|
||||
* matches). The brand is phantom — it never exists at runtime.
|
||||
*/
|
||||
type LaneMatches<TPhase extends LanePhase> = Array<WorkMatch> & {
|
||||
readonly [lanePhase]?: TPhase;
|
||||
};
|
||||
type Lane<TPhase extends LanePhase> = [
|
||||
location: ParsedLocation,
|
||||
matches: LaneMatches<TPhase>,
|
||||
background?: Array<BackgroundLoaderTask>,
|
||||
backgroundSettlement?: Promise<IndexedOutcome | undefined>
|
||||
] & {
|
||||
readonly [lanePhase]?: TPhase;
|
||||
};
|
||||
type ReducedLane = Lane<'reduced'>;
|
||||
type ProjectedLane = Lane<'projected'>;
|
||||
declare const SUCCESS = 0;
|
||||
declare const ERROR = 1;
|
||||
declare const NOT_FOUND = 2;
|
||||
declare const REDIRECTED = 3;
|
||||
declare const CANCELED = 4;
|
||||
type RedirectOutcome = [
|
||||
kind: typeof REDIRECTED,
|
||||
redirect: AnyRedirect,
|
||||
location?: ParsedLocation
|
||||
];
|
||||
type NonRedirectOutcome = [kind: typeof SUCCESS, data: unknown] | [kind: typeof ERROR, error: unknown] | [kind: typeof NOT_FOUND, error: NotFoundError] | [kind: typeof CANCELED];
|
||||
type RawLoaderOutcome = NonRedirectOutcome | [kind: typeof REDIRECTED, redirect: AnyRedirect];
|
||||
type LoaderOutcome = NonRedirectOutcome | RedirectOutcome;
|
||||
type IndexedOutcome = [index: number, outcome: LoaderOutcome, boundary?: number];
|
||||
export type LoaderFlight = [
|
||||
outcome: Promise<RawLoaderOutcome>,
|
||||
controller: AbortController,
|
||||
leases: number
|
||||
];
|
||||
type WorkMatch = AnyRouteMatch & {
|
||||
_flight?: LoaderFlight;
|
||||
};
|
||||
declare const matchPhase: unique symbol;
|
||||
/**
|
||||
* A match whose loader outcome has been applied by `settleInto`, which is the
|
||||
* sole granter of this brand (phantom, zero-runtime). Consumers that require
|
||||
* it — e.g. `cacheLoaderMatch` — can only be reached after settlement, so the
|
||||
* compiler enforces the loader→settle→cache ordering. Sources that arrive
|
||||
* already settled (dehydrated server data) must cast at a named boundary.
|
||||
*/
|
||||
type SettledMatch = WorkMatch & {
|
||||
readonly [matchPhase]: 'settled';
|
||||
};
|
||||
export type LoadTransaction = [
|
||||
controller: AbortController,
|
||||
redirects: number,
|
||||
location: ParsedLocation,
|
||||
matches: Array<AnyRouteMatch>,
|
||||
startedAt: number,
|
||||
done: Promise<void>,
|
||||
/**
|
||||
* Dev-only HMR refresh mode. Presence forces successor rematerialization
|
||||
* until this publication is acknowledged. The optional hydration handoff is
|
||||
* retired when the refresh publishes.
|
||||
*/
|
||||
refresh?: [handoff: NonNullable<AnyRouter['_handoff']> | undefined]
|
||||
];
|
||||
export type PendingSession = [
|
||||
generation: LoadTransaction,
|
||||
boundaryId: string,
|
||||
/** Pending reveal time until acknowledged, then minimum-visible-until time. */
|
||||
deadline: number,
|
||||
revealTimer?: ReturnType<typeof setTimeout>,
|
||||
ack?: Promise<boolean> | true,
|
||||
component?: unknown
|
||||
];
|
||||
type CoordinatorRouter = AnyRouter & {
|
||||
/** Active speculative lanes retained for cancellation, invalidation, and cache clearing. */
|
||||
_preloads?: Map<AbortController, Array<AnyRouteMatch>>;
|
||||
_refreshNextLoad?: boolean;
|
||||
};
|
||||
type BackgroundLoaderTask = [
|
||||
index: number,
|
||||
outcome: Promise<LoaderOutcome>,
|
||||
chunkFailure: Promise<IndexedOutcome | undefined | void>,
|
||||
candidate: WorkMatch
|
||||
];
|
||||
export declare function waitFor<T>(value: T | PromiseLike<T>, signal: AbortSignal): Promise<T>;
|
||||
export declare function getRoute(router: AnyRouter, match: WorkMatch): AnyRoute;
|
||||
export declare function cacheLoaderMatch(router: CoordinatorRouter, match: SettledMatch, planned: AnyRouteMatch | undefined): void;
|
||||
export declare function projectLane(router: AnyRouter, lane: ReducedLane, signal: AbortSignal, start?: number, end?: number): Promise<ProjectedLane>;
|
||||
export declare function commitMatches(router: CoordinatorRouter, tx: LoadTransaction, matches: LaneMatches<'projected'>, resolvedPrefix?: number): void;
|
||||
export declare function loadClientRoute(router: CoordinatorRouter, opts?: {
|
||||
sync?: boolean;
|
||||
}): Promise<void>;
|
||||
export declare function refreshClientRoute(router: CoordinatorRouter): Promise<void>;
|
||||
export declare function preloadClientRoute<TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption, TDefaultStructuralSharingOption extends boolean, TRouterHistory extends RouterHistory, TDehydrated extends Record<string, any> = Record<string, any>, TFrom extends RoutePaths<TRouteTree> | string = string, TTo extends string | undefined = undefined, TMaskFrom extends RoutePaths<TRouteTree> | string = TFrom, TMaskTo extends string = ''>(router: RouterCore<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>, opts: NavigateOptions<RouterCore<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>, TFrom, TTo, TMaskFrom, TMaskTo>): Promise<Array<AnyRouteMatch> | undefined>;
|
||||
declare global {
|
||||
interface Window {
|
||||
[GLOBAL_TSR]?: TsrSsrGlobal;
|
||||
[GLOBAL_SEROVAL]?: any;
|
||||
}
|
||||
}
|
||||
export declare function hydrate(router: AnyRouter): Promise<void>;
|
||||
export {};
|
||||
+595
@@ -0,0 +1,595 @@
|
||||
const require_not_found = require("./not-found.cjs");
|
||||
const require_root = require("./root.cjs");
|
||||
const require_redirect = require("./redirect.cjs");
|
||||
const require_load_client = require("./load-client.cjs");
|
||||
const require_router = require("./router.cjs");
|
||||
const require_await_signal = require("./await-signal.cjs");
|
||||
//#region src/load-server.ts
|
||||
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."
|
||||
});
|
||||
function getRoute(router, match) {
|
||||
return router.routesById[match.routeId];
|
||||
}
|
||||
function normalize(value, rejected) {
|
||||
if (require_redirect.isRedirect(value)) return [REDIRECTED, value];
|
||||
if (require_not_found.isNotFound(value)) return [NOT_FOUND, value];
|
||||
if (rejected && typeof value?.then === "function") value = new Error("A Promise was thrown", { cause: value });
|
||||
return rejected ? [ERROR, value] : [SUCCESS, value];
|
||||
}
|
||||
function normalizeError(router, lane, route, cause, signal, notify = true) {
|
||||
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, lane, route, outcome, signal, notify = true) {
|
||||
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(value, cause) {
|
||||
if (cause !== void 0) return {
|
||||
status: "error",
|
||||
error: cause
|
||||
};
|
||||
return {
|
||||
status: "success",
|
||||
value
|
||||
};
|
||||
}
|
||||
function navigateFrom(router, location) {
|
||||
return (options) => router.navigate({
|
||||
...options,
|
||||
_fromLocation: location
|
||||
});
|
||||
}
|
||||
function waitFor(value, signal) {
|
||||
return signal ? require_await_signal.waitForReason(value, signal) : value;
|
||||
}
|
||||
function resolveSsr(router, lane, index) {
|
||||
const match = lane.matches[index];
|
||||
const route = getRoute(router, match);
|
||||
const parentSsr = lane.matches[index - 1]?.ssr;
|
||||
if (router.isShell()) return route.id === require_root.rootRouteId;
|
||||
if (parentSsr === false) return false;
|
||||
const inherit = (value) => {
|
||||
return value === true && parentSsr === "data-only" ? "data-only" : value;
|
||||
};
|
||||
const defaultSsr = router.options.defaultSsr ?? true;
|
||||
const inheritedDefault = inherit(defaultSsr);
|
||||
match.ssr = inheritedDefault;
|
||||
const option = route.options.ssr;
|
||||
if (option === void 0) return inheritedDefault;
|
||||
if (typeof option !== "function") return inherit(option);
|
||||
const context = {
|
||||
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) {
|
||||
return Promise.reject(cause);
|
||||
}
|
||||
}
|
||||
function stampNotFound(match, outcome) {
|
||||
if (outcome[0] === NOT_FOUND && !outcome[1].routeId) outcome[1].routeId = match.routeId;
|
||||
return outcome;
|
||||
}
|
||||
async function contextualize(router, lane, signal) {
|
||||
const globalBoundary = lane.matches.findIndex((match) => match._notFound);
|
||||
let end = globalBoundary < 0 ? lane.matches.length : globalBoundary + 1;
|
||||
let failure;
|
||||
let parentContext = { ...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);
|
||||
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 = void 0;
|
||||
let context = parentContext;
|
||||
try {
|
||||
let routeContext;
|
||||
if (route.options.context) {
|
||||
const routeContextOptions = {
|
||||
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) ?? void 0;
|
||||
}
|
||||
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 !== void 0) {
|
||||
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 = {
|
||||
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
|
||||
};
|
||||
}
|
||||
function getLoaderContext(router, lane, match, route, index, tasks) {
|
||||
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, lane, index, tasks, signal) {
|
||||
const match = lane.matches[index];
|
||||
const route = getRoute(router, match);
|
||||
let outcome;
|
||||
if (match.ssr === false) outcome = Promise.resolve([SKIPPED]);
|
||||
else {
|
||||
const routeLoader = route.options.loader;
|
||||
const loader = typeof routeLoader === "function" ? routeLoader : routeLoader?.handler;
|
||||
if (!loader) outcome = Promise.resolve([SUCCESS, void 0]);
|
||||
else outcome = Promise.resolve().then(() => loader(getLoaderContext(router, lane, match, route, index, tasks))).then((result) => normalize(result, false), (cause) => normalize(cause, true)).then((result) => {
|
||||
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 = void 0;
|
||||
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, matches, indexed, signal, fallback = 0) {
|
||||
const cause = indexed?.[1][1];
|
||||
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 = require_load_client.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, start = 0, reason = MATCH_SETTLED_ABORT_REASON) {
|
||||
for (let index = start; index < matches.length; index++) matches[index].abortController.abort(reason);
|
||||
}
|
||||
async function applyFailure(router, lane, indexed, signal) {
|
||||
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 = void 0;
|
||||
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];
|
||||
cause.routeId = match.routeId;
|
||||
match._notFound = void 0;
|
||||
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, lane, end, signal) {
|
||||
const chunks = [];
|
||||
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 = require_load_client.loadRouteChunk(route);
|
||||
if (loading) {
|
||||
const chunk = loading.then(() => {
|
||||
signal?.throwIfAborted();
|
||||
}, (cause) => {
|
||||
signal?.throwIfAborted();
|
||||
return [index, stampNotFound(match, normalizeError(router, lane, route, cause, signal))];
|
||||
});
|
||||
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;
|
||||
}
|
||||
}
|
||||
async function projectLane(router, lane, signal) {
|
||||
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, location, matchedMatches, signal) {
|
||||
const matched = {
|
||||
location,
|
||||
matches: matchedMatches.map((match) => ({
|
||||
...match,
|
||||
__beforeLoadContext: void 0,
|
||||
context: {},
|
||||
isFetching: false,
|
||||
abortController: new AbortController()
|
||||
}))
|
||||
};
|
||||
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, void 0, signal, plannedGlobalBoundary);
|
||||
if (boundary !== plannedGlobalBoundary) {
|
||||
matched.matches[plannedGlobalBoundary]._notFound = void 0;
|
||||
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 = [];
|
||||
for (let index = 0; index < loaderEnd; index++) {
|
||||
const task = createLoaderTask(router, lane, index, tasks, signal);
|
||||
tasks.push(task);
|
||||
}
|
||||
let loaderFailure;
|
||||
let control = lane.failure?.[1][0] === REDIRECTED ? lane.failure : void 0;
|
||||
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 = void 0;
|
||||
match.invalid = false;
|
||||
match.isFetching = false;
|
||||
match.updatedAt = Date.now();
|
||||
} else if (outcome[0] === REDIRECTED) {
|
||||
control = [task.index, outcome];
|
||||
throw control;
|
||||
} else {
|
||||
if (match.ssr !== false) {
|
||||
match.status = "success";
|
||||
match.error = void 0;
|
||||
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;
|
||||
}
|
||||
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;
|
||||
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;
|
||||
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 !== void 0) {
|
||||
const match = lane.matches[terminal.boundary];
|
||||
if (match.ssr === true) {
|
||||
const route = getRoute(router, match);
|
||||
try {
|
||||
if (terminal.kind === ERROR) await require_load_client.loadRouteChunk(route, "errorComponent");
|
||||
else if (match._notFound) await Promise.all([require_load_client.loadRouteChunk(route), require_load_client.loadRouteChunk(route, "notFoundComponent")]);
|
||||
else await require_load_client.loadRouteChunk(route, "notFoundComponent");
|
||||
} catch {}
|
||||
signal?.throwIfAborted();
|
||||
}
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
await projectLane(router, {
|
||||
location: lane.location,
|
||||
matches: lane.matches
|
||||
}, signal);
|
||||
signal?.throwIfAborted();
|
||||
router.serverSsr?.onCleanup((settled) => {
|
||||
if (!settled) abortLane();
|
||||
});
|
||||
return {
|
||||
type: "render",
|
||||
status: terminal.status,
|
||||
matches: lane.matches
|
||||
};
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", abortLane);
|
||||
}
|
||||
}
|
||||
async function loadServerRoute(router, opts) {
|
||||
router.updateLatestLocation();
|
||||
const next = router.latestLocation;
|
||||
const previous = router._committed;
|
||||
const previousEnd = router._lifecycleEnd;
|
||||
let result;
|
||||
try {
|
||||
const canonical = router.buildLocation({
|
||||
to: next.pathname,
|
||||
search: true,
|
||||
params: true,
|
||||
hash: true,
|
||||
state: true,
|
||||
_includeValidateSearch: true
|
||||
});
|
||||
if (next.publicHref !== canonical.publicHref) throw require_redirect.redirect({ href: canonical.publicHref || "/" });
|
||||
const changeInfo = require_router.getLocationChangeInfo(next, router.stores.resolvedLocation.get());
|
||||
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 (!require_redirect.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 = require_router.lifecycleEnd(result.matches);
|
||||
router.stores.setMatches(result.matches);
|
||||
router.stores.resolvedLocation.set(next);
|
||||
}
|
||||
});
|
||||
if (result.type === "render") require_router.runRouteLifecycle(router, previous, result.matches, previousEnd, nextEnd);
|
||||
router._commitPromise?.resolve();
|
||||
router._commitPromise = void 0;
|
||||
}
|
||||
//#endregion
|
||||
exports.loadServerRoute = loadServerRoute;
|
||||
|
||||
//# sourceMappingURL=load-server.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"load-server.cjs","names":[],"sources":["../../src/load-server.ts"],"sourcesContent":["// Keep this filename free of a secondary extension so declaration generation\n// can rewrite relative imports for both ESM and CJS.\nimport { isNotFound } from './not-found'\nimport { isRedirect, redirect } from './redirect'\nimport { rootRouteId } from './root'\nimport { loadRouteChunk } from './load-client'\nimport { waitForReason } from './await-signal'\nimport {\n getLocationChangeInfo,\n lifecycleEnd,\n runRouteLifecycle,\n} from './router'\nimport type { ParsedLocation } from './location'\nimport type { AnyRouteMatch } from './Matches'\nimport type { NotFoundError } from './not-found'\nimport type {\n AnyRoute,\n BeforeLoadContextOptions,\n LoaderFnContext,\n RouteContextOptions,\n SsrContextOptions,\n} from './route'\nimport type { AnyRedirect } from './redirect'\nimport type { AnyRouter, SSROption } from './router'\n\ndeclare const serverLanePhase: unique symbol\n\ntype ServerLane<TPhase extends 'matched' | 'contextualized' | 'reduced'> = {\n readonly [serverLanePhase]: TPhase\n location: ParsedLocation\n matches: Array<AnyRouteMatch>\n}\n\ntype MatchedLane = ServerLane<'matched'>\n\ntype IndexedOutcome = [index: number, outcome: LoaderOutcome, boundary?: number]\n\ntype ContextualizedLane = ServerLane<'contextualized'> & {\n end: number\n failure?: IndexedOutcome\n}\n\ntype ReducedLane = ServerLane<'reduced'>\n\nconst SUCCESS = 0\nconst ERROR = 1\nconst NOT_FOUND = 2\nconst REDIRECTED = 3\nconst SKIPPED = 4\n\nconst MATCH_SETTLED_ABORT_REASON = Object.freeze({\n name: 'AbortError',\n message: 'TanStack Router aborted this server match because it settled.',\n})\n\nconst REDIRECT_ABORT_REASON = Object.freeze({\n name: 'AbortError',\n message: 'TanStack Router aborted this server match because of a redirect.',\n})\n\ntype LoaderOutcome =\n | [typeof SUCCESS, data: unknown]\n | [typeof ERROR, error: unknown]\n | [typeof NOT_FOUND, error: NotFoundError]\n | [typeof REDIRECTED, redirect: AnyRedirect]\n | [typeof SKIPPED]\n\ntype LoaderTask = {\n index: number\n outcome: Promise<LoaderOutcome>\n match: Promise<AnyRouteMatch>\n}\n\nexport type ServerLoadResult =\n | {\n type: 'render'\n status: 200 | 404 | 500\n matches: Array<AnyRouteMatch>\n }\n | { type: 'redirect'; redirect: AnyRedirect }\n\nfunction getRoute(router: AnyRouter, match: AnyRouteMatch): AnyRoute {\n return router.routesById[match.routeId]\n}\n\nfunction normalize(value: unknown, rejected: boolean): LoaderOutcome {\n if (isRedirect(value)) {\n return [REDIRECTED, value]\n }\n if (isNotFound(value)) {\n return [NOT_FOUND, value]\n }\n if (rejected && typeof (value as any)?.then === 'function') {\n value = new Error('A Promise was thrown', { cause: value })\n }\n return rejected ? [ERROR, value] : [SUCCESS, value]\n}\n\nfunction normalizeError(\n router: AnyRouter,\n lane: { location: ParsedLocation },\n route: AnyRoute,\n cause: unknown,\n signal?: AbortSignal,\n notify = true,\n): LoaderOutcome {\n signal?.throwIfAborted()\n let outcome = normalize(cause, true)\n if (outcome[0] !== ERROR) {\n return materializeRedirect(router, lane, route, outcome, signal, notify)\n }\n try {\n route.options.onError?.(outcome[1])\n } catch (onErrorCause) {\n outcome = normalize(onErrorCause, true)\n }\n signal?.throwIfAborted()\n return materializeRedirect(router, lane, route, outcome, signal, notify)\n}\n\nfunction materializeRedirect(\n router: AnyRouter,\n lane: { location: ParsedLocation },\n route: AnyRoute,\n outcome: LoaderOutcome,\n signal?: AbortSignal,\n notify = true,\n): LoaderOutcome {\n if (outcome[0] !== REDIRECTED) {\n return outcome\n }\n signal?.throwIfAborted()\n try {\n outcome[1].options._fromLocation = lane.location\n router.resolveRedirect(outcome[1])\n signal?.throwIfAborted()\n return outcome\n } catch (cause) {\n signal?.throwIfAborted()\n return notify\n ? normalizeError(router, lane, route, cause, signal, false)\n : [ERROR, cause]\n }\n}\n\nfunction maybe<TValue>(\n value: TValue,\n cause: unknown,\n): { status: 'success'; value: TValue } | { status: 'error'; error: unknown } {\n if (cause !== undefined) {\n return { status: 'error', error: cause }\n }\n return { status: 'success', value }\n}\n\nfunction navigateFrom(router: AnyRouter, location: ParsedLocation) {\n return (options: any) =>\n router.navigate({\n ...options,\n _fromLocation: location,\n })\n}\n\nfunction waitFor<T>(value: Promise<T>, signal?: AbortSignal): Promise<T> {\n return signal ? waitForReason(value, signal) : value\n}\n\nfunction resolveSsr(\n router: AnyRouter,\n lane: MatchedLane,\n index: number,\n): SSROption | Promise<SSROption> {\n const match = lane.matches[index]!\n const route = getRoute(router, match)\n const parentSsr = lane.matches[index - 1]?.ssr\n\n if (router.isShell()) {\n Line truncated
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import { AnyRouteMatch } from './Matches.cjs';
|
||||
import { AnyRedirect } from './redirect.cjs';
|
||||
import { AnyRouter } from './router.cjs';
|
||||
export type ServerLoadResult = {
|
||||
type: 'render';
|
||||
status: 200 | 404 | 500;
|
||||
matches: Array<AnyRouteMatch>;
|
||||
} | {
|
||||
type: 'redirect';
|
||||
redirect: AnyRedirect;
|
||||
};
|
||||
type ServerLoadOptions = NonNullable<Parameters<AnyRouter['load']>[0]> & {
|
||||
_signal?: AbortSignal;
|
||||
};
|
||||
export declare function loadServerRoute(router: AnyRouter, opts?: ServerLoadOptions): Promise<void>;
|
||||
export {};
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
import { ParsedHistoryState } from '@tanstack/history';
|
||||
import { AnySchema } from './validators.cjs';
|
||||
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;
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
//#region src/manifest.ts
|
||||
const DEV_STYLES_ATTR = "data-tanstack-router-dev-styles";
|
||||
function getAssetCrossOrigin(assetCrossOrigin, kind) {
|
||||
if (!assetCrossOrigin) return;
|
||||
if (typeof assetCrossOrigin === "string") return assetCrossOrigin;
|
||||
return assetCrossOrigin[kind];
|
||||
}
|
||||
function getManifestScriptFormat(manifest) {
|
||||
return manifest?.scriptFormat ?? "module";
|
||||
}
|
||||
function getScriptPreloadAttrs(manifest, link, 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 } : {}
|
||||
};
|
||||
}
|
||||
function resolveManifestAssetLink(link) {
|
||||
if (typeof link === "string") return {
|
||||
href: link,
|
||||
crossOrigin: void 0
|
||||
};
|
||||
return link;
|
||||
}
|
||||
function appendUniqueUserTags(target, tags) {
|
||||
if (tags.length === 0) return;
|
||||
if (tags.length === 1) {
|
||||
target.push(tags[0]);
|
||||
return;
|
||||
}
|
||||
const seen = /* @__PURE__ */ new Set();
|
||||
for (const tag of tags) {
|
||||
const key = JSON.stringify(tag);
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
target.push(tag);
|
||||
}
|
||||
}
|
||||
function getStylesheetHref(asset) {
|
||||
return resolveManifestCssLink(asset).href;
|
||||
}
|
||||
function resolveManifestCssLink(link) {
|
||||
if (typeof link === "string") return {
|
||||
href: link,
|
||||
crossOrigin: void 0
|
||||
};
|
||||
return link;
|
||||
}
|
||||
function createInlineCssStyleAsset(css) {
|
||||
return {
|
||||
attrs: { suppressHydrationWarning: true },
|
||||
children: css
|
||||
};
|
||||
}
|
||||
function createInlineCssPlaceholderAsset() {
|
||||
return { attrs: { suppressHydrationWarning: true } };
|
||||
}
|
||||
//#endregion
|
||||
exports.DEV_STYLES_ATTR = DEV_STYLES_ATTR;
|
||||
exports.appendUniqueUserTags = appendUniqueUserTags;
|
||||
exports.createInlineCssPlaceholderAsset = createInlineCssPlaceholderAsset;
|
||||
exports.createInlineCssStyleAsset = createInlineCssStyleAsset;
|
||||
exports.getAssetCrossOrigin = getAssetCrossOrigin;
|
||||
exports.getManifestScriptFormat = getManifestScriptFormat;
|
||||
exports.getScriptPreloadAttrs = getScriptPreloadAttrs;
|
||||
exports.getStylesheetHref = getStylesheetHref;
|
||||
exports.resolveManifestAssetLink = resolveManifestAssetLink;
|
||||
exports.resolveManifestCssLink = resolveManifestCssLink;
|
||||
|
||||
//# sourceMappingURL=manifest.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"manifest.cjs","names":[],"sources":["../../src/manifest.ts"],"sourcesContent":["export type AssetCrossOrigin = 'anonymous' | 'use-credentials'\nexport type ScriptFormat = 'module' | 'iife'\n\nexport const DEV_STYLES_ATTR = 'data-tanstack-router-dev-styles'\n\nexport type AssetCrossOriginConfig =\n | AssetCrossOrigin\n | Partial<Record<'script' | 'stylesheet', AssetCrossOrigin>>\n\nexport type ManifestAssetLink =\n | string\n | {\n href: string\n crossOrigin?: AssetCrossOrigin\n }\n\nexport function getAssetCrossOrigin(\n assetCrossOrigin: AssetCrossOriginConfig | undefined,\n kind: 'script' | 'stylesheet',\n): AssetCrossOrigin | undefined {\n if (!assetCrossOrigin) {\n return undefined\n }\n\n if (typeof assetCrossOrigin === 'string') {\n return assetCrossOrigin\n }\n\n return assetCrossOrigin[kind]\n}\n\nexport function getManifestScriptFormat(\n manifest: { scriptFormat?: ScriptFormat } | undefined,\n): ScriptFormat {\n return manifest?.scriptFormat ?? 'module'\n}\n\nexport function getScriptPreloadAttrs(\n manifest: { scriptFormat?: ScriptFormat } | undefined,\n link: ManifestAssetLink,\n assetCrossOrigin?: AssetCrossOriginConfig,\n): {\n rel: 'modulepreload' | 'preload'\n as?: 'script'\n href: string\n crossOrigin?: AssetCrossOrigin\n} {\n const preloadLink = resolveManifestAssetLink(link)\n const crossOrigin =\n getAssetCrossOrigin(assetCrossOrigin, 'script') ?? preloadLink.crossOrigin\n\n return {\n ...(getManifestScriptFormat(manifest) === 'iife'\n ? { rel: 'preload', as: 'script' }\n : { rel: 'modulepreload' }),\n href: preloadLink.href,\n ...(crossOrigin ? { crossOrigin } : {}),\n }\n}\n\nexport function resolveManifestAssetLink(link: ManifestAssetLink) {\n if (typeof link === 'string') {\n return { href: link, crossOrigin: undefined }\n }\n\n return link\n}\n\nexport type Manifest = {\n scriptFormat?: ScriptFormat\n inlineStyle?: ManifestInlineCss\n routes: Record<string, ManifestRoute>\n}\n\nexport type ServerManifest = {\n scriptFormat?: ScriptFormat\n inlineCss?: ServerManifestInlineCss\n routes: Record<string, ServerManifestRoute>\n}\n\nexport type ServerManifestInlineCss = {\n styles: Record<string, string>\n templates?: Record<string, InlineCssTemplate>\n}\n\nexport type InlineCssTemplate = {\n strings: Array<string>\n urls: Array<string>\n}\n\nexport type ManifestRoute = {\n filePath?: string\n preloads?: Array<ManifestAssetLink>\n scripts?: Array<ManifestScript>\n css?: Array<ManifestCssLink>\n}\n\nexport type ServerManifestRoute = ManifestRoute\n\nexport type ManifestRouteAssets = Pick<\n ManifestRoute,\n 'preloads' | 'scripts' | 'css'\n>\n\nexport type RouterManagedTitleTag = {\n tag: 'title'\n attrs?: Record<string, any>\n children: string\n}\n\nexport type RouterManagedMetaTag = {\n tag: 'meta'\n attrs?: Record<string, any>\n children?: never\n}\n\nexport type RouterManagedLinkTag = {\n tag: 'link'\n attrs?: Record<string, any>\n children?: never\n}\n\nexport type RouterManagedScriptTag = {\n tag: 'script'\n attrs?: Record<string, any>\n children?: string\n}\n\nexport type ManifestScript = Omit<RouterManagedScriptTag, 'tag'>\n\nexport type RouterManagedStyleTag = {\n tag: 'style'\n attrs?: Record<string, any>\n children?: string\n inlineCss?: true\n}\n\nexport type RouterManagedTag =\n | RouterManagedTitleTag\n | RouterManagedMetaTag\n | RouterManagedLinkTag\n | RouterManagedScriptTag\n | RouterManagedStyleTag\n\nexport function appendUniqueUserTags(\n target: Array<RouterManagedTag>,\n tags: Array<RouterManagedTag>,\n) {\n if (tags.length === 0) {\n return\n }\n\n if (tags.length === 1) {\n target.push(tags[0]!)\n return\n }\n\n const seen = new Set<string>()\n for (const tag of tags) {\n const key = JSON.stringify(tag)\n if (seen.has(key)) {\n continue\n }\n seen.add(key)\n target.push(tag)\n }\n}\n\nexport type ManifestCssLink =\n | string\n | {\n href: string\n crossOrigin?: AssetCrossOrigin\n [DEV_STYLES_ATTR]?: true\n }\n\nexport type ManifestInlineCss = {\n attrs?: Record<string, any>\n children?: string\n}\n\nexport type RouterManagedInlineCssTag = RouterManagedStyleTag & {\n inlineCss: true\n}\n\nexport function getStylesheetHref(asset: ManifestCssLink) {\n return resolveManifestCssLink(asset).href\n}\n\nexport function resolveManifestCssLink(link: ManifestCssLink) {\n if (typeof link === 'string') {\n return { href: link, crossOrigin: undefined }\n }\n\n return link\n}\n\nexport function createInlineCssStyleAsset(css: string): ManifestInlineCss {\n return {\n attrs: {\n suppressHydrationWarning: true,\n },\n children: css,\n }\n}\n\nexport function createInlineCssPlaceholderAsset(): ManifestInlineCss {\n return {\n attrs: {\n suppressHydrationWarning: true,\n },\n }\n}\n"],"mappings":";AAGA,MAAa,kBAAkB;AAa/B,SAAgB,oBACd,kBACA,MAC8B;CAC9B,IAAI,CAAC,kBACHLine truncated
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
export type AssetCrossOrigin = 'anonymous' | 'use-credentials';
|
||||
export type ScriptFormat = 'module' | 'iife';
|
||||
export declare 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 declare function getAssetCrossOrigin(assetCrossOrigin: AssetCrossOriginConfig | undefined, kind: 'script' | 'stylesheet'): AssetCrossOrigin | undefined;
|
||||
export declare function getManifestScriptFormat(manifest: {
|
||||
scriptFormat?: ScriptFormat;
|
||||
} | undefined): ScriptFormat;
|
||||
export declare function getScriptPreloadAttrs(manifest: {
|
||||
scriptFormat?: ScriptFormat;
|
||||
} | undefined, link: ManifestAssetLink, assetCrossOrigin?: AssetCrossOriginConfig): {
|
||||
rel: 'modulepreload' | 'preload';
|
||||
as?: 'script';
|
||||
href: string;
|
||||
crossOrigin?: AssetCrossOrigin;
|
||||
};
|
||||
export declare function resolveManifestAssetLink(link: ManifestAssetLink): {
|
||||
href: string;
|
||||
crossOrigin?: AssetCrossOrigin;
|
||||
};
|
||||
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 declare function appendUniqueUserTags(target: Array<RouterManagedTag>, tags: Array<RouterManagedTag>): void;
|
||||
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 declare function getStylesheetHref(asset: ManifestCssLink): string;
|
||||
export declare function resolveManifestCssLink(link: ManifestCssLink): {
|
||||
href: string;
|
||||
crossOrigin?: AssetCrossOrigin;
|
||||
"data-tanstack-router-dev-styles"?: true;
|
||||
};
|
||||
export declare function createInlineCssStyleAsset(css: string): ManifestInlineCss;
|
||||
export declare function createInlineCssPlaceholderAsset(): ManifestInlineCss;
|
||||
+588
@@ -0,0 +1,588 @@
|
||||
const require_utils = require("./utils.cjs");
|
||||
const require_invariant = require("./invariant.cjs");
|
||||
const require_path = require("./path.cjs");
|
||||
const require_sieve_cache = require("./sieve-cache.cjs");
|
||||
const SEGMENT_TYPE_INDEX = 4;
|
||||
const SEGMENT_TYPE_PATHLESS = 5;
|
||||
function getParamNames(data) {
|
||||
const cached = data.names;
|
||||
if (cached) return cached;
|
||||
const keys = [];
|
||||
for (const segment of data) if (typeof segment !== "string") keys.push(segment[1]);
|
||||
return data.names = keys;
|
||||
}
|
||||
/** Parse one segment for matching and retain the same record for interpolation. */
|
||||
function parseSegment(path, start, end) {
|
||||
const part = path.substring(start, end);
|
||||
if (part.charCodeAt(0) === 36) return part.length === 1 ? [
|
||||
2,
|
||||
"_splat",
|
||||
"",
|
||||
void 0
|
||||
] : [
|
||||
1,
|
||||
part.substring(1),
|
||||
"",
|
||||
""
|
||||
];
|
||||
const open = part.indexOf("{");
|
||||
if (open >= 0) {
|
||||
const close = part.indexOf("}", open);
|
||||
const optional = part.charCodeAt(open + 1) === 45;
|
||||
const nameStart = open + (optional ? 3 : 2);
|
||||
if (close >= 0 && part.charCodeAt(nameStart - 1) === 36 && (!optional || nameStart < close)) {
|
||||
const key = part.substring(nameStart, close);
|
||||
return [
|
||||
optional ? 3 : key ? 1 : 2,
|
||||
key || "_splat",
|
||||
part.substring(0, open),
|
||||
path.substring(start + close + 1, key ? end : path.length)
|
||||
];
|
||||
}
|
||||
}
|
||||
return part;
|
||||
}
|
||||
function parseSegments(defaultCaseSensitive, route, start, node, dynamicListsToSort, parentInterpolation) {
|
||||
let cursor = start;
|
||||
const path = route.fullPath ?? route.from;
|
||||
const options = route.options;
|
||||
const length = path.length;
|
||||
const literalEnd = path.endsWith("/") ? length - 1 : length;
|
||||
const caseSensitive = options?.caseSensitive ?? defaultCaseSensitive;
|
||||
const parseParams = options?.params?.parse ?? options?.parseParams;
|
||||
let interpolation;
|
||||
let literalStart = parentInterpolation ? start - 1 : 0;
|
||||
if (!node || path.includes("$")) {
|
||||
interpolation = parentInterpolation?.slice() ?? [];
|
||||
const tail = require_utils.last(interpolation);
|
||||
if (tail && typeof tail !== "string" && tail[0] === 2) {
|
||||
interpolation[interpolation.length - 1] = [
|
||||
tail[0],
|
||||
tail[1],
|
||||
tail[2],
|
||||
tail[3] === void 0 ? void 0 : tail[3] + path.substring(start - (path[start - 2] === "/" ? 2 : 1), literalEnd)
|
||||
];
|
||||
literalStart = length;
|
||||
}
|
||||
}
|
||||
while (cursor < length) {
|
||||
const start = cursor;
|
||||
const next = path.indexOf("/", start);
|
||||
let end = next === -1 ? length : next;
|
||||
const segment = parseSegment(path, start, end);
|
||||
cursor = end + 1;
|
||||
let nextNode;
|
||||
if (typeof segment === "string") {
|
||||
if (!node) continue;
|
||||
let name = segment;
|
||||
let staticChildren;
|
||||
if (caseSensitive) staticChildren = node.static ??= /* @__PURE__ */ new Map();
|
||||
else {
|
||||
name = segment.toLowerCase();
|
||||
staticChildren = node.staticInsensitive ??= /* @__PURE__ */ new Map();
|
||||
}
|
||||
const existingNode = staticChildren.get(name);
|
||||
if (existingNode) nextNode = existingNode;
|
||||
else {
|
||||
const next = createSegmentNode(node);
|
||||
nextNode = next;
|
||||
staticChildren.set(name, next);
|
||||
}
|
||||
} else {
|
||||
const kind = segment[0];
|
||||
let prefix = segment[2];
|
||||
let suffix = segment[3] ?? "";
|
||||
if (kind === 2) {
|
||||
end = length;
|
||||
cursor = end + 1;
|
||||
}
|
||||
if (interpolation && literalStart < end) {
|
||||
if (literalStart < start - 1) interpolation.push(path.substring(literalStart, start - 1));
|
||||
segment[2] = "/" + prefix;
|
||||
if (kind === 2 && segment[3] !== void 0 && literalEnd < length) segment[3] = suffix.slice(0, -1);
|
||||
interpolation.push(segment);
|
||||
literalStart = end;
|
||||
}
|
||||
if (!node) continue;
|
||||
const actuallyCaseSensitive = caseSensitive && !!(prefix || suffix);
|
||||
if (!caseSensitive) {
|
||||
prefix = prefix.toLowerCase();
|
||||
suffix = suffix.toLowerCase();
|
||||
}
|
||||
const siblings = kind === 1 ? node.dynamic ??= [] : kind === 3 ? node.optional ??= [] : node.wildcard ??= [];
|
||||
const existingNode = kind !== 2 && !parseParams && siblings.find((s) => !s.parse && s.caseSensitive === actuallyCaseSensitive && s.prefix === prefix && s.suffix === suffix);
|
||||
if (existingNode) nextNode = existingNode;
|
||||
else {
|
||||
const next = createSegmentNode(node, kind, actuallyCaseSensitive, prefix, suffix);
|
||||
nextNode = next;
|
||||
siblings.push(next);
|
||||
if (siblings.length === 2) dynamicListsToSort?.push(siblings);
|
||||
}
|
||||
}
|
||||
node = nextNode;
|
||||
}
|
||||
if (interpolation && literalStart < literalEnd) interpolation.push(path.substring(literalStart, literalEnd));
|
||||
const segmentData = interpolation?.slice();
|
||||
if (!node) return segmentData;
|
||||
if (parseParams && route.children && !route.isRoot && route.id && route.id.charCodeAt(route.id.lastIndexOf("/") + 1) === 95) {
|
||||
const pathlessNode = createSegmentNode(node, SEGMENT_TYPE_PATHLESS);
|
||||
(node.pathless ??= []).push(pathlessNode);
|
||||
node = pathlessNode;
|
||||
}
|
||||
const isLeaf = (route.path || !route.children) && !route.isRoot;
|
||||
if (isLeaf && literalEnd < length) {
|
||||
const indexNode = createSegmentNode(node, SEGMENT_TYPE_INDEX);
|
||||
node.index = indexNode;
|
||||
node = indexNode;
|
||||
}
|
||||
node.parse = parseParams ?? null;
|
||||
node.priority = options?.params?.priority ?? 0;
|
||||
if (!node.route) {
|
||||
node.data = segmentData;
|
||||
if (isLeaf) node.route = route;
|
||||
}
|
||||
return [
|
||||
node,
|
||||
cursor,
|
||||
segmentData
|
||||
];
|
||||
}
|
||||
function sortDynamic(a, b) {
|
||||
if (a.parse && !b.parse) return -1;
|
||||
if (!a.parse && b.parse) return 1;
|
||||
if (a.parse && b.parse && (a.priority || b.priority)) return b.priority - a.priority;
|
||||
if (a.prefix && b.prefix && a.prefix !== b.prefix) {
|
||||
if (a.prefix.startsWith(b.prefix)) return -1;
|
||||
if (b.prefix.startsWith(a.prefix)) return 1;
|
||||
}
|
||||
if (a.suffix && b.suffix && a.suffix !== b.suffix) {
|
||||
if (a.suffix.endsWith(b.suffix)) return -1;
|
||||
if (b.suffix.endsWith(a.suffix)) return 1;
|
||||
}
|
||||
if (a.prefix && !b.prefix) return -1;
|
||||
if (!a.prefix && b.prefix) return 1;
|
||||
if (a.suffix && !b.suffix) return -1;
|
||||
if (!a.suffix && b.suffix) return 1;
|
||||
if (a.caseSensitive && !b.caseSensitive) return -1;
|
||||
if (!a.caseSensitive && b.caseSensitive) return 1;
|
||||
return 0;
|
||||
}
|
||||
function createSegmentNode(parent, kind = 0, caseSensitive, prefix, suffix) {
|
||||
return {
|
||||
kind,
|
||||
depth: parent ? parent.depth + 1 : 0,
|
||||
pathless: null,
|
||||
index: null,
|
||||
static: null,
|
||||
staticInsensitive: null,
|
||||
dynamic: null,
|
||||
optional: null,
|
||||
wildcard: null,
|
||||
route: null,
|
||||
data: void 0,
|
||||
parent,
|
||||
parse: null,
|
||||
priority: 0,
|
||||
caseSensitive,
|
||||
prefix,
|
||||
suffix
|
||||
};
|
||||
}
|
||||
function processRouteMasks(routeList, processedTree) {
|
||||
const segmentTree = createSegmentNode();
|
||||
const dynamicListsToSort = [];
|
||||
function visit(route, start, parentNode, parentInterpolation) {
|
||||
const [node, cursor, segments] = parseSegments(false, route, start, parentNode, dynamicListsToSort, parentInterpolation);
|
||||
if (route.children) for (const child of route.children) visit(child, cursor, node, segments);
|
||||
}
|
||||
for (const route of routeList) visit(route, 1, segmentTree);
|
||||
for (const nodes of dynamicListsToSort) nodes.sort(sortDynamic);
|
||||
processedTree.masksTree = segmentTree;
|
||||
processedTree.flatCache = require_sieve_cache.createSieveCache(1e3);
|
||||
}
|
||||
/**
|
||||
* Take an arbitrary list of routes, create a tree from them (if it hasn't been created already), and match a path against it.
|
||||
*/
|
||||
function findFlatMatch(path, processedTree) {
|
||||
path ||= "/";
|
||||
const cached = processedTree.flatCache.get(path);
|
||||
if (cached !== void 0) return cached;
|
||||
const result = findMatch(path, processedTree.masksTree);
|
||||
processedTree.flatCache.set(path, result);
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree
|
||||
*/
|
||||
function findSingleMatch(from, caseSensitive, fuzzy, path, processedTree) {
|
||||
from ||= "/";
|
||||
path ||= "/";
|
||||
const key = caseSensitive ? `case\0${from}` : from;
|
||||
let tree = processedTree.singleCache.get(key);
|
||||
if (!tree) {
|
||||
tree = createSegmentNode();
|
||||
parseSegments(caseSensitive, { from }, 1, tree);
|
||||
processedTree.singleCache.set(key, tree);
|
||||
}
|
||||
return findMatch(path, tree, fuzzy);
|
||||
}
|
||||
function findRouteMatch(path, processedTree, fuzzy = false) {
|
||||
const key = fuzzy ? path : `nofuzz\0${path}`;
|
||||
const cached = processedTree.matchCache.get(key);
|
||||
if (cached !== void 0) return cached;
|
||||
path ||= "/";
|
||||
let result;
|
||||
try {
|
||||
result = findMatch(path, processedTree.segmentTree, fuzzy);
|
||||
} catch (err) {
|
||||
if (err instanceof URIError) result = null;
|
||||
else throw err;
|
||||
}
|
||||
if (result) result.branch = buildRouteBranch(result.route);
|
||||
processedTree.matchCache.set(key, result);
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
* Processes a route tree into a segment trie for efficient path matching.
|
||||
* Also builds lookup maps for routes by ID and by trimmed full path.
|
||||
*/
|
||||
function processRouteTree(routeTree, caseSensitive = false) {
|
||||
const segmentTree = createSegmentNode();
|
||||
const dynamicListsToSort = [];
|
||||
const routesById = {};
|
||||
const routesByPath = {};
|
||||
let index = 0;
|
||||
function visit(route, start, parentNode, parentInterpolation) {
|
||||
route.init(index);
|
||||
if (route.id in routesById) {
|
||||
if (process.env.NODE_ENV !== "production") throw new Error(`Invariant failed: Duplicate routes found with id: ${String(route.id)}`);
|
||||
require_invariant.invariant();
|
||||
}
|
||||
routesById[route.id] = route;
|
||||
if (index !== 0 && route.path) {
|
||||
const trimmedFullPath = require_path.trimPathRight(route.fullPath);
|
||||
if (!routesByPath[trimmedFullPath] || route.fullPath.endsWith("/")) routesByPath[trimmedFullPath] = route;
|
||||
}
|
||||
index++;
|
||||
const [node, cursor, segments] = parseSegments(caseSensitive, route, start, parentNode, dynamicListsToSort, parentInterpolation);
|
||||
route._interpolation = segments;
|
||||
if (route.children) for (const child of route.children) visit(child, cursor, node, segments);
|
||||
}
|
||||
visit(routeTree, 1, segmentTree);
|
||||
for (const nodes of dynamicListsToSort) nodes.sort(sortDynamic);
|
||||
return {
|
||||
processedTree: {
|
||||
segmentTree,
|
||||
singleCache: require_sieve_cache.createSieveCache(1e3),
|
||||
matchCache: require_sieve_cache.createSieveCache(1e3),
|
||||
flatCache: null,
|
||||
masksTree: null
|
||||
},
|
||||
routesById,
|
||||
routesByPath
|
||||
};
|
||||
}
|
||||
function findMatch(path, segmentTree, fuzzy = false) {
|
||||
const parts = path.split("/");
|
||||
const leaf = getNodeMatch(path, parts, segmentTree, fuzzy);
|
||||
if (!leaf) return null;
|
||||
const [rawParams] = extractParams(path, parts, leaf);
|
||||
return {
|
||||
route: leaf.node.route,
|
||||
rawParams
|
||||
};
|
||||
}
|
||||
/**
|
||||
* This function is "resumable":
|
||||
* - the `leaf` input can contain `extract` and `rawParams` properties from a previous `extractParams` call
|
||||
* - the returned `state` can be passed back as `extract` in a future call to continue extracting params from where we left off
|
||||
*
|
||||
* Inputs are *not* mutated.
|
||||
*/
|
||||
function extractParams(path, parts, leaf) {
|
||||
const list = buildBranch(leaf.node);
|
||||
const names = leaf.node.data && getParamNames(leaf.node.data);
|
||||
const rawParams = Object.create(null);
|
||||
/** which segment of the path we're currently processing */
|
||||
let partIndex = leaf.extract?.part ?? 0;
|
||||
/** which node of the route tree branch we're currently processing */
|
||||
let nodeIndex = leaf.extract?.node ?? 0;
|
||||
/** index of the 1st character of the segment we're processing in the path string */
|
||||
let pathIndex = leaf.extract?.path ?? 0;
|
||||
/** Next original parameter name, independent of pathless/static nodes. */
|
||||
let paramIndex = leaf.extract?.param ?? 0;
|
||||
for (; nodeIndex < list.length; partIndex++, nodeIndex++, pathIndex++) {
|
||||
const node = list[nodeIndex];
|
||||
if (node.kind === SEGMENT_TYPE_INDEX) break;
|
||||
if (node.kind === SEGMENT_TYPE_PATHLESS) {
|
||||
partIndex--;
|
||||
pathIndex--;
|
||||
continue;
|
||||
}
|
||||
const part = parts[partIndex];
|
||||
const currentPathIndex = pathIndex;
|
||||
if (part) pathIndex += part.length;
|
||||
if (node.kind === 1 || node.kind === 3) {
|
||||
const name = names[paramIndex++];
|
||||
if (node.kind === 3 && leaf.skipped & 1 << nodeIndex) {
|
||||
partIndex--;
|
||||
pathIndex = currentPathIndex - 1;
|
||||
continue;
|
||||
}
|
||||
const value = node.suffix || node.prefix ? part.substring(node.prefix.length, part.length - node.suffix.length) : part;
|
||||
if (value || node.kind === 1) rawParams[name] = decodeURIComponent(value);
|
||||
} else if (node.kind === 2) {
|
||||
const n = node;
|
||||
const value = path.substring(currentPathIndex + n.prefix.length, path.length - n.suffix.length);
|
||||
const splat = decodeURIComponent(value);
|
||||
rawParams["*"] = splat;
|
||||
rawParams._splat = splat;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (leaf.rawParams) Object.assign(rawParams, leaf.rawParams);
|
||||
return [rawParams, {
|
||||
part: partIndex,
|
||||
node: nodeIndex,
|
||||
path: pathIndex,
|
||||
param: paramIndex
|
||||
}];
|
||||
}
|
||||
function buildRouteBranch(route) {
|
||||
const list = [route];
|
||||
while (route.parentRoute) {
|
||||
route = route.parentRoute;
|
||||
list.push(route);
|
||||
}
|
||||
list.reverse();
|
||||
return list;
|
||||
}
|
||||
function buildBranch(node) {
|
||||
const list = Array(node.depth + 1);
|
||||
do {
|
||||
list[node.depth] = node;
|
||||
node = node.parent;
|
||||
} while (node);
|
||||
return list;
|
||||
}
|
||||
function getNodeMatch(path, parts, segmentTree, fuzzy) {
|
||||
if (path === "/" && segmentTree.index) return {
|
||||
node: segmentTree.index,
|
||||
skipped: 0
|
||||
};
|
||||
const trailingSlash = !require_utils.last(parts);
|
||||
const pathIsIndex = trailingSlash && path !== "/";
|
||||
const partsLength = parts.length - (trailingSlash ? 1 : 0);
|
||||
const stack = [{
|
||||
node: segmentTree,
|
||||
index: 1,
|
||||
skipped: 0,
|
||||
statics: 0,
|
||||
dynamics: 0,
|
||||
optionals: 0
|
||||
}];
|
||||
let bestFuzzy = null;
|
||||
let bestMatch = null;
|
||||
while (stack.length) {
|
||||
const frame = stack.pop();
|
||||
const { node, index, skipped, statics, dynamics, optionals } = frame;
|
||||
let { extract, rawParams } = frame;
|
||||
if (node.kind === 2 && node.route && !isFrameMoreSpecific(bestMatch, frame)) continue;
|
||||
if (node.parse) {
|
||||
if (!validateParseParams(path, parts, frame)) continue;
|
||||
rawParams = frame.rawParams;
|
||||
extract = frame.extract;
|
||||
}
|
||||
if (fuzzy && node.route && node.kind !== SEGMENT_TYPE_INDEX && isFrameMoreSpecific(bestFuzzy, frame)) bestFuzzy = frame;
|
||||
const isBeyondPath = index === partsLength;
|
||||
if (isBeyondPath) {
|
||||
if (node.route && (!pathIsIndex || node.kind === SEGMENT_TYPE_INDEX || node.kind === 2) && isFrameMoreSpecific(bestMatch, frame)) bestMatch = frame;
|
||||
if (!node.optional && !node.wildcard && !node.index && !node.pathless) continue;
|
||||
}
|
||||
const part = isBeyondPath ? void 0 : parts[index];
|
||||
let lowerPart;
|
||||
if (isBeyondPath && node.index) {
|
||||
const indexFrame = {
|
||||
node: node.index,
|
||||
index,
|
||||
skipped,
|
||||
statics,
|
||||
dynamics,
|
||||
optionals,
|
||||
extract,
|
||||
rawParams
|
||||
};
|
||||
let indexValid = true;
|
||||
if (node.index.parse) {
|
||||
if (!validateParseParams(path, parts, indexFrame)) indexValid = false;
|
||||
}
|
||||
if (indexValid) {
|
||||
if (!dynamics && !optionals && !skipped && isPerfectStaticMatch(statics, partsLength)) return indexFrame;
|
||||
if (isFrameMoreSpecific(bestMatch, indexFrame)) bestMatch = indexFrame;
|
||||
}
|
||||
}
|
||||
if (node.wildcard) for (let i = node.wildcard.length - 1; i >= 0; i--) {
|
||||
const segment = node.wildcard[i];
|
||||
const { prefix, suffix } = segment;
|
||||
if (prefix) {
|
||||
if (isBeyondPath) continue;
|
||||
if (!(segment.caseSensitive ? part : lowerPart ??= part.toLowerCase()).startsWith(prefix)) continue;
|
||||
}
|
||||
if (suffix) {
|
||||
if (isBeyondPath) continue;
|
||||
const end = parts.slice(index).join("/");
|
||||
const suffixPart = end.slice(-suffix.length);
|
||||
if ((segment.caseSensitive ? suffixPart : suffixPart.toLowerCase()) !== suffix || end.length - suffix.length < prefix.length) continue;
|
||||
}
|
||||
stack.push({
|
||||
node: segment,
|
||||
index: partsLength,
|
||||
skipped,
|
||||
statics,
|
||||
dynamics,
|
||||
optionals,
|
||||
extract,
|
||||
rawParams
|
||||
});
|
||||
}
|
||||
if (node.optional) {
|
||||
const nextSkipped = skipped | 1 << node.depth + 1;
|
||||
for (let i = node.optional.length - 1; i >= 0; i--) {
|
||||
const segment = node.optional[i];
|
||||
stack.push({
|
||||
node: segment,
|
||||
index,
|
||||
skipped: nextSkipped,
|
||||
statics,
|
||||
dynamics,
|
||||
optionals,
|
||||
extract,
|
||||
rawParams
|
||||
});
|
||||
}
|
||||
if (!isBeyondPath) for (let i = node.optional.length - 1; i >= 0; i--) {
|
||||
const segment = node.optional[i];
|
||||
const { prefix, suffix } = segment;
|
||||
if (prefix || suffix) {
|
||||
const casePart = segment.caseSensitive ? part : lowerPart ??= part.toLowerCase();
|
||||
if (prefix && !casePart.startsWith(prefix)) continue;
|
||||
if (suffix && casePart.indexOf(suffix, casePart.length - suffix.length) < prefix.length) continue;
|
||||
}
|
||||
stack.push({
|
||||
node: segment,
|
||||
index: index + 1,
|
||||
skipped,
|
||||
statics,
|
||||
dynamics,
|
||||
optionals: optionals + segmentScore(partsLength, index),
|
||||
extract,
|
||||
rawParams
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!isBeyondPath && node.dynamic && part) for (let i = node.dynamic.length - 1; i >= 0; i--) {
|
||||
const segment = node.dynamic[i];
|
||||
const { prefix, suffix } = segment;
|
||||
if (prefix || suffix) {
|
||||
const casePart = segment.caseSensitive ? part : lowerPart ??= part.toLowerCase();
|
||||
if (prefix && !casePart.startsWith(prefix)) continue;
|
||||
if (suffix && casePart.indexOf(suffix, casePart.length - suffix.length) < prefix.length) continue;
|
||||
}
|
||||
stack.push({
|
||||
node: segment,
|
||||
index: index + 1,
|
||||
skipped,
|
||||
statics,
|
||||
dynamics: dynamics + segmentScore(partsLength, index),
|
||||
optionals,
|
||||
extract,
|
||||
rawParams
|
||||
});
|
||||
}
|
||||
if (!isBeyondPath && node.staticInsensitive) {
|
||||
const match = node.staticInsensitive.get(lowerPart ??= part.toLowerCase());
|
||||
if (match) stack.push({
|
||||
node: match,
|
||||
index: index + 1,
|
||||
skipped,
|
||||
statics: statics + segmentScore(partsLength, index),
|
||||
dynamics,
|
||||
optionals,
|
||||
extract,
|
||||
rawParams
|
||||
});
|
||||
}
|
||||
if (!isBeyondPath && node.static) {
|
||||
const match = node.static.get(part);
|
||||
if (match) stack.push({
|
||||
node: match,
|
||||
index: index + 1,
|
||||
skipped,
|
||||
statics: statics + segmentScore(partsLength, index),
|
||||
dynamics,
|
||||
optionals,
|
||||
extract,
|
||||
rawParams
|
||||
});
|
||||
}
|
||||
if (node.pathless) for (let i = node.pathless.length - 1; i >= 0; i--) {
|
||||
const segment = node.pathless[i];
|
||||
stack.push({
|
||||
node: segment,
|
||||
index,
|
||||
skipped,
|
||||
statics,
|
||||
dynamics,
|
||||
optionals,
|
||||
extract,
|
||||
rawParams
|
||||
});
|
||||
}
|
||||
}
|
||||
if (bestMatch) return bestMatch;
|
||||
if (fuzzy && bestFuzzy) {
|
||||
let sliceIndex = bestFuzzy.index;
|
||||
for (let i = 0; i < bestFuzzy.index; i++) sliceIndex += parts[i].length;
|
||||
const splat = sliceIndex === path.length ? "/" : path.slice(sliceIndex);
|
||||
bestFuzzy.rawParams ??= Object.create(null);
|
||||
bestFuzzy.rawParams["**"] = decodeURIComponent(splat);
|
||||
return bestFuzzy;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function segmentScore(partsLength, index) {
|
||||
return 2 ** (partsLength - index - 1);
|
||||
}
|
||||
function isPerfectStaticMatch(statics, partsLength) {
|
||||
return statics === 2 ** (partsLength - 1) - 1;
|
||||
}
|
||||
function validateParseParams(path, parts, frame) {
|
||||
let rawParams;
|
||||
let state;
|
||||
try {
|
||||
[rawParams, state] = extractParams(path, parts, frame);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
frame.rawParams = rawParams;
|
||||
frame.extract = state;
|
||||
if (!frame.node.parse) return true;
|
||||
try {
|
||||
if (frame.node.parse(rawParams) === false) return null;
|
||||
} catch {}
|
||||
return true;
|
||||
}
|
||||
function isFrameMoreSpecific(prev, next) {
|
||||
if (!prev) return true;
|
||||
return next.statics > prev.statics || next.statics === prev.statics && (next.dynamics > prev.dynamics || next.dynamics === prev.dynamics && (next.optionals > prev.optionals || next.optionals === prev.optionals && ((next.node.kind === SEGMENT_TYPE_INDEX) > (prev.node.kind === SEGMENT_TYPE_INDEX) || next.node.kind === SEGMENT_TYPE_INDEX === (prev.node.kind === SEGMENT_TYPE_INDEX) && next.node.depth > prev.node.depth)));
|
||||
}
|
||||
//#endregion
|
||||
exports.buildRouteBranch = buildRouteBranch;
|
||||
exports.findFlatMatch = findFlatMatch;
|
||||
exports.findRouteMatch = findRouteMatch;
|
||||
exports.findSingleMatch = findSingleMatch;
|
||||
exports.parseSegments = parseSegments;
|
||||
exports.processRouteMasks = processRouteMasks;
|
||||
exports.processRouteTree = processRouteTree;
|
||||
|
||||
//# sourceMappingURL=new-process-route-tree.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"new-process-route-tree.cjs","names":[],"sources":["../../src/new-process-route-tree.ts"],"sourcesContent":["import { invariant } from './invariant'\nimport { trimPathRight } from './path'\nimport { createSieveCache } from './sieve-cache'\nimport { last } from './utils'\nimport type { SieveCache } from './sieve-cache'\nimport type { InterpolationSegment, RouteInterpolation } from './path'\n\nexport const SEGMENT_TYPE_PATHNAME = 0\nexport const SEGMENT_TYPE_PARAM = 1\nexport const SEGMENT_TYPE_WILDCARD = 2\nexport const SEGMENT_TYPE_OPTIONAL_PARAM = 3\nconst SEGMENT_TYPE_INDEX = 4\nconst SEGMENT_TYPE_PATHLESS = 5 // only used in matching to represent pathless routes that need to carry more information\n\n/**\n * All the kinds of segments that can be present in a route path.\n */\nexport type SegmentKind =\n | typeof SEGMENT_TYPE_PATHNAME\n | typeof SEGMENT_TYPE_PARAM\n | typeof SEGMENT_TYPE_WILDCARD\n | typeof SEGMENT_TYPE_OPTIONAL_PARAM\n\n/**\n * All the kinds of segments that can be present in the segment tree.\n */\ntype ExtendedSegmentKind =\n | SegmentKind\n | typeof SEGMENT_TYPE_INDEX\n | typeof SEGMENT_TYPE_PATHLESS\n\nexport type DynamicPathSegment = [\n kind: Exclude<SegmentKind, typeof SEGMENT_TYPE_PATHNAME>,\n key: string,\n prefix: string,\n /** Undefined marks a bare splat, which discards the remaining template. */\n suffix: string | undefined,\n]\n\nexport function getParamNames(data: RouteInterpolation): Array<string> {\n const cached = data.names\n if (cached) {\n return cached\n }\n const keys: Array<string> = []\n for (const segment of data) {\n if (typeof segment !== 'string') {\n keys.push(segment[1 /* key */])\n }\n }\n return (data.names = keys)\n}\n\n/** Parse one segment for matching and retain the same record for interpolation. */\nexport function parseSegment(\n /** The full path string containing the segment. */\n path: string,\n /** The starting index of the segment within the path. */\n start: number,\n /** The next slash, or the length of the path. */\n end: number,\n): InterpolationSegment {\n const part = path.substring(start, end)\n if (part.charCodeAt(0) === 36) {\n return part.length === 1\n ? [SEGMENT_TYPE_WILDCARD, '_splat', '', undefined]\n : [SEGMENT_TYPE_PARAM, part.substring(1), '', '']\n }\n const open = part.indexOf('{')\n if (open >= 0) {\n const close = part.indexOf('}', open)\n const optional = part.charCodeAt(open + 1) === 45\n const nameStart = open + (optional ? 3 : 2)\n if (\n close >= 0 &&\n part.charCodeAt(nameStart - 1) === 36 &&\n (!optional || nameStart < close)\n ) {\n const key = part.substring(nameStart, close)\n return [\n optional\n ? SEGMENT_TYPE_OPTIONAL_PARAM\n : key\n ? SEGMENT_TYPE_PARAM\n : SEGMENT_TYPE_WILDCARD,\n key || '_splat',\n part.substring(0, open),\n path.substring(start + close + 1, key ? end : path.length),\n ]\n }\n }\n return part\n}\n\ntype ParsedRoute<T extends RouteLike> = [\n node: AnySegmentNode<T>,\n cursor: number,\n segments: RouteInterpolation | undefined,\n]\n\n/** Compile a template, optionally attaching its new segments to the matching trie. */\nexport function parseSegments<TRouteLike extends RouteLike>(\n defaultCaseSensitive: boolean,\n route: TRouteLike,\n start: number,\n): RouteInterpolation\nexport function parseSegments<TRouteLike extends RouteLike>(\n defaultCaseSensitive: boolean,\n route: TRouteLike,\n start: number,\n node: AnySegmentNode<TRouteLike>,\n dynamicListsToSort?: Array<Array<DynamicSegmentNode<TRouteLike>>>,\n parentInterpolation?: RouteInterpolation,\n): ParsedRoute<TRouteLike>\nexport function parseSegments<TRouteLike extends RouteLike>(\n defaultCaseSensitive: boolean,\n route: TRouteLike,\n start: number,\n node?: AnySegmentNode<TRouteLike>,\n /** Each dynamic sibling list is recorded once, when it first needs sorting. */\n dynamicListsToSort?: Array<Array<DynamicSegmentNode<TRouteLike>>>,\n parentInterpolation?: RouteInterpolation,\n): RouteInterpolation | ParsedRoute<TRouteLike> {\n let cursor = start\n const path = route.fullPath ?? route.from\n const options = route.options\n const length = path.length\n const literalEnd = path.endsWith('/') ? length - 1 : length\n const caseSensitive = options?.caseSensitive ?? defaultCaseSensitive\n const parseParams = options?.params?.parse ?? options?.parseParams\n let interpolation: Array<InterpolationSegment> | undefined\n let literalStart = parentInterpolation ? start - 1 : 0\n if (!node || path.includes('$')) {\n interpolation = parentInterpolation?.slice() ?? []\n const tail = last(interpolation)\n if (\n tail &&\n typeof tail !== 'string' &&\n tail[0 /* kind */] === SEGMENT_TYPE_WILDCARD\n ) {\n // A parent's wildcard consumes the child's template too.\n // `start` follows that entire tLine truncated
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
import { SieveCache } from './sieve-cache.cjs';
|
||||
import { InterpolationSegment, RouteInterpolation } from './path.cjs';
|
||||
export declare const SEGMENT_TYPE_PATHNAME = 0;
|
||||
export declare const SEGMENT_TYPE_PARAM = 1;
|
||||
export declare const SEGMENT_TYPE_WILDCARD = 2;
|
||||
export declare const SEGMENT_TYPE_OPTIONAL_PARAM = 3;
|
||||
declare const SEGMENT_TYPE_INDEX = 4;
|
||||
declare const SEGMENT_TYPE_PATHLESS = 5;
|
||||
/**
|
||||
* All the kinds of segments that can be present in a route path.
|
||||
*/
|
||||
export type SegmentKind = typeof SEGMENT_TYPE_PATHNAME | typeof SEGMENT_TYPE_PARAM | typeof SEGMENT_TYPE_WILDCARD | typeof SEGMENT_TYPE_OPTIONAL_PARAM;
|
||||
/**
|
||||
* All the kinds of segments that can be present in the segment tree.
|
||||
*/
|
||||
type ExtendedSegmentKind = SegmentKind | typeof SEGMENT_TYPE_INDEX | typeof SEGMENT_TYPE_PATHLESS;
|
||||
export type DynamicPathSegment = [
|
||||
kind: Exclude<SegmentKind, typeof SEGMENT_TYPE_PATHNAME>,
|
||||
key: string,
|
||||
prefix: string,
|
||||
/** Undefined marks a bare splat, which discards the remaining template. */
|
||||
suffix: string | undefined
|
||||
];
|
||||
export declare function getParamNames(data: RouteInterpolation): Array<string>;
|
||||
/** Parse one segment for matching and retain the same record for interpolation. */
|
||||
export declare function parseSegment(
|
||||
/** The full path string containing the segment. */
|
||||
path: string,
|
||||
/** The starting index of the segment within the path. */
|
||||
start: number,
|
||||
/** The next slash, or the length of the path. */
|
||||
end: number): InterpolationSegment;
|
||||
type ParsedRoute<T extends RouteLike> = [
|
||||
node: AnySegmentNode<T>,
|
||||
cursor: number,
|
||||
segments: RouteInterpolation | undefined
|
||||
];
|
||||
/** Compile a template, optionally attaching its new segments to the matching trie. */
|
||||
export declare function parseSegments<TRouteLike extends RouteLike>(defaultCaseSensitive: boolean, route: TRouteLike, start: number): RouteInterpolation;
|
||||
export declare function parseSegments<TRouteLike extends RouteLike>(defaultCaseSensitive: boolean, route: TRouteLike, start: number, node: AnySegmentNode<TRouteLike>, dynamicListsToSort?: Array<Array<DynamicSegmentNode<TRouteLike>>>, parentInterpolation?: RouteInterpolation): ParsedRoute<TRouteLike>;
|
||||
type StaticSegmentNode<T extends RouteLike> = SegmentNode<T> & {
|
||||
kind: typeof SEGMENT_TYPE_PATHNAME | typeof SEGMENT_TYPE_PATHLESS | typeof SEGMENT_TYPE_INDEX;
|
||||
};
|
||||
type DynamicSegmentNode<T extends RouteLike> = SegmentNode<T> & {
|
||||
kind: typeof SEGMENT_TYPE_PARAM | typeof SEGMENT_TYPE_WILDCARD | typeof SEGMENT_TYPE_OPTIONAL_PARAM;
|
||||
prefix: string;
|
||||
suffix: string;
|
||||
caseSensitive: boolean;
|
||||
};
|
||||
type AnySegmentNode<T extends RouteLike> = StaticSegmentNode<T> | DynamicSegmentNode<T>;
|
||||
type SegmentNode<T extends RouteLike> = {
|
||||
kind: ExtendedSegmentKind;
|
||||
prefix?: string;
|
||||
suffix?: string;
|
||||
caseSensitive?: boolean;
|
||||
pathless: Array<StaticSegmentNode<T>> | null;
|
||||
/** Exact index segment (highest priority) */
|
||||
index: StaticSegmentNode<T> | null;
|
||||
/** Static segments (2nd priority) */
|
||||
static: Map<string, StaticSegmentNode<T>> | null;
|
||||
/** Case insensitive static segments (3rd highest priority) */
|
||||
staticInsensitive: Map<string, StaticSegmentNode<T>> | null;
|
||||
/** Dynamic segments ($param) */
|
||||
dynamic: Array<DynamicSegmentNode<T>> | null;
|
||||
/** Optional dynamic segments ({-$param}) */
|
||||
optional: Array<DynamicSegmentNode<T>> | null;
|
||||
/** Wildcard segments ($ - lowest priority) */
|
||||
wildcard: Array<DynamicSegmentNode<T>> | null;
|
||||
/** Terminal route (if this path can end here) */
|
||||
route: T | null;
|
||||
/** Original template data for this candidate or parse gate. */
|
||||
data: RouteInterpolation | undefined;
|
||||
parent: AnySegmentNode<T> | undefined;
|
||||
depth: number;
|
||||
/** route.options.params.parse function, set on the last node of the route */
|
||||
parse: null | ((params: Record<string, string>) => unknown);
|
||||
/** route.options.params.priority ?? 0 */
|
||||
priority: number;
|
||||
};
|
||||
type RouteLike = {
|
||||
_interpolation?: RouteInterpolation;
|
||||
id?: string;
|
||||
path?: string;
|
||||
children?: Array<RouteLike>;
|
||||
parentRoute?: RouteLike;
|
||||
isRoot?: boolean;
|
||||
options?: {
|
||||
caseSensitive?: boolean;
|
||||
parseParams?: (params: Record<string, string>) => unknown;
|
||||
params?: {
|
||||
parse?: (params: Record<string, string>) => unknown;
|
||||
priority?: number;
|
||||
};
|
||||
};
|
||||
} & ({
|
||||
fullPath: string;
|
||||
from?: never;
|
||||
} | {
|
||||
fullPath?: never;
|
||||
from: string;
|
||||
});
|
||||
export type ProcessedTree<TTree extends Extract<RouteLike, {
|
||||
fullPath: string;
|
||||
}>, TFlat extends Extract<RouteLike, {
|
||||
from: string;
|
||||
}>, TSingle extends Extract<RouteLike, {
|
||||
from: string;
|
||||
}>> = {
|
||||
/** a representation of the `routeTree` as a segment tree */
|
||||
segmentTree: AnySegmentNode<TTree>;
|
||||
/** a mini route tree generated from the flat `routeMasks` list */
|
||||
masksTree: AnySegmentNode<TFlat> | null;
|
||||
/** @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree */
|
||||
singleCache: SieveCache<string, AnySegmentNode<TSingle>>;
|
||||
/** a cache of route matches from the `segmentTree` */
|
||||
matchCache: SieveCache<string, RouteMatch<TTree> | null>;
|
||||
/** a cache of route matches from the `masksTree` */
|
||||
flatCache: SieveCache<string, ReturnType<typeof findMatch<TFlat>>> | null;
|
||||
};
|
||||
export declare function processRouteMasks<TRouteLike extends Extract<RouteLike, {
|
||||
from: string;
|
||||
}>>(routeList: Array<TRouteLike>, processedTree: ProcessedTree<any, TRouteLike, any>): void;
|
||||
/**
|
||||
* Take an arbitrary list of routes, create a tree from them (if it hasn't been created already), and match a path against it.
|
||||
*/
|
||||
export declare function findFlatMatch<T extends Extract<RouteLike, {
|
||||
from: string;
|
||||
}>>(
|
||||
/** The path to match. */
|
||||
path: string,
|
||||
/** The `processedTree` returned by the initial `processRouteTree` call. */
|
||||
processedTree: ProcessedTree<any, T, any>): {
|
||||
route: T;
|
||||
/**
|
||||
* The raw (unparsed) params extracted from the path.
|
||||
* This will be the exhaustive list of all params defined in the route's path.
|
||||
*/
|
||||
rawParams: Record<string, string>;
|
||||
} | null;
|
||||
/**
|
||||
* @deprecated keep until v2 so that `router.matchRoute` can keep not caring about the actual route tree
|
||||
*/
|
||||
export declare function findSingleMatch(from: string, caseSensitive: boolean, fuzzy: boolean, path: string, processedTree: ProcessedTree<any, any, {
|
||||
from: string;
|
||||
}>): {
|
||||
route: {
|
||||
from: string;
|
||||
};
|
||||
/**
|
||||
* The raw (unparsed) params extracted from the path.
|
||||
* This will be the exhaustive list of all params defined in the route's path.
|
||||
*/
|
||||
rawParams: Record<string, string>;
|
||||
} | null;
|
||||
type RouteMatch<T extends Extract<RouteLike, {
|
||||
fullPath: string;
|
||||
}>> = {
|
||||
route: T;
|
||||
rawParams: Record<string, string>;
|
||||
branch: ReadonlyArray<T>;
|
||||
};
|
||||
export declare function findRouteMatch<T extends Extract<RouteLike, {
|
||||
fullPath: string;
|
||||
}>>(
|
||||
/** The path to match against the route tree. */
|
||||
path: string,
|
||||
/** The `processedTree` returned by the initial `processRouteTree` call. */
|
||||
processedTree: ProcessedTree<T, any, any>,
|
||||
/** If `true`, allows fuzzy matching (partial matches), i.e. which node in the tree would have been an exact match if the `path` had been shorter? */
|
||||
fuzzy?: boolean): RouteMatch<T> | null;
|
||||
export interface ProcessRouteTreeResult<TRouteLike extends Extract<RouteLike, {
|
||||
fullPath: string;
|
||||
}> & {
|
||||
id: string;
|
||||
}> {
|
||||
/** Should be considered a black box, needs to be provided to all matching functions in this module. */
|
||||
processedTree: ProcessedTree<TRouteLike, any, any>;
|
||||
/** A lookup map of routes by their unique IDs. */
|
||||
routesById: Record<string, TRouteLike>;
|
||||
/** A lookup map of routes by their trimmed full paths. */
|
||||
routesByPath: Record<string, TRouteLike>;
|
||||
}
|
||||
/**
|
||||
* Processes a route tree into a segment trie for efficient path matching.
|
||||
* Also builds lookup maps for routes by ID and by trimmed full path.
|
||||
*/
|
||||
export declare function processRouteTree<TRouteLike extends Extract<RouteLike, {
|
||||
fullPath: string;
|
||||
}> & {
|
||||
id: string;
|
||||
init: (originalIndex: number) => void;
|
||||
}>(
|
||||
/** The root of the route tree to process. */
|
||||
routeTree: TRouteLike,
|
||||
/** Whether matching should be case sensitive by default (overridden by individual route options). */
|
||||
caseSensitive?: boolean): ProcessRouteTreeResult<TRouteLike>;
|
||||
declare function findMatch<T extends RouteLike>(path: string, segmentTree: AnySegmentNode<T>, fuzzy?: boolean): {
|
||||
route: T;
|
||||
/**
|
||||
* The raw (unparsed) params extracted from the path.
|
||||
* This will be the exhaustive list of all params defined in the route's path.
|
||||
*/
|
||||
rawParams: Record<string, string>;
|
||||
} | null;
|
||||
export declare function buildRouteBranch<T extends RouteLike>(route: T): T[];
|
||||
export {};
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
//#region src/not-found.ts
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
function notFound(options = {}) {
|
||||
options.isNotFound = true;
|
||||
if (options.throw) throw options;
|
||||
return options;
|
||||
}
|
||||
/** Determine if a value is a TanStack Router not-found error. */
|
||||
function isNotFound(obj) {
|
||||
return obj?.isNotFound === true;
|
||||
}
|
||||
//#endregion
|
||||
exports.isNotFound = isNotFound;
|
||||
exports.notFound = notFound;
|
||||
|
||||
//# sourceMappingURL=not-found.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"not-found.cjs","names":[],"sources":["../../src/not-found.ts"],"sourcesContent":["import type { RouteIds } from './routeInfo'\nimport type { RegisteredRouter } from './router'\n\nexport type NotFoundError = {\n /**\n @deprecated\n Use `routeId: rootRouteId` instead\n */\n global?: boolean\n /**\n @private\n Do not use this. It's used internally to indicate a path matching error\n */\n _global?: boolean\n data?: any\n throw?: boolean\n routeId?: RouteIds<RegisteredRouter['routeTree']>\n headers?: HeadersInit\n}\n\n/**\n * Create a not-found error object recognized by TanStack Router.\n *\n * Throw this from loaders/actions to trigger the nearest `notFoundComponent`.\n * Use `routeId` to target a specific route's not-found boundary. If `throw`\n * is true, the error is thrown instead of returned.\n *\n * @param options Optional settings including `routeId`, `headers`, and `throw`.\n * @returns A not-found error object that can be thrown or returned.\n * @link https://tanstack.com/router/latest/docs/router/framework/react/api/router/notFoundFunction\n */\nexport function notFound(options: NotFoundError = {}) {\n ;(options as any).isNotFound = true\n if (options.throw) throw options\n return options\n}\n\n/** Determine if a value is a TanStack Router not-found error. */\nexport function isNotFound(obj: any): obj is NotFoundError {\n return obj?.isNotFound === true\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,SAAgB,SAAS,UAAyB,CAAC,GAAG;CACnD,QAAiB,aAAa;CAC/B,IAAI,QAAQ,OAAO,MAAM;CACzB,OAAO;AACT;;AAGA,SAAgB,WAAW,KAAgC;CACzD,OAAO,KAAK,eAAe;AAC7B"}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import { RouteIds } from './routeInfo.cjs';
|
||||
import { RegisteredRouter } from './router.cjs';
|
||||
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 declare function notFound(options?: NotFoundError): NotFoundError;
|
||||
/** Determine if a value is a TanStack Router not-found error. */
|
||||
export declare function isNotFound(obj: any): obj is NotFoundError;
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
const require_utils = require("./utils.cjs");
|
||||
//#region src/path.ts
|
||||
/** Join path segments, cleaning duplicate slashes between parts. */
|
||||
function joinPaths(paths) {
|
||||
return cleanPath(paths.filter((val) => {
|
||||
return val !== void 0;
|
||||
}).join("/"));
|
||||
}
|
||||
/** Remove repeated slashes from a path string. */
|
||||
function cleanPath(path) {
|
||||
return path.replace(/\/{2,}/g, "/");
|
||||
}
|
||||
/** Trim leading slashes (except preserving root '/'). */
|
||||
function trimPathLeft(path) {
|
||||
return path === "/" ? path : path.replace(/^\/+/, "");
|
||||
}
|
||||
/** Trim trailing slashes (except preserving root '/'). */
|
||||
function trimPathRight(path) {
|
||||
const len = path.length;
|
||||
return len > 1 && path[len - 1] === "/" ? path.replace(/\/+$/, "") : path;
|
||||
}
|
||||
/** Trim both leading and trailing slashes. */
|
||||
function trimPath(path) {
|
||||
return trimPathRight(trimPathLeft(path));
|
||||
}
|
||||
/** Remove a trailing slash from value when appropriate for comparisons. */
|
||||
function removeTrailingSlash(value, basepath) {
|
||||
if (value?.endsWith("/") && value !== "/" && value !== `${basepath}/`) return value.slice(0, -1);
|
||||
return value;
|
||||
}
|
||||
/**
|
||||
* Compare two pathnames for exact equality after normalizing trailing slashes
|
||||
* relative to the provided `basepath`.
|
||||
*/
|
||||
function exactPathTest(pathName1, pathName2, basepath) {
|
||||
return removeTrailingSlash(pathName1, basepath) === removeTrailingSlash(pathName2, basepath);
|
||||
}
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
function resolvePath(base, to, trailingSlash = "never", cache) {
|
||||
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) {
|
||||
key = isBase ? base : base + "\0" + to;
|
||||
const cached = cache.get(key);
|
||||
if (cached) return cached;
|
||||
}
|
||||
let baseSegments;
|
||||
if (isBase) baseSegments = base.split("/");
|
||||
else {
|
||||
if (base.includes("//")) base = cleanPath(base);
|
||||
baseSegments = base.split("/");
|
||||
while (baseSegments.length > 1 && require_utils.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) baseSegments = [value];
|
||||
else if (index === length - 1) baseSegments.push(value);
|
||||
} else if (value === "..") if (baseSegments.length > 1) baseSegments.pop();
|
||||
else baseSegments = [""];
|
||||
else if (value === ".") {} else baseSegments.push(value);
|
||||
}
|
||||
}
|
||||
if (baseSegments.length > 1) {
|
||||
if (require_utils.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.
|
||||
*/
|
||||
function compileDecodeCharMap(pathParamsAllowedCharacters) {
|
||||
const charMap = new Map(pathParamsAllowedCharacters.map((char) => [encodeURIComponent(char), char]));
|
||||
const regex = new RegExp([...charMap.keys()].join("|").replace(/[.*()]/g, "\\$&"), "g");
|
||||
return (encoded) => encoded.replace(regex, (match) => charMap.get(match) ?? match);
|
||||
}
|
||||
function getRouteSegments(route) {
|
||||
return route._interpolation;
|
||||
}
|
||||
/** A splat is missing when it has no value; `0` and `false` are stringified like any other param. */
|
||||
function isMissingSplat(value) {
|
||||
return value == null || value === "";
|
||||
}
|
||||
/** Devtools checks navigation availability separately from the hot formatter. */
|
||||
function hasMissingPathParams(segments, params) {
|
||||
return segments.some((part) => {
|
||||
if (typeof part === "string") return false;
|
||||
const [kind, key] = part;
|
||||
return kind === 2 ? isMissingSplat(params[key]) : kind === 1 && !(key in params);
|
||||
});
|
||||
}
|
||||
function encodeParam(key, value, decoder) {
|
||||
if (typeof value !== "string") return "" + (value ?? void 0);
|
||||
const splat = key === "_splat";
|
||||
if (splat && (!value || /^[a-zA-Z0-9\-._~!/]*$/.test(value))) return value;
|
||||
let encoded = encodeURIComponent(value);
|
||||
if (splat) encoded = encoded.replaceAll("%2F", "/");
|
||||
return decoder ? decoder(encoded) : encoded;
|
||||
}
|
||||
/** Substitute current values into parsed segments, optionally collecting raw params. */
|
||||
function interpolatePath(path, segments, params, decoder, usedParams) {
|
||||
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 === 2;
|
||||
const suffix = splat && rawSuffix !== void 0 ? rawSuffix + trailingSlash : rawSuffix;
|
||||
let paramValue = params[key];
|
||||
if (kind === 3 && paramValue == null) continue;
|
||||
if (usedParams) {
|
||||
usedParams[key] = paramValue;
|
||||
if (splat) usedParams["*"] = paramValue;
|
||||
}
|
||||
if (splat && isMissingSplat(paramValue)) {
|
||||
if (prefix === "/" && !suffix) continue;
|
||||
paramValue = "";
|
||||
}
|
||||
joined += prefix + encodeParam(key, paramValue, decoder) + (suffix || "");
|
||||
}
|
||||
return joined + trailingSlash || "/";
|
||||
}
|
||||
//#endregion
|
||||
exports.cleanPath = cleanPath;
|
||||
exports.compileDecodeCharMap = compileDecodeCharMap;
|
||||
exports.exactPathTest = exactPathTest;
|
||||
exports.getRouteSegments = getRouteSegments;
|
||||
exports.hasMissingPathParams = hasMissingPathParams;
|
||||
exports.interpolatePath = interpolatePath;
|
||||
exports.joinPaths = joinPaths;
|
||||
exports.removeTrailingSlash = removeTrailingSlash;
|
||||
exports.resolvePath = resolvePath;
|
||||
exports.trimPath = trimPath;
|
||||
exports.trimPathLeft = trimPathLeft;
|
||||
exports.trimPathRight = trimPathRight;
|
||||
|
||||
//# sourceMappingURL=path.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"path.cjs","names":[],"sources":["../../src/path.ts"],"sourcesContent":["import { last } from './utils'\nimport {\n SEGMENT_TYPE_OPTIONAL_PARAM,\n SEGMENT_TYPE_PARAM,\n SEGMENT_TYPE_WILDCARD,\n} from './new-process-route-tree'\nimport type { SieveCache } from './sieve-cache'\nimport type { DynamicPathSegment } from './new-process-route-tree'\nimport type { AnyRoute } from './route'\n\n/** Join path segments, cleaning duplicate slashes between parts. */\nexport function joinPaths(paths: Array<string | undefined>) {\n return cleanPath(\n paths\n .filter((val) => {\n return val !== undefined\n })\n .join('/'),\n )\n}\n\n/** Remove repeated slashes from a path string. */\nexport function cleanPath(path: string) {\n // remove double slashes\n return path.replace(/\\/{2,}/g, '/')\n}\n\n/** Trim leading slashes (except preserving root '/'). */\nexport function trimPathLeft(path: string) {\n return path === '/' ? path : path.replace(/^\\/+/, '')\n}\n\n/** Trim trailing slashes (except preserving root '/'). */\nexport function trimPathRight(path: string) {\n const len = path.length\n return len > 1 && path[len - 1] === '/' ? path.replace(/\\/+$/, '') : path\n}\n\n/** Trim both leading and trailing slashes. */\nexport function trimPath(path: string) {\n return trimPathRight(trimPathLeft(path))\n}\n\n/** Remove a trailing slash from value when appropriate for comparisons. */\nexport function removeTrailingSlash(value: string, basepath: string): string {\n if (value?.endsWith('/') && value !== '/' && value !== `${basepath}/`) {\n return value.slice(0, -1)\n }\n return value\n}\n\n// intended to only compare path name\n// see the usage in the isActive under useLinkProps\n// /sample/path1 = /sample/path1/\n// /sample/path1/some <> /sample/path1\n/**\n * Compare two pathnames for exact equality after normalizing trailing slashes\n * relative to the provided `basepath`.\n */\nexport function exactPathTest(\n pathName1: string,\n pathName2: string,\n basepath: string,\n): boolean {\n return (\n removeTrailingSlash(pathName1, basepath) ===\n removeTrailingSlash(pathName2, basepath)\n )\n}\n\n// When resolving relative paths, we treat all paths as if they are trailing slash\n// documents. All trailing slashes are removed after the path is resolved.\n// Here are a few examples:\n//\n// /a/b/c + ./d = /a/b/c/d\n// /a/b/c + ../d = /a/b/d\n// /a/b/c + ./d/ = /a/b/c/d\n// /a/b/c + ../d/ = /a/b/d\n// /a/b/c + ./ = /a/b/c\n//\n// Absolute paths that start with `/` short circuit the resolution process to the root\n// path.\n//\n// Here are some examples:\n//\n// /a/b/c + /d = /d\n// /a/b/c + /d/ = /d\n// /a/b/c + / = /\n//\n// Non-.-prefixed paths are still treated as relative paths, resolved like `./`\n//\n// Here are some examples:\n//\n// /a/b/c + d = /a/b/c/d\n// /a/b/c + d/ = /a/b/c/d\n// /a/b/c + d/e = /a/b/c/d/e\n/**\n * Resolve a destination path against a base, honoring trailing-slash policy\n * and supporting relative segments (`.`/`..`) and absolute `to` values.\n *\n * Internal: parameters are positional so the router's hot callers pass no\n * options object.\n */\nexport function resolvePath(\n base: string,\n to: string,\n trailingSlash: 'always' | 'never' | 'preserve' = 'never',\n cache?: SieveCache<string, string>,\n) {\n if (to.includes('//')) {\n to = cleanPath(to)\n }\n\n if (to.startsWith('/')) {\n if (to.length === 1 || trailingSlash === 'preserve') {\n return to\n }\n if (trailingSlash === 'always') {\n return to.endsWith('/') ? to : `${to}/`\n }\n return to.endsWith('/') ? to.slice(0, -1) : to\n }\n\n const isBase = to === '.'\n let key\n if (cache) {\n // `trailingSlash` is static per router, so it doesn't need to be part of the cache key\n key = isBase ? base : base + '\\0' + to\n const cached = cache.get(key)\n if (cached) return cached\n }\n\n let baseSegments: Array<string>\n if (isBase) {\n baseSegments = base.split('/')\n } else {\n if (base.includes('//')) {\n base = cleanPath(base)\n }\n baseSegments = base.split('/')\n while (baseSegments.length > 1 && last(baseSegments) === '') {\n baseSegments.pop()\n }\n\n const toSegments = to.split('/')\n for (let index = 0, length = toSegments.length; index < length; index++) {\n const value = toSegments[index]!\n if (value === '') {\n if (!index) {\n // Leading slash\n baseSegments = [value]\n } else if (index === length - 1) {\n // Trailing Slash\n baseSegments.push(value)\n } else {\n // ignore inter-slashes\n }\n } else if (value === '..') {\n if (baseSegments.length > 1) {\n baseSegments.pop()\n } else {\n baseSegments = ['']\n }\n } else if (value === '.') {\n // ignore\n } else {\n baseSegments.push(value)\n }\n }\n }\n\n if (baseSegmentLine truncated
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
import { SieveCache } from './sieve-cache.cjs';
|
||||
import { DynamicPathSegment } from './new-process-route-tree.cjs';
|
||||
import { AnyRoute } from './route.cjs';
|
||||
/** Join path segments, cleaning duplicate slashes between parts. */
|
||||
export declare function joinPaths(paths: Array<string | undefined>): string;
|
||||
/** Remove repeated slashes from a path string. */
|
||||
export declare function cleanPath(path: string): string;
|
||||
/** Trim leading slashes (except preserving root '/'). */
|
||||
export declare function trimPathLeft(path: string): string;
|
||||
/** Trim trailing slashes (except preserving root '/'). */
|
||||
export declare function trimPathRight(path: string): string;
|
||||
/** Trim both leading and trailing slashes. */
|
||||
export declare function trimPath(path: string): string;
|
||||
/** Remove a trailing slash from value when appropriate for comparisons. */
|
||||
export declare function removeTrailingSlash(value: string, basepath: string): string;
|
||||
/**
|
||||
* Compare two pathnames for exact equality after normalizing trailing slashes
|
||||
* relative to the provided `basepath`.
|
||||
*/
|
||||
export declare function exactPathTest(pathName1: string, pathName2: string, basepath: string): boolean;
|
||||
/**
|
||||
* 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 declare function resolvePath(base: string, to: string, trailingSlash?: 'always' | 'never' | 'preserve', cache?: SieveCache<string, string>): string;
|
||||
/**
|
||||
* Create a pre-compiled decode config from allowed characters.
|
||||
* Created once for the router's fixed encoding configuration.
|
||||
*/
|
||||
export declare function compileDecodeCharMap(pathParamsAllowedCharacters: ReadonlyArray<string>): (encoded: string) => string;
|
||||
export type InterpolationSegment = string | DynamicPathSegment;
|
||||
export type RouteInterpolation = Array<InterpolationSegment> & {
|
||||
names?: Array<string>;
|
||||
};
|
||||
export declare function getRouteSegments(route: AnyRoute): RouteInterpolation | undefined;
|
||||
/** Devtools checks navigation availability separately from the hot formatter. */
|
||||
export declare function hasMissingPathParams(segments: RouteInterpolation, params: Record<string, unknown>): boolean;
|
||||
/** Substitute current values into parsed segments, optionally collecting raw params. */
|
||||
export declare function interpolatePath(path: string, segments: RouteInterpolation, params: Record<string, unknown>, decoder?: (encoded: string) => string, usedParams?: Record<string, unknown>): string;
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
//#region src/qss.ts
|
||||
/**
|
||||
* 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"
|
||||
* ```
|
||||
*/
|
||||
function encode(obj, stringify = String) {
|
||||
let result;
|
||||
for (const key in obj) {
|
||||
const val = obj[key];
|
||||
if (val !== void 0) (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) {
|
||||
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" }
|
||||
*/
|
||||
function decode(str) {
|
||||
const searchParams = new URLSearchParams(str);
|
||||
const result = 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;
|
||||
}
|
||||
//#endregion
|
||||
exports.decode = decode;
|
||||
exports.encode = encode;
|
||||
|
||||
//# sourceMappingURL=qss.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"qss.cjs","names":[],"sources":["../../src/qss.ts"],"sourcesContent":["/**\n * Program is a reimplementation of the `qss` package:\n * Copyright (c) Luke Edwards luke.edwards05@gmail.com, MIT License\n * https://github.com/lukeed/qss/blob/master/license.md\n *\n * This reimplementation uses modern browser APIs\n * (namely URLSearchParams) and TypeScript while still\n * maintaining the original functionality and interface.\n *\n * Update: this implementation has also been mangled to\n * fit exactly our use-case (single value per key in encoding).\n */\n\n/**\n * Encodes an object into a query string.\n * @param obj - The object to encode into a query string.\n * @param stringify - An optional custom stringify function.\n * @returns The encoded query string.\n * @example\n * ```\n * // Example input: encode({ token: 'foo', key: 'value' })\n * // Expected output: \"token=foo&key=value\"\n * ```\n */\nexport function encode(\n obj: Record<string, any>,\n stringify: (value: any) => string = String,\n): string {\n let result: URLSearchParams | undefined\n\n for (const key in obj) {\n const val = obj[key]\n if (val !== undefined) {\n ;(result ||= new URLSearchParams()).set(key, stringify(val))\n }\n }\n\n return result ? result.toString() : ''\n}\n\n/**\n * Converts a string value to its appropriate type (string, number, boolean).\n * @param mix - The string value to convert.\n * @returns The converted value.\n * @example\n * // Example input: toValue(\"123\")\n * // Expected output: 123\n */\nfunction toValue(str: unknown) {\n if (!str) return ''\n\n if (str === 'false') return false\n if (str === 'true') return true\n return +str * 0 === 0 && +str + '' === str ? +str : str\n}\n/**\n * Decodes a query string into an object.\n * @param str - The query string to decode.\n * @returns The decoded key-value pairs in an object format.\n * @example\n * // Example input: decode(\"token=foo&key=value\")\n * // Expected output: { \"token\": \"foo\", \"key\": \"value\" }\n */\nexport function decode(str: any): any {\n const searchParams = new URLSearchParams(str)\n\n const result: Record<string, unknown> = Object.create(null)\n\n for (const [key, value] of searchParams.entries()) {\n const previousValue = result[key]\n if (previousValue == null) {\n result[key] = toValue(value)\n } else if (Array.isArray(previousValue)) {\n previousValue.push(toValue(value))\n } else {\n result[key] = [previousValue, toValue(value)]\n }\n }\n\n return result\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,OACd,KACA,YAAoC,QAC5B;CACR,IAAI;CAEJ,KAAK,MAAM,OAAO,KAAK;EACrB,MAAM,MAAM,IAAI;EAChB,IAAI,QAAQ,KAAA,GACT,CAAC,WAAW,IAAI,gBAAgB,GAAG,IAAI,KAAK,UAAU,GAAG,CAAC;CAE/D;CAEA,OAAO,SAAS,OAAO,SAAS,IAAI;AACtC;;;;;;;;;AAUA,SAAS,QAAQ,KAAc;CAC7B,IAAI,CAAC,KAAK,OAAO;CAEjB,IAAI,QAAQ,SAAS,OAAO;CAC5B,IAAI,QAAQ,QAAQ,OAAO;CAC3B,OAAO,CAAC,MAAM,MAAM,KAAK,CAAC,MAAM,OAAO,MAAM,CAAC,MAAM;AACtD;;;;;;;;;AASA,SAAgB,OAAO,KAAe;CACpC,MAAM,eAAe,IAAI,gBAAgB,GAAG;CAE5C,MAAM,SAAkC,OAAO,OAAO,IAAI;CAE1D,KAAK,MAAM,CAAC,KAAK,UAAU,aAAa,QAAQ,GAAG;EACjD,MAAM,gBAAgB,OAAO;EAC7B,IAAI,iBAAiB,MACnB,OAAO,OAAO,QAAQ,KAAK;OACtB,IAAI,MAAM,QAAQ,aAAa,GACpC,cAAc,KAAK,QAAQ,KAAK,CAAC;OAEjC,OAAO,OAAO,CAAC,eAAe,QAAQ,KAAK,CAAC;CAEhD;CAEA,OAAO;AACT"}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* 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 declare function encode(obj: Record<string, any>, stringify?: (value: any) => string): string;
|
||||
/**
|
||||
* 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 declare function decode(str: any): any;
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
//#region src/redirect.ts
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
function redirect(opts) {
|
||||
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.options = opts;
|
||||
if (opts.throw) throw response;
|
||||
return response;
|
||||
}
|
||||
/** Check whether a value is a TanStack Router redirect Response. */
|
||||
function isRedirect(obj) {
|
||||
return obj instanceof Response && !!obj.options;
|
||||
}
|
||||
/** True if value is a redirect with a resolved `href` location. */
|
||||
function isResolvedRedirect(obj) {
|
||||
return isRedirect(obj) && !!obj.options.href;
|
||||
}
|
||||
/** Parse a serialized redirect object back into a redirect Response. */
|
||||
function parseRedirect(obj) {
|
||||
if (obj !== null && typeof obj === "object" && obj.isSerializedRedirect) return redirect(obj);
|
||||
}
|
||||
//#endregion
|
||||
exports.isRedirect = isRedirect;
|
||||
exports.isResolvedRedirect = isResolvedRedirect;
|
||||
exports.parseRedirect = parseRedirect;
|
||||
exports.redirect = redirect;
|
||||
|
||||
//# sourceMappingURL=redirect.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"redirect.cjs","names":[],"sources":["../../src/redirect.ts"],"sourcesContent":["import type { NavigateOptions } from './link'\nimport type { AnyRouter, RegisteredRouter } from './router'\n\nexport type AnyRedirect = Redirect<any, any, any, any, any>\n\n/**\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType)\n */\nexport type Redirect<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = Response & {\n options: NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>\n}\n\nexport type RedirectOptions<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string | undefined = undefined,\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '.',\n> = {\n href?: string\n /**\n * @deprecated Use `statusCode` instead\n **/\n code?: number\n /**\n * The HTTP status code to use when redirecting.\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType#statuscode-property)\n */\n statusCode?: number\n /**\n * 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.\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType#throw-property)\n */\n throw?: any\n /**\n * The HTTP headers to use when redirecting.\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType#headers-property)\n */\n headers?: HeadersInit\n} & NavigateOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>\n\nexport type ResolvedRedirect<\n TRouter extends AnyRouter = RegisteredRouter,\n TFrom extends string = string,\n TTo extends string = '',\n TMaskFrom extends string = TFrom,\n TMaskTo extends string = '',\n> = Redirect<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>\n\n/**\n * Options for route-bound redirect, where 'from' is automatically set.\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType)\n */\nexport type RedirectOptionsRoute<\n TDefaultFrom extends string = string,\n TRouter extends AnyRouter = RegisteredRouter,\n TTo extends string | undefined = undefined,\n TMaskTo extends string = '',\n> = Omit<\n RedirectOptions<TRouter, TDefaultFrom, TTo, TDefaultFrom, TMaskTo>,\n 'from'\n>\n\n/**\n * A redirect function bound to a specific route, with 'from' pre-set to the route's fullPath.\n * This enables relative redirects like `Route.redirect({ to: './overview' })`.\n * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType)\n */\nexport interface RedirectFnRoute<in out TDefaultFrom extends string = string> {\n <\n TRouter extends AnyRouter = RegisteredRouter,\n const TTo extends string | undefined = undefined,\n const TMaskTo extends string = '',\n >(\n opts: RedirectOptionsRoute<TDefaultFrom, TRouter, TTo, TMaskTo>,\n ): Redirect<TRouter, TDefaultFrom, TTo, TDefaultFrom, TMaskTo>\n}\n\n/**\n * Create a redirect Response understood by TanStack Router.\n *\n * Use from route `loader`/`beforeLoad` or server functions to trigger a\n * navigation. If `throw: true` is set, the redirect is thrown instead of\n * returned. External `href` values are classified as full-document\n * navigations when the router resolves the redirect.\n *\n * @param opts Options for the redirect. Common fields:\n * - `href`: absolute URL for external redirects.\n * - `statusCode`: HTTP status code to use (defaults to 307).\n * - `headers`: additional headers to include on the Response.\n * - Standard navigation options like `to`, `params`, `search`, `replace`,\n * and `reloadDocument` for internal redirects.\n * @returns A Response augmented with router navigation options.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction\n */\nexport function redirect<\n TRouter extends AnyRouter = RegisteredRouter,\n const TTo extends string | undefined = '.',\n const TFrom extends string = string,\n const TMaskFrom extends string = TFrom,\n const TMaskTo extends string = '',\n>(\n opts: RedirectOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,\n): Redirect<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> {\n opts.statusCode = opts.statusCode || opts.code || 307\n\n const headers = new Headers(opts.headers)\n if (opts.href && headers.get('Location') === null) {\n headers.set('Location', opts.href)\n }\n\n const response = new Response(null, {\n status: opts.statusCode,\n headers,\n })\n\n ;(response as Redirect<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>).options =Line truncated
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
import { NavigateOptions } from './link.cjs';
|
||||
import { AnyRouter, RegisteredRouter } from './router.cjs';
|
||||
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 declare 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>;
|
||||
/** Check whether a value is a TanStack Router redirect Response. */
|
||||
export declare function isRedirect(obj: any): obj is AnyRedirect;
|
||||
/** True if value is a redirect with a resolved `href` location. */
|
||||
export declare function isResolvedRedirect(obj: any): obj is AnyRedirect & {
|
||||
options: {
|
||||
href: string;
|
||||
};
|
||||
};
|
||||
/** Parse a serialized redirect object back into a redirect Response. */
|
||||
export declare function parseRedirect(obj: any): Redirect<AnyRouter, string, ".", string, ""> | undefined;
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
const require_path = require("./path.cjs");
|
||||
//#region src/rewrite.ts
|
||||
/** Compose multiple rewrite pairs into a single in/out rewrite. */
|
||||
function composeRewrites(rewrites) {
|
||||
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;
|
||||
}
|
||||
};
|
||||
}
|
||||
/** Create a rewrite pair that strips/adds a basepath on input/output. */
|
||||
function rewriteBasepath(basepath, caseSensitive, rewrite) {
|
||||
const trimmedBasepath = require_path.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();
|
||||
if (pathname === checkBasepath) url.pathname = "/";
|
||||
else if (pathname.startsWith(checkBasepathWithSlash)) url.pathname = url.pathname.slice(normalizedBasepath.length);
|
||||
return url;
|
||||
},
|
||||
output: ({ url }) => {
|
||||
url.pathname = require_path.cleanPath(`/${trimmedBasepath}${url.pathname}`);
|
||||
return url;
|
||||
}
|
||||
};
|
||||
return rewrite ? {
|
||||
input: ({ url }) => executeRewriteInput(rewrite, basepathRewrite.input({ url })),
|
||||
output: ({ url }) => basepathRewrite.output({ url: executeRewriteOutput(rewrite, url) })
|
||||
} : basepathRewrite;
|
||||
}
|
||||
/** Execute a location input rewrite if provided. */
|
||||
function executeRewriteInput(rewrite, 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. */
|
||||
function executeRewriteOutput(rewrite, 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;
|
||||
}
|
||||
//#endregion
|
||||
exports.composeRewrites = composeRewrites;
|
||||
exports.executeRewriteInput = executeRewriteInput;
|
||||
exports.executeRewriteOutput = executeRewriteOutput;
|
||||
exports.rewriteBasepath = rewriteBasepath;
|
||||
|
||||
//# sourceMappingURL=rewrite.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"rewrite.cjs","names":[],"sources":["../../src/rewrite.ts"],"sourcesContent":["import { cleanPath, trimPath } from './path'\nimport type { LocationRewrite } from './router'\n\n/** Compose multiple rewrite pairs into a single in/out rewrite. */\nexport function composeRewrites(rewrites: Array<LocationRewrite>) {\n return {\n input: ({ url }) => {\n for (const rewrite of rewrites) {\n url = executeRewriteInput(rewrite, url)\n }\n return url\n },\n output: ({ url }) => {\n for (let i = rewrites.length - 1; i >= 0; i--) {\n url = executeRewriteOutput(rewrites[i], url)\n }\n return url\n },\n } satisfies LocationRewrite\n}\n\n/** Create a rewrite pair that strips/adds a basepath on input/output. */\nexport function rewriteBasepath(\n basepath: string,\n caseSensitive?: boolean,\n rewrite?: LocationRewrite,\n) {\n const trimmedBasepath = trimPath(basepath)\n const normalizedBasepath = `/${trimmedBasepath}`\n const checkBasepath = caseSensitive\n ? normalizedBasepath\n : normalizedBasepath.toLowerCase()\n const checkBasepathWithSlash = `${checkBasepath}/`\n\n const basepathRewrite = {\n input: ({ url }) => {\n const pathname = caseSensitive ? url.pathname : url.pathname.toLowerCase()\n\n // Handle exact basepath match (e.g., /my-app -> /)\n if (pathname === checkBasepath) {\n url.pathname = '/'\n } else if (pathname.startsWith(checkBasepathWithSlash)) {\n // Handle basepath with trailing content (e.g., /my-app/users -> /users)\n url.pathname = url.pathname.slice(normalizedBasepath.length)\n }\n return url\n },\n output: ({ url }) => {\n // `url.pathname` always starts with \"/\", so only slashes already inside\n // it can repeat; cleanPath keeps the joinPaths normalization.\n url.pathname = cleanPath(`/${trimmedBasepath}${url.pathname}`)\n return url\n },\n } satisfies LocationRewrite\n\n // Strip the basepath before custom input and restore it after custom output.\n return rewrite\n ? ({\n input: ({ url }) =>\n executeRewriteInput(rewrite, basepathRewrite.input({ url })),\n output: ({ url }) =>\n basepathRewrite.output({ url: executeRewriteOutput(rewrite, url) }),\n } satisfies LocationRewrite)\n : basepathRewrite\n}\n\n/** Execute a location input rewrite if provided. */\nexport function executeRewriteInput(\n rewrite: LocationRewrite | undefined,\n url: URL,\n): URL {\n const res = rewrite?.input?.({ url })\n if (res) {\n if (typeof res === 'string') {\n return new URL(res)\n } else if (res instanceof URL) {\n return res\n }\n }\n return url\n}\n\n/** Execute a location output rewrite if provided. */\nexport function executeRewriteOutput(\n rewrite: LocationRewrite | undefined,\n url: URL,\n): URL {\n const res = rewrite?.output?.({ url })\n if (res) {\n if (typeof res === 'string') {\n return new URL(res)\n } else if (res instanceof URL) {\n return res\n }\n }\n return url\n}\n"],"mappings":";;;AAIA,SAAgB,gBAAgB,UAAkC;CAChE,OAAO;EACL,QAAQ,EAAE,UAAU;GAClB,KAAK,MAAM,WAAW,UACpB,MAAM,oBAAoB,SAAS,GAAG;GAExC,OAAO;EACT;EACA,SAAS,EAAE,UAAU;GACnB,KAAK,IAAI,IAAI,SAAS,SAAS,GAAG,KAAK,GAAG,KACxC,MAAM,qBAAqB,SAAS,IAAI,GAAG;GAE7C,OAAO;EACT;CACF;AACF;;AAGA,SAAgB,gBACd,UACA,eACA,SACA;CACA,MAAM,kBAAkB,aAAA,SAAS,QAAQ;CACzC,MAAM,qBAAqB,IAAI;CAC/B,MAAM,gBAAgB,gBAClB,qBACA,mBAAmB,YAAY;CACnC,MAAM,yBAAyB,GAAG,cAAc;CAEhD,MAAM,kBAAkB;EACtB,QAAQ,EAAE,UAAU;GAClB,MAAM,WAAW,gBAAgB,IAAI,WAAW,IAAI,SAAS,YAAY;GAGzE,IAAI,aAAa,eACf,IAAI,WAAW;QACV,IAAI,SAAS,WAAW,sBAAsB,GAEnD,IAAI,WAAW,IAAI,SAAS,MAAM,mBAAmB,MAAM;GAE7D,OAAO;EACT;EACA,SAAS,EAAE,UAAU;GAGnB,IAAI,WAAW,aAAA,UAAU,IAAI,kBAAkB,IAAI,UAAU;GAC7D,OAAO;EACT;CACF;CAGA,OAAO,UACF;EACC,QAAQ,EAAE,UACR,oBAAoB,SAAS,gBAAgB,MAAM,EAAE,IAAI,CAAC,CAAC;EAC7D,SAAS,EAAE,UACT,gBAAgB,OAAO,EAAE,KAAK,qBAAqB,SAAS,GAAG,EAAE,CAAC;CACtE,IACA;AACN;;AAGA,SAAgB,oBACd,SACA,KACK;CACL,MAAM,MAAM,SAAS,QAAQ,EAAE,IAAI,CAAC;CACpC,IAAI;MACE,OAAO,QAAQ,UACjB,OAAO,IAAI,IAAI,GAAG;OACb,IAAI,eAAe,KACxB,OAAO;CAAA;CAGX,OAAO;AACT;;AAGA,SAAgB,qBACd,SACA,KACK;CACL,MAAM,MAAM,SAAS,SAAS,EAAE,IAAI,CAAC;CACrC,IAAI;MACE,OAAO,QAAQ,UACjB,OAAO,IAAI,IAAI,GAAG;OACb,IAAI,eAAe,KACxB,OAAO;CAAA;CAGX,OAAO;AACT"}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import { LocationRewrite } from './router.cjs';
|
||||
/** Compose multiple rewrite pairs into a single in/out rewrite. */
|
||||
export declare function composeRewrites(rewrites: Array<LocationRewrite>): {
|
||||
input: ({ url }: {
|
||||
url: URL;
|
||||
}) => URL;
|
||||
output: ({ url }: {
|
||||
url: URL;
|
||||
}) => URL;
|
||||
};
|
||||
/** Create a rewrite pair that strips/adds a basepath on input/output. */
|
||||
export declare function rewriteBasepath(basepath: string, caseSensitive?: boolean, rewrite?: LocationRewrite): {
|
||||
input: ({ url }: {
|
||||
url: URL;
|
||||
}) => URL;
|
||||
output: ({ url }: {
|
||||
url: URL;
|
||||
}) => URL;
|
||||
};
|
||||
/** Execute a location input rewrite if provided. */
|
||||
export declare function executeRewriteInput(rewrite: LocationRewrite | undefined, url: URL): URL;
|
||||
/** Execute a location output rewrite if provided. */
|
||||
export declare function executeRewriteOutput(rewrite: LocationRewrite | undefined, url: URL): URL;
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
//#region src/root.ts
|
||||
/** Stable identifier used for the root route in a route tree. */
|
||||
const rootRouteId = "__root__";
|
||||
//#endregion
|
||||
exports.rootRouteId = rootRouteId;
|
||||
|
||||
//# sourceMappingURL=root.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"root.cjs","names":[],"sources":["../../src/root.ts"],"sourcesContent":["/** Stable identifier used for the root route in a route tree. */\nexport const rootRouteId = '__root__'\nexport type RootRouteId = typeof rootRouteId\n"],"mappings":";;AACA,MAAa,cAAc"}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
/** Stable identifier used for the root route in a route tree. */
|
||||
export declare const rootRouteId = "__root__";
|
||||
export type RootRouteId = typeof rootRouteId;
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
const require_invariant = require("./invariant.cjs");
|
||||
const require_path = require("./path.cjs");
|
||||
const require_not_found = require("./not-found.cjs");
|
||||
const require_root = require("./root.cjs");
|
||||
const require_redirect = require("./redirect.cjs");
|
||||
//#region src/route.ts
|
||||
var BaseRoute = class {
|
||||
get to() {
|
||||
return this._to;
|
||||
}
|
||||
get id() {
|
||||
return this._id;
|
||||
}
|
||||
get path() {
|
||||
return this._path;
|
||||
}
|
||||
get fullPath() {
|
||||
return this._fullPath;
|
||||
}
|
||||
constructor(options) {
|
||||
this.init = (originalIndex) => {
|
||||
this.originalIndex = originalIndex;
|
||||
this._branch = void 0;
|
||||
const options = this.options;
|
||||
const isRoot = !options?.path && !options?.id;
|
||||
this.parentRoute = this.options.getParentRoute?.();
|
||||
if (isRoot) this._path = require_root.rootRouteId;
|
||||
else if (!this.parentRoute) {
|
||||
if (process.env.NODE_ENV !== "production") throw new Error(`Invariant failed: Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a Route instance.`);
|
||||
require_invariant.invariant();
|
||||
}
|
||||
let path = isRoot ? require_root.rootRouteId : options?.path;
|
||||
if (path && path !== "/") path = require_path.trimPathLeft(path);
|
||||
const customId = options?.id || path;
|
||||
const id = isRoot ? require_root.rootRouteId : require_path.cleanPath((this.parentRoute.id === "__root__" ? "" : this.parentRoute.id) + "/" + (customId ?? ""));
|
||||
if (path === "__root__") path = "/";
|
||||
const fullPath = id === "__root__" ? "/" : path === void 0 ? this.parentRoute.fullPath : require_path.cleanPath(this.parentRoute.fullPath + "/" + path);
|
||||
this._path = path;
|
||||
this._id = id;
|
||||
this._fullPath = fullPath;
|
||||
this._to = require_path.trimPathRight(fullPath);
|
||||
};
|
||||
this.addChildren = (children) => {
|
||||
return this._addFileChildren(children);
|
||||
};
|
||||
this._addFileChildren = (children) => {
|
||||
if (Array.isArray(children)) this.children = children;
|
||||
if (typeof children === "object" && children !== null) this.children = Object.values(children);
|
||||
return this;
|
||||
};
|
||||
this._addFileTypes = () => {
|
||||
return this;
|
||||
};
|
||||
this.updateLoader = (options) => {
|
||||
Object.assign(this.options, options);
|
||||
return this;
|
||||
};
|
||||
this.update = (options) => {
|
||||
Object.assign(this.options, options);
|
||||
return this;
|
||||
};
|
||||
this.lazy = (lazyFn) => {
|
||||
this.lazyFn = lazyFn;
|
||||
return this;
|
||||
};
|
||||
this.redirect = (opts) => require_redirect.redirect({
|
||||
from: this.fullPath,
|
||||
...opts
|
||||
});
|
||||
this.options = options || {};
|
||||
this.isRoot = !options?.getParentRoute;
|
||||
if (options?.id && options?.path) throw new Error(`Route cannot have both an 'id' and a 'path' option.`);
|
||||
}
|
||||
};
|
||||
var BaseRouteApi = class {
|
||||
constructor({ id }) {
|
||||
this.notFound = (opts) => {
|
||||
return require_not_found.notFound({
|
||||
routeId: this.id,
|
||||
...opts
|
||||
});
|
||||
};
|
||||
this.redirect = (opts) => require_redirect.redirect({
|
||||
from: this.id,
|
||||
...opts
|
||||
});
|
||||
this.id = id;
|
||||
}
|
||||
};
|
||||
var BaseRootRoute = class extends BaseRoute {
|
||||
constructor(options) {
|
||||
super(options);
|
||||
}
|
||||
};
|
||||
//#endregion
|
||||
exports.BaseRootRoute = BaseRootRoute;
|
||||
exports.BaseRoute = BaseRoute;
|
||||
exports.BaseRouteApi = BaseRouteApi;
|
||||
|
||||
//# sourceMappingURL=route.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"route.cjs","names":[],"sources":["../../src/route.ts"],"sourcesContent":["import { invariant } from './invariant'\nimport { cleanPath, trimPathLeft, trimPathRight } from './path'\nimport { notFound } from './not-found'\nimport { redirect } from './redirect'\nimport { rootRouteId } from './root'\nimport type { LazyRoute } from './fileRoute'\nimport type { RouteInterpolation } from './path'\nimport type { NotFoundError } from './not-found'\nimport type { RedirectFnRoute } from './redirect'\nimport type { NavigateOptions, ParsePathParams } from './link'\nimport type { ParsedLocation } from './location'\nimport type {\n AnyRouteMatch,\n MakePreValidationErrorHandlingRouteMatchUnion,\n MakeRouteMatchFromRoute,\n MakeRouteMatchUnion,\n RouteMatch,\n} from './Matches'\nimport type { RootRouteId } from './root'\nimport type { ParseRoute, RouteById, RouteIds, RoutePaths } from './routeInfo'\nimport type { AnyRouter, Register, RegisteredRouter, SSROption } from './router'\nimport type { BuildLocationFn, NavigateFn } from './RouterProvider'\nimport type {\n Assign,\n Awaitable,\n Constrain,\n Expand,\n IntersectAssign,\n LooseAsyncReturnType,\n LooseReturnType,\n NoInfer,\n} from './utils'\nimport type {\n AnySchema,\n AnyStandardSchemaValidator,\n AnyValidator,\n AnyValidatorAdapter,\n AnyValidatorObj,\n DefaultValidator,\n ResolveSearchValidatorInput,\n ResolveValidatorOutput,\n StandardSchemaValidator,\n ValidatorAdapter,\n ValidatorFn,\n ValidatorObj,\n} from './validators'\nimport type { ValidateSerializableLifecycleResult } from './ssr/serializer/transformer'\n\nexport type AnyPathParams = {}\n\nexport type SearchSchemaInput = {\n __TSearchSchemaInput__: 'TSearchSchemaInput'\n}\n\nexport type AnyContext = {}\n\nexport interface RouteContext {}\n\nexport type PreloadableObj = { preload?: () => Promise<void> | undefined }\n\nexport type RoutePathOptions<TCustomId, TPath> =\n | {\n path: TPath\n }\n | {\n id: TCustomId\n }\n\nexport interface StaticDataRouteOption {}\n\nexport type RoutePathOptionsIntersection<TCustomId, TPath> = {\n path: TPath\n id: TCustomId\n}\n\nexport type SearchFilter<TInput, TResult = TInput> = (prev: TInput) => TResult\n\nexport type SearchMiddlewareMeta = {\n removed?: Map<string, unknown>\n removedAny?: Set<string>\n defaulted?: Map<string, unknown>\n explicit?: unknown\n}\n\nexport type SearchMiddlewareContext<TSearchSchema> = {\n search: TSearchSchema\n next: (newSearch: TSearchSchema) => TSearchSchema\n meta?: SearchMiddlewareMeta\n}\n\nexport type SearchMiddleware<TSearchSchema> = (\n ctx: SearchMiddlewareContext<TSearchSchema>,\n) => TSearchSchema\n\nexport type ResolveId<\n TParentRoute,\n TCustomId extends string,\n TPath extends string,\n> = TParentRoute extends { id: infer TParentId extends string }\n ? RoutePrefix<TParentId, string extends TCustomId ? TPath : TCustomId>\n : RootRouteId\n\nexport type InferFullSearchSchema<TRoute> = TRoute extends {\n types: {\n fullSearchSchema: infer TFullSearchSchema\n }\n}\n ? TFullSearchSchema\n : {}\n\nexport type InferFullSearchSchemaInput<TRoute> = TRoute extends {\n types: {\n fullSearchSchemaInput: infer TFullSearchSchemaInput\n }\n}\n ? TFullSearchSchemaInput\n : {}\n\nexport type InferAllParams<TRoute> = TRoute extends {\n types: {\n allParams: infer TAllParams\n }\n}\n ? TAllParams\n : {}\n\nexport type InferAllContext<TRoute> = unknown extends TRoute\n ? TRoute\n : TRoute extends {\n types: {\n allContext: infer TAllContext\n }\n }\n ? TAllContext\n : {}\n\nexport type ResolveSearchSchemaFnInput<TSearchValidator> =\n TSearchValidator extends (input: infer TSearchSchemaInput) => any\n ? TSearchSchemaInput extends SearchSchemaInput\n ? Omit<TSearchSchemaInput, keyof SearchSchemaInput>\n : ResolveSearchSchemaFn<TSearchValidator>\n : AnySchema\n\nexport type ResolveSearchSchemaInput<TSearchValidator> =\n TSearchValidator extends AnyStandardSchemaValidator\n ? NonNullable<TSearchValidator['~standard']['types']>['input']\n : TSearchValidator extends AnyValidatorAdapter\n ? TSearchValidator['types']['input']\n : TSearchValidator extends AnyValidatorObj\n ? ResolveSearchSchemaFnInput<TSearchValidator['parse']>\n : ResolveSearchSchemaFnInput<TSearchValidator>\n\nexport type ResolveSearchSchemaFn<TSearchValidator> = TSearchValidator extends (\n ...args: any\n) => infer TSearchSchema\n ? TSearchSchema\n : AnySchema\n\nexport type ResolveSearchSchema<TSearchValidator> =\n unknown extends TSearchValidator\n ? TSearchValidator\n : TSearchValidator extends AnyStandardSchemaValidator\n ? NonNullable<TSearchValidator['~standard']['types']>['output']\n : TSearchValidator extends AnyValidatorAdapter\n ? TSearchValidator['types']['output']\n : TSearchValidator extends AnyValidatorObj\n ? ResolveSearchSchemaFn<TSearchValidator[Line truncated
|
||||
+532
@@ -0,0 +1,532 @@
|
||||
import { LazyRoute } from './fileRoute.cjs';
|
||||
import { NotFoundError } from './not-found.cjs';
|
||||
import { RedirectFnRoute } from './redirect.cjs';
|
||||
import { NavigateOptions, ParsePathParams } from './link.cjs';
|
||||
import { ParsedLocation } from './location.cjs';
|
||||
import { AnyRouteMatch, MakePreValidationErrorHandlingRouteMatchUnion, MakeRouteMatchFromRoute, MakeRouteMatchUnion, RouteMatch } from './Matches.cjs';
|
||||
import { RootRouteId } from './root.cjs';
|
||||
import { ParseRoute, RouteById, RouteIds, RoutePaths } from './routeInfo.cjs';
|
||||
import { AnyRouter, Register, RegisteredRouter, SSROption } from './router.cjs';
|
||||
import { BuildLocationFn, NavigateFn } from './RouterProvider.cjs';
|
||||
import { Assign, Awaitable, Constrain, Expand, IntersectAssign, LooseAsyncReturnType, LooseReturnType, NoInfer } from './utils.cjs';
|
||||
import { AnySchema, AnyStandardSchemaValidator, AnyValidator, AnyValidatorAdapter, AnyValidatorObj, DefaultValidator, ResolveSearchValidatorInput, ResolveValidatorOutput, StandardSchemaValidator, ValidatorAdapter, ValidatorFn, ValidatorObj } from './validators.cjs';
|
||||
import { ValidateSerializableLifecycleResult } from './ssr/serializer/transformer.cjs';
|
||||
export type AnyPathParams = {};
|
||||
export type SearchSchemaInput = {
|
||||
__TSearchSchemaInput__: 'TSearchSchemaInput';
|
||||
};
|
||||
export type AnyContext = {};
|
||||
export interface RouteContext {
|
||||
}
|
||||
export type PreloadableObj = {
|
||||
preload?: () => Promise<void> | undefined;
|
||||
};
|
||||
export type RoutePathOptions<TCustomId, TPath> = {
|
||||
path: TPath;
|
||||
} | {
|
||||
id: TCustomId;
|
||||
};
|
||||
export interface StaticDataRouteOption {
|
||||
}
|
||||
export type RoutePathOptionsIntersection<TCustomId, TPath> = {
|
||||
path: TPath;
|
||||
id: TCustomId;
|
||||
};
|
||||
export type SearchFilter<TInput, TResult = TInput> = (prev: TInput) => TResult;
|
||||
export type SearchMiddlewareMeta = {
|
||||
removed?: Map<string, unknown>;
|
||||
removedAny?: Set<string>;
|
||||
defaulted?: Map<string, unknown>;
|
||||
explicit?: unknown;
|
||||
};
|
||||
export type SearchMiddlewareContext<TSearchSchema> = {
|
||||
search: TSearchSchema;
|
||||
next: (newSearch: TSearchSchema) => TSearchSchema;
|
||||
meta?: SearchMiddlewareMeta;
|
||||
};
|
||||
export type SearchMiddleware<TSearchSchema> = (ctx: SearchMiddlewareContext<TSearchSchema>) => TSearchSchema;
|
||||
export type ResolveId<TParentRoute, TCustomId extends string, TPath extends string> = TParentRoute extends {
|
||||
id: infer TParentId extends string;
|
||||
} ? RoutePrefix<TParentId, string extends TCustomId ? TPath : TCustomId> : RootRouteId;
|
||||
export type InferFullSearchSchema<TRoute> = TRoute extends {
|
||||
types: {
|
||||
fullSearchSchema: infer TFullSearchSchema;
|
||||
};
|
||||
} ? TFullSearchSchema : {};
|
||||
export type InferFullSearchSchemaInput<TRoute> = TRoute extends {
|
||||
types: {
|
||||
fullSearchSchemaInput: infer TFullSearchSchemaInput;
|
||||
};
|
||||
} ? TFullSearchSchemaInput : {};
|
||||
export type InferAllParams<TRoute> = TRoute extends {
|
||||
types: {
|
||||
allParams: infer TAllParams;
|
||||
};
|
||||
} ? TAllParams : {};
|
||||
export type InferAllContext<TRoute> = unknown extends TRoute ? TRoute : TRoute extends {
|
||||
types: {
|
||||
allContext: infer TAllContext;
|
||||
};
|
||||
} ? TAllContext : {};
|
||||
export type ResolveSearchSchemaFnInput<TSearchValidator> = TSearchValidator extends (input: infer TSearchSchemaInput) => any ? TSearchSchemaInput extends SearchSchemaInput ? Omit<TSearchSchemaInput, keyof SearchSchemaInput> : ResolveSearchSchemaFn<TSearchValidator> : AnySchema;
|
||||
export type ResolveSearchSchemaInput<TSearchValidator> = TSearchValidator extends AnyStandardSchemaValidator ? NonNullable<TSearchValidator['~standard']['types']>['input'] : TSearchValidator extends AnyValidatorAdapter ? TSearchValidator['types']['input'] : TSearchValidator extends AnyValidatorObj ? ResolveSearchSchemaFnInput<TSearchValidator['parse']> : ResolveSearchSchemaFnInput<TSearchValidator>;
|
||||
export type ResolveSearchSchemaFn<TSearchValidator> = TSearchValidator extends (...args: any) => infer TSearchSchema ? TSearchSchema : AnySchema;
|
||||
export type ResolveSearchSchema<TSearchValidator> = unknown extends TSearchValidator ? TSearchValidator : TSearchValidator extends AnyStandardSchemaValidator ? NonNullable<TSearchValidator['~standard']['types']>['output'] : TSearchValidator extends AnyValidatorAdapter ? TSearchValidator['types']['output'] : TSearchValidator extends AnyValidatorObj ? ResolveSearchSchemaFn<TSearchValidator['parse']> : ResolveSearchSchemaFn<TSearchValidator>;
|
||||
export type ResolveRequiredParams<TPath extends string, T> = {
|
||||
[K in ParsePathParams<TPath>['required']]: T;
|
||||
};
|
||||
export type ResolveOptionalParams<TPath extends string, T> = {
|
||||
[K in ParsePathParams<TPath>['optional']]?: T | undefined;
|
||||
};
|
||||
export type ResolveParams<TPath extends string, T = string> = ResolveRequiredParams<TPath, T> & ResolveOptionalParams<TPath, T>;
|
||||
export type ParseParamsFn<in out TPath extends string, in out TParams> = (rawParams: Expand<ResolveParams<TPath>>) => TParams | false;
|
||||
type ValidateParsedParams<TPath extends string, TParams> = [TParams] extends [
|
||||
ResolveParams<TPath, any>
|
||||
] ? unknown : never;
|
||||
export type StringifyParamsFn<in out TPath extends string, in out TParams> = (params: TParams) => ResolveParams<TPath>;
|
||||
export type ParamsOptions<in out TPath extends string, in out TParams> = {
|
||||
params?: {
|
||||
parse?: ParseParamsFn<TPath, TParams> & ValidateParsedParams<TPath, TParams>;
|
||||
/**
|
||||
* When multiple route candidates use `params.parse` during matching,
|
||||
* higher priorities are tried first.
|
||||
*
|
||||
* @default 0
|
||||
*/
|
||||
priority?: number;
|
||||
stringify?: StringifyParamsFn<TPath, TParams>;
|
||||
};
|
||||
/**
|
||||
@deprecated Use params.parse instead
|
||||
*/
|
||||
parseParams?: ParseParamsFn<TPath, TParams> & ValidateParsedParams<TPath, TParams>;
|
||||
/**
|
||||
@deprecated Use params.stringify instead
|
||||
*/
|
||||
stringifyParams?: StringifyParamsFn<TPath, TParams>;
|
||||
};
|
||||
interface RequiredStaticDataRouteOption {
|
||||
staticData: StaticDataRouteOption;
|
||||
}
|
||||
interface OptionalStaticDataRouteOption {
|
||||
staticData?: StaticDataRouteOption;
|
||||
}
|
||||
export type UpdatableStaticRouteOption = {} extends StaticDataRouteOption ? OptionalStaticDataRouteOption : RequiredStaticDataRouteOption;
|
||||
export type MetaDescriptor = {
|
||||
charSet: 'utf-8';
|
||||
} | {
|
||||
title: string;
|
||||
} | {
|
||||
name: string;
|
||||
content: string;
|
||||
} | {
|
||||
property: string;
|
||||
content: string;
|
||||
} | {
|
||||
httpEquiv: string;
|
||||
content: string;
|
||||
} | {
|
||||
'script:ld+json': LdJsonObject;
|
||||
} | {
|
||||
tagName: 'meta' | 'link';
|
||||
[name: string]: string;
|
||||
} | Record<string, unknown>;
|
||||
type LdJsonObject = {
|
||||
[Key in string]: LdJsonValue;
|
||||
} & {
|
||||
[Key in string]?: LdJsonValue | undefined;
|
||||
};
|
||||
type LdJsonArray = Array<LdJsonValue> | ReadonlyArray<LdJsonValue>;
|
||||
type LdJsonPrimitive = string | number | boolean | null;
|
||||
type LdJsonValue = LdJsonPrimitive | LdJsonObject | LdJsonArray;
|
||||
export type RouteLinkEntry = {};
|
||||
export type SearchValidator<TInput, TOutput> = ValidatorObj<TInput, TOutput> | ValidatorFn<TInput, TOutput> | ValidatorAdapter<TInput, TOutput> | StandardSchemaValidator<TInput, TOutput> | undefined;
|
||||
export type AnySearchValidator = SearchValidator<any, any>;
|
||||
export type DefaultSearchValidator = SearchValidator<Record<string, unknown>, AnySchema>;
|
||||
export type RoutePrefix<TPrefix extends string, TPath extends string> = string extends TPath ? RootRouteId : TPath extends string ? TPrefix extends RootRouteId ? TPath extends '/' ? '/' : `/${TrimPath<TPath>}` : `${TPrefix}/${TPath}` extends '/' ? '/' : `/${TrimPathLeft<`${TrimPathRight<TPrefix>}/${TrimPath<TPath>}`>}` : never;
|
||||
export type TrimPath<T extends string> = '' extends T ? '' : TrimPathRight<TrimPathLeft<T>>;
|
||||
export type TrimPathLeft<T extends string> = T extends `${RootRouteId}/${infer U}` ? TrimPathLeft<U> : T extends `/${infer U}` ? TrimPathLeft<U> : T;
|
||||
export type TrimPathRight<T extends string> = T extends '/' ? '/' : T extends `${infer U}/` ? TrimPathRight<U> : T;
|
||||
export type ContextReturnType<TContextFn> = unknown extends TContextFn ? TContextFn : LooseReturnType<TContextFn> extends never ? AnyContext : LooseReturnType<TContextFn>;
|
||||
export type ContextAsyncReturnType<TContextFn> = unknown extends TContextFn ? TContextFn : LooseAsyncReturnType<TContextFn> extends never ? AnyContext : LooseAsyncReturnType<TContextFn>;
|
||||
export type ResolveRouteContext<TRouteContextFn, TBeforeLoadFn> = Assign<ContextReturnType<TRouteContextFn>, ContextAsyncReturnType<TBeforeLoadFn>>;
|
||||
export type ResolveRouteLoaderFn<TLoaderFn> = TLoaderFn extends {
|
||||
handler: infer THandler;
|
||||
} ? THandler : TLoaderFn;
|
||||
export type RouteLoaderObject<TRegister, TParentRoute extends AnyRoute = AnyRoute, TId extends string = string, TParams = {}, TLoaderDeps = {}, TRouterContext = {}, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TServerMiddlewares = unknown, THandlers = undefined> = {
|
||||
handler: RouteLoaderFn<TRegister, TParentRoute, TId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn, TServerMiddlewares, THandlers>;
|
||||
staleReloadMode?: LoaderStaleReloadMode;
|
||||
};
|
||||
export type ResolveLoaderData<TLoaderFn> = unknown extends TLoaderFn ? TLoaderFn : LooseAsyncReturnType<ResolveRouteLoaderFn<TLoaderFn>> extends never ? undefined : LooseAsyncReturnType<ResolveRouteLoaderFn<TLoaderFn>>;
|
||||
export type ResolveFullSearchSchema<TParentRoute extends AnyRoute, TSearchValidator> = unknown extends TParentRoute ? ResolveValidatorOutput<TSearchValidator> : IntersectAssign<InferFullSearchSchema<TParentRoute>, ResolveValidatorOutput<TSearchValidator>>;
|
||||
export type ResolveFullSearchSchemaInput<TParentRoute extends AnyRoute, TSearchValidator> = IntersectAssign<InferFullSearchSchemaInput<TParentRoute>, ResolveSearchValidatorInput<TSearchValidator>>;
|
||||
export type ResolveAllParamsFromParent<TParentRoute extends AnyRoute, TParams> = Assign<InferAllParams<TParentRoute>, TParams>;
|
||||
export type RouteContextParameter<TParentRoute extends AnyRoute, TRouterContext> = unknown extends TParentRoute ? TRouterContext : Assign<TRouterContext, InferAllContext<TParentRoute>>;
|
||||
export type BeforeLoadContextParameter<TParentRoute extends AnyRoute, TRouterContext, TRouteContextFn> = Assign<RouteContextParameter<TParentRoute, TRouterContext>, ContextReturnType<TRouteContextFn>>;
|
||||
export type ResolveAllContext<TParentRoute extends AnyRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn> = Assign<BeforeLoadContextParameter<TParentRoute, TRouterContext, TRouteContextFn>, ContextAsyncReturnType<TBeforeLoadFn>>;
|
||||
export interface FullSearchSchemaOption<in out TParentRoute extends AnyRoute, in out TSearchValidator> {
|
||||
search: Expand<ResolveFullSearchSchema<TParentRoute, TSearchValidator>>;
|
||||
}
|
||||
export interface RemountDepsOptions<in out TRouteId, in out TFullSearchSchema, in out TAllParams, in out TLoaderDeps> {
|
||||
routeId: TRouteId;
|
||||
search: TFullSearchSchema;
|
||||
params: TAllParams;
|
||||
loaderDeps: TLoaderDeps;
|
||||
}
|
||||
export type MakeRemountDepsOptionsUnion<TRouteTree extends AnyRoute = RegisteredRouter['routeTree']> = ParseRoute<TRouteTree> extends infer TRoute extends AnyRoute ? TRoute extends any ? RemountDepsOptions<TRoute['id'], TRoute['types']['fullSearchSchema'], TRoute['types']['allParams'], TRoute['types']['loaderDeps']> : never : never;
|
||||
export interface RouteTypes<in out TRegister, in out TParentRoute extends AnyRoute, in out TPath extends string, in out TFullPath extends string, in out TCustomId extends string, in out TId extends string, in out TSearchValidator, in out TParams, in out TRouterContext, in out TRouteContextFn, in out TBeforeLoadFn, in out TLoaderDeps, in out TLoaderFn, in out TChildren, in out TFileRouteTypes, in out TSSR, in out TServerMiddlewares, in out THandlers> {
|
||||
parentRoute: TParentRoute;
|
||||
path: TPath;
|
||||
to: TrimPathRight<TFullPath>;
|
||||
fullPath: TFullPath;
|
||||
customId: TCustomId;
|
||||
id: TId;
|
||||
searchSchema: ResolveValidatorOutput<TSearchValidator>;
|
||||
searchSchemaInput: ResolveSearchValidatorInput<TSearchValidator>;
|
||||
searchValidator: TSearchValidator;
|
||||
fullSearchSchema: ResolveFullSearchSchema<TParentRoute, TSearchValidator>;
|
||||
fullSearchSchemaInput: ResolveFullSearchSchemaInput<TParentRoute, TSearchValidator>;
|
||||
params: TParams;
|
||||
allParams: ResolveAllParamsFromParent<TParentRoute, TParams>;
|
||||
routerContext: TRouterContext;
|
||||
routeContext: ResolveRouteContext<TRouteContextFn, TBeforeLoadFn>;
|
||||
routeContextFn: TRouteContextFn;
|
||||
beforeLoadFn: TBeforeLoadFn;
|
||||
allContext: ResolveAllContext<TParentRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn>;
|
||||
children: TChildren;
|
||||
loaderData: ResolveLoaderData<TLoaderFn>;
|
||||
loaderDeps: TLoaderDeps;
|
||||
fileRouteTypes: TFileRouteTypes;
|
||||
ssr: ResolveSSR<TSSR>;
|
||||
allSsr: ResolveAllSSR<TParentRoute, TSSR>;
|
||||
}
|
||||
export type ResolveSSR<TSSR> = TSSR extends (...args: ReadonlyArray<any>) => any ? LooseReturnType<TSSR> : TSSR;
|
||||
export type ResolveAllSSR<TParentRoute extends AnyRoute, TSSR> = unknown extends TParentRoute ? ResolveSSR<TSSR> : unknown extends TSSR ? TParentRoute['types']['allSsr'] : ResolveSSR<TSSR>;
|
||||
export type ResolveFullPath<TParentRoute extends AnyRoute, TPath extends string, TPrefixed = RoutePrefix<TParentRoute['fullPath'], TPath>> = TPrefixed extends RootRouteId ? '/' : TPrefixed;
|
||||
export interface RouteExtensions<in out TId, in out TFullPath> {
|
||||
id: TId;
|
||||
fullPath: TFullPath;
|
||||
}
|
||||
export type RouteLazyFn<TRoute extends AnyRoute> = (lazyFn: () => Promise<LazyRoute<TRoute>>) => TRoute;
|
||||
export type RouteAddChildrenFn<in out TRegister, in out TParentRoute extends AnyRoute, in out TPath extends string, in out TFullPath extends string, in out TCustomId extends string, in out TId extends string, in out TSearchValidator, in out TParams, in out TRouterContext, in out TRouteContextFn, in out TBeforeLoadFn, in out TLoaderDeps extends Record<string, any>, in out TLoaderFn, in out TFileRouteTypes, in out TSSR, in out TServerMiddlewares, in out THandlers> = <const TNewChildren>(children: Constrain<TNewChildren, ReadonlyArray<AnyRoute> | Record<string, AnyRoute>>) => Route<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TNewChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
|
||||
export type RouteAddFileChildrenFn<in out TRegister, in out TParentRoute extends AnyRoute, in out TPath extends string, in out TFullPath extends string, in out TCustomId extends string, in out TId extends string, in out TSearchValidator, in out TParams, in out TRouterContext, in out TRouteContextFn, in out TBeforeLoadFn, in out TLoaderDeps extends Record<string, any>, in out TLoaderFn, in out TFileRouteTypes, in out TSSR, in out TServerMiddlewares, in out THandlers> = <const TNewChildren>(children: TNewChildren) => Route<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TNewChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
|
||||
export type RouteAddFileTypesFn<TRegister, TParentRoute extends AnyRoute, TPath extends string, TFullPath extends string, TCustomId extends string, TId extends string, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps extends Record<string, any>, TLoaderFn, TChildren, TSSR, TServerMiddlewares, THandlers> = <TNewFileRouteTypes>() => Route<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TNewFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
|
||||
export interface Route<in out TRegister, in out TParentRoute extends AnyRoute, in out TPath extends string, in out TFullPath extends string, in out TCustomId extends string, in out TId extends string, in out TSearchValidator, in out TParams, in out TRouterContext, in out TRouteContextFn, in out TBeforeLoadFn, in out TLoaderDeps extends Record<string, any>, in out TLoaderFn, in out TChildren, in out TFileRouteTypes, in out TSSR, in out TServerMiddlewares, in out THandlers> extends RouteExtensions<TId, TFullPath> {
|
||||
path: TPath;
|
||||
parentRoute: TParentRoute;
|
||||
children?: TChildren;
|
||||
types: RouteTypes<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
|
||||
options: RouteOptions<TRegister, TParentRoute, TId, TCustomId, TFullPath, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TSSR, TServerMiddlewares, THandlers>;
|
||||
isRoot: TParentRoute extends AnyRoute ? true : false;
|
||||
lazyFn?: () => Promise<LazyRoute<Route<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>>>;
|
||||
rank: number;
|
||||
to: TrimPathRight<TFullPath>;
|
||||
init: (originalIndex: number) => void;
|
||||
update: (options: UpdatableRouteOptions<TParentRoute, TCustomId, TFullPath, TParams, TSearchValidator, TLoaderFn, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn>) => this;
|
||||
lazy: RouteLazyFn<Route<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>>;
|
||||
addChildren: RouteAddChildrenFn<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
|
||||
_addFileChildren: RouteAddFileChildrenFn<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
|
||||
_addFileTypes: RouteAddFileTypesFn<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TSSR, TServerMiddlewares, THandlers>;
|
||||
/**
|
||||
* Create a redirect with `from` automatically set to this route's path.
|
||||
* Enables relative redirects like `Route.redirect({ to: './overview' })`.
|
||||
* @param opts Redirect options (same as `redirect()` but without `from`)
|
||||
* @returns A redirect Response that can be thrown from loaders/beforeLoad
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction
|
||||
*/
|
||||
redirect: RedirectFnRoute<TFullPath>;
|
||||
}
|
||||
export type AnyRoute = Route<any, any, any, any, any, any, any, any, any, any, any, any, any, any, any, any, any, any>;
|
||||
export type AnyRouteWithContext<TContext> = AnyRoute & {
|
||||
types: {
|
||||
allContext: TContext;
|
||||
};
|
||||
};
|
||||
export type RouteOptions<TRegister, TParentRoute extends AnyRoute = AnyRoute, TId extends string = string, TCustomId extends string = string, TFullPath extends string = string, TPath extends string = string, TSearchValidator = undefined, TParams = AnyPathParams, TLoaderDeps extends Record<string, any> = {}, TLoaderFn = undefined, TRouterContext = {}, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TSSR = unknown, TServerMiddlewares = unknown, THandlers = undefined> = BaseRouteOptions<TRegister, TParentRoute, TId, TCustomId, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TSSR, TServerMiddlewares, THandlers> & UpdatableRouteOptions<NoInfer<TParentRoute>, NoInfer<TCustomId>, NoInfer<TFullPath>, NoInfer<TParams>, NoInfer<TSearchValidator>, NoInfer<TLoaderFn>, NoInfer<TLoaderDeps>, NoInfer<TRouterContext>, NoInfer<TRouteContextFn>, NoInfer<TBeforeLoadFn>>;
|
||||
export type RouteContextFn<in out TParentRoute extends AnyRoute, in out TSearchValidator, in out TParams, in out TRouterContext, in out TRouteId> = (ctx: RouteContextOptions<TParentRoute, TSearchValidator, TParams, TRouterContext, TRouteId>) => any;
|
||||
export type FileBaseRouteOptions<TRegister, TParentRoute extends AnyRoute = AnyRoute, TId extends string = string, TPath extends string = string, TSearchValidator = undefined, TParams = {}, TLoaderDeps extends Record<string, any> = {}, TLoaderFn = undefined, TRouterContext = {}, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TRemountDepsFn = AnyContext, TSSR = unknown, TServerMiddlewares = unknown, THandlers = undefined> = ParamsOptions<TPath, TParams> & FilebaseRouteOptionsInterface<TRegister, TParentRoute, TId, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TRemountDepsFn, TSSR, TServerMiddlewares, THandlers>;
|
||||
export interface FilebaseRouteOptionsInterface<TRegister, TParentRoute extends AnyRoute = AnyRoute, TId extends string = string, TPath extends string = string, TSearchValidator = undefined, TParams = {}, TLoaderDeps extends Record<string, any> = {}, TLoaderFn = undefined, TRouterContext = {}, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TRemountDepsFn = AnyContext, TSSR = unknown, TServerMiddlewares = unknown, THandlers = undefined> {
|
||||
validateSearch?: Constrain<TSearchValidator, AnyValidator, DefaultValidator>;
|
||||
shouldReload?: boolean | ((match: LoaderFnContext<TRegister, TParentRoute, TId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn, TServerMiddlewares, THandlers>) => any);
|
||||
context?: Constrain<TRouteContextFn, (ctx: RouteContextOptions<TParentRoute, TParams, TRouterContext, TLoaderDeps, TId>) => any>;
|
||||
ssr?: Constrain<TSSR, undefined | SSROption | ((ctx: SsrContextOptions<TParentRoute, TSearchValidator, TParams>) => Awaitable<undefined | SSROption>)>;
|
||||
beforeLoad?: Constrain<TBeforeLoadFn, (ctx: BeforeLoadContextOptions<TRegister, TParentRoute, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TId, TServerMiddlewares, THandlers>) => ValidateSerializableLifecycleResult<TRegister, TParentRoute, TSSR, TBeforeLoadFn>>;
|
||||
loaderDeps?: (opts: FullSearchSchemaOption<TParentRoute, TSearchValidator>) => TLoaderDeps;
|
||||
remountDeps?: Constrain<TRemountDepsFn, (opt: RemountDepsOptions<TId, ResolveFullSearchSchema<TParentRoute, TSearchValidator>, Expand<ResolveAllParamsFromParent<TParentRoute, TParams>>, TLoaderDeps>) => any>;
|
||||
loader?: Constrain<TLoaderFn, RouteLoaderFn<TRegister, TParentRoute, TId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn, TServerMiddlewares, THandlers> | RouteLoaderObject<TRegister, TParentRoute, TId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn, TServerMiddlewares, THandlers>>;
|
||||
}
|
||||
export type BaseRouteOptions<TRegister, TParentRoute extends AnyRoute = AnyRoute, TId extends string = string, TCustomId extends string = string, TPath extends string = string, TSearchValidator = undefined, TParams = {}, TLoaderDeps extends Record<string, any> = {}, TLoaderFn = undefined, TRouterContext = {}, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TSSR = unknown, TServerMiddlewares = unknown, THandlers = undefined> = RoutePathOptions<TCustomId, TPath> & FileBaseRouteOptions<TRegister, TParentRoute, TId, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, AnyContext, TSSR, TServerMiddlewares, THandlers> & {
|
||||
getParentRoute: () => TParentRoute;
|
||||
};
|
||||
export interface ContextOptions<in out TParentRoute extends AnyRoute, in out TParams, in out TRouteId> {
|
||||
abortController: AbortController;
|
||||
preload: boolean;
|
||||
params: Expand<ResolveAllParamsFromParent<TParentRoute, TParams>>;
|
||||
location: ParsedLocation;
|
||||
/**
|
||||
* @deprecated Use `throw redirect({ to: '/somewhere' })` instead
|
||||
**/
|
||||
navigate: NavigateFn;
|
||||
buildLocation: BuildLocationFn;
|
||||
cause: 'preload' | 'enter' | 'stay';
|
||||
matches: Array<MakeRouteMatchUnion>;
|
||||
routeId: TRouteId;
|
||||
}
|
||||
export interface RouteContextOptions<in out TParentRoute extends AnyRoute, in out TParams, in out TRouterContext, in out TLoaderDeps, in out TRouteId> extends ContextOptions<TParentRoute, TParams, TRouteId> {
|
||||
deps: TLoaderDeps;
|
||||
context: Expand<RouteContextParameter<TParentRoute, TRouterContext>>;
|
||||
}
|
||||
export interface SsrContextOptions<in out TParentRoute extends AnyRoute, in out TSearchValidator, in out TParams> {
|
||||
params: {
|
||||
status: 'success';
|
||||
value: Expand<ResolveAllParamsFromParent<TParentRoute, TParams>>;
|
||||
} | {
|
||||
status: 'error';
|
||||
error: unknown;
|
||||
};
|
||||
search: {
|
||||
status: 'success';
|
||||
value: Expand<ResolveFullSearchSchema<TParentRoute, TSearchValidator>>;
|
||||
} | {
|
||||
status: 'error';
|
||||
error: unknown;
|
||||
};
|
||||
location: ParsedLocation;
|
||||
matches: Array<MakePreValidationErrorHandlingRouteMatchUnion>;
|
||||
}
|
||||
export interface BeforeLoadContextOptions<in out TRegister, in out TParentRoute extends AnyRoute, in out TSearchValidator, in out TParams, in out TRouterContext, in out TRouteContextFn, in out TRouteId, in out TServerMiddlewares, in out THandlers> extends ContextOptions<TParentRoute, TParams, TRouteId>, FullSearchSchemaOption<TParentRoute, TSearchValidator> {
|
||||
context: Expand<BeforeLoadContextParameter<TParentRoute, TRouterContext, TRouteContextFn>>;
|
||||
}
|
||||
type AssetFnContextOptions<in out TRouteId, in out TFullPath, in out TParentRoute extends AnyRoute, in out TParams, in out TSearchValidator, in out TLoaderFn, in out TRouterContext, in out TRouteContextFn, in out TBeforeLoadFn, in out TLoaderDeps> = {
|
||||
ssr?: {
|
||||
nonce?: string;
|
||||
};
|
||||
matches: Array<RouteMatch<TRouteId, TFullPath, ResolveAllParamsFromParent<TParentRoute, TParams>, ResolveFullSearchSchema<TParentRoute, TSearchValidator>, ResolveLoaderData<TLoaderFn>, ResolveAllContext<TParentRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn>, TLoaderDeps>>;
|
||||
match: RouteMatch<TRouteId, TFullPath, ResolveAllParamsFromParent<TParentRoute, TParams>, ResolveFullSearchSchema<TParentRoute, TSearchValidator>, ResolveLoaderData<TLoaderFn>, ResolveAllContext<TParentRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn>, TLoaderDeps>;
|
||||
params: ResolveAllParamsFromParent<TParentRoute, TParams>;
|
||||
loaderData?: ResolveLoaderData<TLoaderFn>;
|
||||
};
|
||||
export interface DefaultUpdatableRouteOptionsExtensions {
|
||||
component?: unknown;
|
||||
errorComponent?: unknown;
|
||||
notFoundComponent?: unknown;
|
||||
pendingComponent?: unknown;
|
||||
}
|
||||
export interface UpdatableRouteOptionsExtensions extends DefaultUpdatableRouteOptionsExtensions {
|
||||
}
|
||||
export interface UpdatableRouteOptions<in out TParentRoute extends AnyRoute, in out TRouteId, in out TFullPath, in out TParams, in out TSearchValidator, in out TLoaderFn, in out TLoaderDeps, in out TRouterContext, in out TRouteContextFn, in out TBeforeLoadFn> extends UpdatableStaticRouteOption, UpdatableRouteOptionsExtensions {
|
||||
/**
|
||||
* If true, this route will be matched as case-sensitive
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
caseSensitive?: boolean;
|
||||
/**
|
||||
* If true, this route will be forcefully wrapped in a suspense boundary
|
||||
*/
|
||||
wrapInSuspense?: boolean;
|
||||
pendingMs?: number;
|
||||
pendingMinMs?: number;
|
||||
staleTime?: number;
|
||||
gcTime?: number;
|
||||
preload?: boolean;
|
||||
preloadStaleTime?: number;
|
||||
preloadGcTime?: number;
|
||||
search?: {
|
||||
middlewares?: Array<SearchMiddleware<ResolveFullSearchSchema<TParentRoute, TSearchValidator>>>;
|
||||
};
|
||||
/**
|
||||
@deprecated Use search.middlewares instead
|
||||
*/
|
||||
preSearchFilters?: Array<SearchFilter<ResolveFullSearchSchema<TParentRoute, TSearchValidator>>>;
|
||||
/**
|
||||
@deprecated Use search.middlewares instead
|
||||
*/
|
||||
postSearchFilters?: Array<SearchFilter<ResolveFullSearchSchema<TParentRoute, TSearchValidator>>>;
|
||||
onCatch?: (error: ErrorBoundaryTypes['error']) => void;
|
||||
onError?: (err: any) => void;
|
||||
onEnter?: (match: RouteMatch<TRouteId, TFullPath, ResolveAllParamsFromParent<TParentRoute, TParams>, ResolveFullSearchSchema<TParentRoute, TSearchValidator>, ResolveLoaderData<TLoaderFn>, ResolveAllContext<TParentRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn>, TLoaderDeps>) => void;
|
||||
onStay?: (match: RouteMatch<TRouteId, TFullPath, ResolveAllParamsFromParent<TParentRoute, TParams>, ResolveFullSearchSchema<TParentRoute, TSearchValidator>, ResolveLoaderData<TLoaderFn>, ResolveAllContext<TParentRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn>, TLoaderDeps>) => void;
|
||||
onLeave?: (match: RouteMatch<TRouteId, TFullPath, ResolveAllParamsFromParent<TParentRoute, TParams>, ResolveFullSearchSchema<TParentRoute, TSearchValidator>, ResolveLoaderData<TLoaderFn>, ResolveAllContext<TParentRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn>, TLoaderDeps>) => void;
|
||||
headers?: (ctx: AssetFnContextOptions<TRouteId, TFullPath, TParentRoute, TParams, TSearchValidator, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps>) => Awaitable<Record<string, string> | undefined>;
|
||||
head?: (ctx: AssetFnContextOptions<TRouteId, TFullPath, TParentRoute, TParams, TSearchValidator, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps>) => Awaitable<{
|
||||
links?: AnyRouteMatch['links'];
|
||||
scripts?: AnyRouteMatch['headScripts'];
|
||||
meta?: AnyRouteMatch['meta'];
|
||||
styles?: AnyRouteMatch['styles'];
|
||||
}>;
|
||||
scripts?: (ctx: AssetFnContextOptions<TRouteId, TFullPath, TParentRoute, TParams, TSearchValidator, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps>) => Awaitable<AnyRouteMatch['scripts']>;
|
||||
codeSplitGroupings?: Array<Array<'loader' | 'component' | 'pendingComponent' | 'notFoundComponent' | 'errorComponent'>>;
|
||||
}
|
||||
export type RouteLoaderFn<in out TRegister, in out TParentRoute extends AnyRoute = AnyRoute, in out TId extends string = string, in out TParams = {}, in out TLoaderDeps = {}, in out TRouterContext = {}, in out TRouteContextFn = AnyContext, in out TBeforeLoadFn = AnyContext, in out TServerMiddlewares = unknown, in out THandlers = undefined> = (match: LoaderFnContext<TRegister, TParentRoute, TId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn, TServerMiddlewares, THandlers>) => any;
|
||||
export type LoaderStaleReloadMode = 'background' | 'blocking';
|
||||
export type RouteLoaderEntry<TRegister, TParentRoute extends AnyRoute = AnyRoute, TId extends string = string, TParams = {}, TLoaderDeps = {}, TRouterContext = {}, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TServerMiddlewares = unknown, THandlers = undefined> = RouteLoaderFn<TRegister, TParentRoute, TId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn, TServerMiddlewares, THandlers> | RouteLoaderObject<TRegister, TParentRoute, TId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn, TServerMiddlewares, THandlers>;
|
||||
export interface LoaderFnContext<in out TRegister = unknown, in out TParentRoute extends AnyRoute = AnyRoute, in out TId extends string = string, in out TParams = {}, in out TLoaderDeps = {}, in out TRouterContext = {}, in out TRouteContextFn = AnyContext, in out TBeforeLoadFn = AnyContext, in out TServerMiddlewares = unknown, in out THandlers = undefined> {
|
||||
abortController: AbortController;
|
||||
preload: boolean;
|
||||
params: Expand<ResolveAllParamsFromParent<TParentRoute, TParams>>;
|
||||
deps: TLoaderDeps;
|
||||
context: Expand<ResolveAllContext<TParentRoute, TRouterContext, TRouteContextFn, TBeforeLoadFn>>;
|
||||
location: ParsedLocation;
|
||||
/**
|
||||
* @deprecated Use `throw redirect({ to: '/somewhere' })` instead
|
||||
**/
|
||||
navigate: (opts: NavigateOptions<AnyRouter>) => Promise<void> | void;
|
||||
parentMatchPromise: TId extends RootRouteId ? never : Promise<MakeRouteMatchFromRoute<TParentRoute>>;
|
||||
cause: 'preload' | 'enter' | 'stay';
|
||||
route: AnyRoute;
|
||||
}
|
||||
export interface DefaultRootRouteOptionsExtensions {
|
||||
shellComponent?: unknown;
|
||||
}
|
||||
export interface RootRouteOptionsExtensions extends DefaultRootRouteOptionsExtensions {
|
||||
}
|
||||
export interface RootRouteOptions<TRegister = unknown, TSearchValidator = undefined, TRouterContext = {}, TRouteContextFn = AnyContext, TBeforeLoadFn = AnyContext, TLoaderDeps extends Record<string, any> = {}, TLoaderFn = undefined, TSSR = unknown, TServerMiddlewares = unknown, THandlers = undefined> extends Omit<RouteOptions<TRegister, any, // TParentRoute
|
||||
RootRouteId, // TId
|
||||
RootRouteId, // TCustomId
|
||||
'', // TFullPath
|
||||
'', // TPath
|
||||
TSearchValidator, {}, // TParams
|
||||
TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TSSR, TServerMiddlewares, THandlers>, 'path' | 'id' | 'getParentRoute' | 'caseSensitive' | 'parseParams' | 'stringifyParams' | 'params'>, RootRouteOptionsExtensions {
|
||||
}
|
||||
export type RouteConstraints = {
|
||||
TParentRoute: AnyRoute;
|
||||
TPath: string;
|
||||
TFullPath: string;
|
||||
TCustomId: string;
|
||||
TId: string;
|
||||
TSearchSchema: AnySchema;
|
||||
TFullSearchSchema: AnySchema;
|
||||
TParams: Record<string, any>;
|
||||
TAllParams: Record<string, any>;
|
||||
TParentContext: AnyContext;
|
||||
TRouteContext: RouteContext;
|
||||
TAllContext: AnyContext;
|
||||
TRouterContext: AnyContext;
|
||||
TChildren: unknown;
|
||||
TRouteTree: AnyRoute;
|
||||
};
|
||||
export type RouteTypesById<TRouter extends AnyRouter, TId> = RouteById<TRouter['routeTree'], TId>['types'];
|
||||
export type RouteMask<TRouteTree extends AnyRoute> = {
|
||||
routeTree: TRouteTree;
|
||||
from: RoutePaths<TRouteTree>;
|
||||
to?: any;
|
||||
params?: any;
|
||||
search?: any;
|
||||
hash?: any;
|
||||
state?: any;
|
||||
unmaskOnReload?: boolean;
|
||||
};
|
||||
/**
|
||||
* @deprecated Use `ErrorComponentProps` instead.
|
||||
*/
|
||||
export type ErrorRouteProps = {
|
||||
error: unknown;
|
||||
info?: {
|
||||
componentStack: string;
|
||||
};
|
||||
reset: () => void;
|
||||
};
|
||||
export interface DefaultErrorBoundaryTypes {
|
||||
error: unknown;
|
||||
}
|
||||
/** Frameworks can specialize the error exposed by boundary components and callbacks. */
|
||||
export interface ErrorBoundaryTypes extends DefaultErrorBoundaryTypes {
|
||||
}
|
||||
export type ErrorComponentProps<TError = ErrorBoundaryTypes['error']> = {
|
||||
error: TError;
|
||||
info?: {
|
||||
componentStack: string;
|
||||
};
|
||||
reset: () => void;
|
||||
};
|
||||
export type NotFoundRouteProps = {
|
||||
data?: unknown;
|
||||
isNotFound: boolean;
|
||||
routeId: RouteIds<RegisteredRouter['routeTree']>;
|
||||
};
|
||||
export declare class BaseRoute<in out TRegister = Register, in out TParentRoute extends AnyRoute = AnyRoute, in out TPath extends string = '/', in out TFullPath extends string = ResolveFullPath<TParentRoute, TPath>, in out TCustomId extends string = string, in out TId extends string = ResolveId<TParentRoute, TCustomId, TPath>, in out TSearchValidator = undefined, in out TParams = ResolveParams<TPath>, in out TRouterContext = AnyContext, in out TRouteContextFn = AnyContext, in out TBeforeLoadFn = AnyContext, in out TLoaderDeps extends Record<string, any> = {}, in out TLoaderFn = undefined, in out TChildren = unknown, in out TFileRouteTypes = unknown, in out TSSR = unknown, in out TServerMiddlewares = unknown, in out THandlers = undefined> {
|
||||
isRoot: TParentRoute extends AnyRoute ? true : false;
|
||||
options: RouteOptions<TRegister, TParentRoute, TId, TCustomId, TFullPath, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TSSR, TServerMiddlewares, THandlers>;
|
||||
parentRoute: TParentRoute;
|
||||
private _id;
|
||||
private _path;
|
||||
private _fullPath;
|
||||
private _to;
|
||||
get to(): TrimPathRight<TFullPath>;
|
||||
get id(): TId;
|
||||
get path(): TPath;
|
||||
get fullPath(): TFullPath;
|
||||
children?: TChildren;
|
||||
originalIndex?: number;
|
||||
rank: number;
|
||||
lazyFn?: () => Promise<LazyRoute<Route<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>>>;
|
||||
constructor(options?: RouteOptions<TRegister, TParentRoute, TId, TCustomId, TFullPath, TPath, TSearchValidator, TParams, TLoaderDeps, TLoaderFn, TRouterContext, TRouteContextFn, TBeforeLoadFn, TSSR, TServerMiddlewares, THandlers>);
|
||||
types: RouteTypes<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
|
||||
init: (originalIndex: number) => void;
|
||||
addChildren: RouteAddChildrenFn<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
|
||||
_addFileChildren: RouteAddFileChildrenFn<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
|
||||
_addFileTypes: RouteAddFileTypesFn<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TSSR, TServerMiddlewares, THandlers>;
|
||||
updateLoader: <TNewLoaderFn>(options: {
|
||||
loader: Constrain<TNewLoaderFn, RouteLoaderFn<TRegister, TParentRoute, TCustomId, TParams, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn>>;
|
||||
}) => BaseRoute<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TNewLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>;
|
||||
update: (options: UpdatableRouteOptions<TParentRoute, TCustomId, TFullPath, TParams, TSearchValidator, TLoaderFn, TLoaderDeps, TRouterContext, TRouteContextFn, TBeforeLoadFn>) => this;
|
||||
lazy: RouteLazyFn<Route<TRegister, TParentRoute, TPath, TFullPath, TCustomId, TId, TSearchValidator, TParams, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, TFileRouteTypes, TSSR, TServerMiddlewares, THandlers>>;
|
||||
/**
|
||||
* Create a redirect with `from` automatically set to this route's fullPath.
|
||||
* Enables relative redirects like `Route.redirect({ to: './overview' })`.
|
||||
* @param opts Redirect options (same as `redirect()` but without `from`)
|
||||
* @returns A redirect Response that can be thrown from loaders/beforeLoad
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction
|
||||
*/
|
||||
redirect: RedirectFnRoute<TFullPath>;
|
||||
}
|
||||
export declare class BaseRouteApi<TId, TRouter extends AnyRouter = RegisteredRouter> {
|
||||
id: TId;
|
||||
constructor({ id }: {
|
||||
id: TId;
|
||||
});
|
||||
notFound: (opts?: NotFoundError) => NotFoundError;
|
||||
/**
|
||||
* Create a redirect with `from` automatically set to this route's path.
|
||||
* Enables relative redirects like `routeApi.redirect({ to: './overview' })`.
|
||||
* @param opts Redirect options (same as `redirect()` but without `from`)
|
||||
* @returns A redirect Response that can be thrown from loaders/beforeLoad
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction
|
||||
*/
|
||||
redirect: RedirectFnRoute<RouteTypesById<TRouter, TId>['fullPath']>;
|
||||
}
|
||||
export interface RootRoute<in out TRegister, in out TSearchValidator = undefined, in out TRouterContext = {}, in out TRouteContextFn = AnyContext, in out TBeforeLoadFn = AnyContext, in out TLoaderDeps extends Record<string, any> = {}, in out TLoaderFn = undefined, in out TChildren = unknown, in out TFileRouteTypes = unknown, in out TSSR = unknown, in out TServerMiddlewares = unknown, in out THandlers = undefined> extends Route<TRegister, any, // TParentRoute
|
||||
'/', // TPath
|
||||
'/', // TFullPath
|
||||
string, // TCustomId
|
||||
RootRouteId, // TId
|
||||
TSearchValidator, // TSearchValidator
|
||||
{}, // TParams
|
||||
TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, // TChildren
|
||||
TFileRouteTypes, TSSR, TServerMiddlewares, THandlers> {
|
||||
}
|
||||
export declare class BaseRootRoute<in out TRegister = Register, in out TSearchValidator = undefined, in out TRouterContext = {}, in out TRouteContextFn = AnyContext, in out TBeforeLoadFn = AnyContext, in out TLoaderDeps extends Record<string, any> = {}, in out TLoaderFn = undefined, in out TChildren = unknown, in out TFileRouteTypes = unknown, in out TSSR = unknown, in out TServerMiddlewares = unknown, in out THandlers = undefined> extends BaseRoute<TRegister, any, // TParentRoute
|
||||
'/', // TPath
|
||||
'/', // TFullPath
|
||||
string, // TCustomId
|
||||
RootRouteId, // TId
|
||||
TSearchValidator, // TSearchValidator
|
||||
{}, // TParams
|
||||
TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TChildren, // TChildren
|
||||
TFileRouteTypes, TSSR, TServerMiddlewares, THandlers> {
|
||||
constructor(options?: RootRouteOptions<TRegister, TSearchValidator, TRouterContext, TRouteContextFn, TBeforeLoadFn, TLoaderDeps, TLoaderFn, TSSR, TServerMiddlewares, THandlers>);
|
||||
}
|
||||
export interface RouteLike {
|
||||
id: string;
|
||||
isRoot?: boolean;
|
||||
path?: string;
|
||||
fullPath: string;
|
||||
rank?: number;
|
||||
parentRoute?: RouteLike;
|
||||
children?: Array<RouteLike>;
|
||||
options?: {
|
||||
caseSensitive?: boolean;
|
||||
};
|
||||
}
|
||||
export {};
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
import { InferFileRouteTypes } from './fileRoute.cjs';
|
||||
import { AddTrailingSlash, RemoveTrailingSlashes } from './link.cjs';
|
||||
import { AnyRoute } from './route.cjs';
|
||||
import { AnyRouter, TrailingSlashOption } from './router.cjs';
|
||||
import { PartialMergeAll } from './utils.cjs';
|
||||
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;
|
||||
+982
@@ -0,0 +1,982 @@
|
||||
const require_utils = require("./utils.cjs");
|
||||
const require_path = require("./path.cjs");
|
||||
const require_sieve_cache = require("./sieve-cache.cjs");
|
||||
const require_new_process_route_tree = require("./new-process-route-tree.cjs");
|
||||
const require_not_found = require("./not-found.cjs");
|
||||
const require_scroll_restoration = require("./scroll-restoration.cjs");
|
||||
const require_searchParams = require("./searchParams.cjs");
|
||||
const require_root = require("./root.cjs");
|
||||
const require_redirect = require("./redirect.cjs");
|
||||
const require_load_client = require("./load-client.cjs");
|
||||
const require_rewrite = require("./rewrite.cjs");
|
||||
const require_stores = require("./stores.cjs");
|
||||
let _tanstack_history = require("@tanstack/history");
|
||||
let _tanstack_router_core_isServer = require("@tanstack/router-core/isServer");
|
||||
//#region src/router.ts
|
||||
function isExternalUrl(url, origin) {
|
||||
return url.protocol !== "http:" && url.protocol !== "https:" || url.origin !== origin || !!url.username || !!url.password;
|
||||
}
|
||||
function getUrlPath(url) {
|
||||
return url.pathname + url.search + url.hash;
|
||||
}
|
||||
function routeNeedsLoad(route) {
|
||||
return route.options.loader || route.options.beforeLoad || route.lazyFn || route.options.component?.preload || route.options.pendingComponent?.preload;
|
||||
}
|
||||
/**
|
||||
* Convert an unknown error into a minimal, serializable object.
|
||||
* Includes name and message (and stack in development).
|
||||
*/
|
||||
function defaultSerializeError(err) {
|
||||
if (err instanceof Error) {
|
||||
const obj = {
|
||||
name: err.name,
|
||||
message: err.message
|
||||
};
|
||||
if (process.env.NODE_ENV === "development") obj.stack = err.stack;
|
||||
return obj;
|
||||
}
|
||||
return { data: err };
|
||||
}
|
||||
/** Options for configuring trailing-slash behavior. */
|
||||
const trailingSlashOptions = {
|
||||
always: "always",
|
||||
never: "never",
|
||||
preserve: "preserve"
|
||||
};
|
||||
/**
|
||||
* Compute whether path, href or hash changed between previous and current
|
||||
* resolved locations.
|
||||
*/
|
||||
function getLocationChangeInfo(location, resolvedLocation) {
|
||||
return {
|
||||
fromLocation: resolvedLocation,
|
||||
toLocation: location,
|
||||
pathChanged: resolvedLocation?.pathname !== location.pathname,
|
||||
hrefChanged: resolvedLocation?.href !== location.href,
|
||||
hashChanged: resolvedLocation?.hash !== location.hash
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Return only state owned by the application, excluding volatile history
|
||||
* bookkeeping. Mask payloads (`__tempLocation`/`__tempKey`) are kept: they
|
||||
* distinguish otherwise-identical locations.
|
||||
*/
|
||||
function _getUserHistoryState({ key: _key, __TSR_key: _tsrKey, __TSR_index: _tsrIndex, __hashScrollIntoViewOptions: _hashScroll, ...state }) {
|
||||
return state;
|
||||
}
|
||||
function lifecycleEnd(matches) {
|
||||
return matches.findIndex((match) => match.status === "error" || match.status === "notFound" || match._notFound) + 1;
|
||||
}
|
||||
/** Run route lifecycle callbacks in leave/enter/stay phases. */
|
||||
function runRouteLifecycle(router, previous, matches, previousEnd, nextEnd, owner) {
|
||||
if (previousEnd) previous = previous.slice(0, previousEnd);
|
||||
if (nextEnd) matches = matches.slice(0, nextEnd);
|
||||
for (const match of previous) {
|
||||
if (owner && router._tx !== owner) return;
|
||||
if (!matches.some((candidate) => candidate.routeId === match.routeId)) router.routesById[match.routeId].options.onLeave?.(match);
|
||||
}
|
||||
for (const match of matches) {
|
||||
if (owner && router._tx !== owner) return;
|
||||
router.routesById[match.routeId].options[previous.some((candidate) => candidate.routeId === match.routeId) ? "onStay" : "onEnter"]?.(match);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Core, framework-agnostic router engine that powers TanStack Router.
|
||||
*
|
||||
* Provides navigation, matching, loading, preloading, caching and event APIs
|
||||
* used by framework adapters (React/Solid). Prefer framework helpers like
|
||||
* `createRouter` in app code.
|
||||
*
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/RouterType
|
||||
*/
|
||||
var RouterCore = class {
|
||||
/**
|
||||
* @deprecated Use the `createRouter` function instead
|
||||
*/
|
||||
constructor(options, getStoreConfig) {
|
||||
this.tempLocationKey = `${Math.round(Math.random() * 1e7)}`;
|
||||
this._scroll = { next: true };
|
||||
this.subscribers = /* @__PURE__ */ new Set();
|
||||
this._cache = /* @__PURE__ */ new Map();
|
||||
this._committed = [];
|
||||
this.startTransition = async (fn) => {
|
||||
fn();
|
||||
return false;
|
||||
};
|
||||
this.update = (newOptions) => {
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
if (newOptions.notFoundRoute) console.warn("The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/framework/react/guide/not-found-errors#migrating-from-notfoundroute for more info.");
|
||||
}
|
||||
const prevOptions = this.options;
|
||||
this.options = {
|
||||
...prevOptions,
|
||||
...newOptions
|
||||
};
|
||||
this.isServer = this.options.isServer ?? _tanstack_router_core_isServer.isServer ?? typeof document === "undefined";
|
||||
if (!(_tanstack_router_core_isServer.isServer ?? this.isServer)) this.staticLocations = /* @__PURE__ */ new WeakMap();
|
||||
this.protocolAllowlist = new Set(this.options.protocolAllowlist);
|
||||
if (!this.history || this.options.history && this.options.history !== this.history) if (!this.options.history) {
|
||||
if (!(_tanstack_router_core_isServer.isServer ?? this.isServer)) this.history = (0, _tanstack_history.createBrowserHistory)();
|
||||
} else this.history = this.options.history;
|
||||
this.origin = this.options.origin;
|
||||
if (!this.origin) if (!(_tanstack_router_core_isServer.isServer ?? this.isServer) && window?.origin && window.origin !== "null") this.origin = window.origin;
|
||||
else this.origin = "http://localhost";
|
||||
const nextBasepath = this.options.basepath ?? "/";
|
||||
const nextRewriteOption = this.options.rewrite;
|
||||
const rewriteChanged = this.basepath !== nextBasepath || prevOptions?.rewrite !== nextRewriteOption || prevOptions?.caseSensitive !== this.options.caseSensitive;
|
||||
if (rewriteChanged) {
|
||||
this.basepath = nextBasepath;
|
||||
this.rewrite = nextBasepath !== "/" && require_path.trimPath(nextBasepath) ? require_rewrite.rewriteBasepath(nextBasepath, this.options.caseSensitive, nextRewriteOption) : nextRewriteOption;
|
||||
}
|
||||
if (this.history) this.updateLatestLocation();
|
||||
if (this.options.routeTree !== this.routeTree || (_tanstack_router_core_isServer.isServer ?? this.isServer) && prevOptions?.caseSensitive !== this.options.caseSensitive) {
|
||||
this.routeTree = this.options.routeTree;
|
||||
let processRouteTreeResult;
|
||||
if (process.env.NODE_ENV !== "development" && (_tanstack_router_core_isServer.isServer ?? this.isServer) && globalThis.__TSR_CACHE__ && globalThis.__TSR_CACHE__.routeTree === this.routeTree && globalThis.__TSR_CACHE__.caseSensitive === this.options.caseSensitive) processRouteTreeResult = globalThis.__TSR_CACHE__.processRouteTreeResult;
|
||||
else {
|
||||
processRouteTreeResult = this.buildRouteTree();
|
||||
if (process.env.NODE_ENV !== "development" && (_tanstack_router_core_isServer.isServer ?? this.isServer) && globalThis.__TSR_CACHE__ === void 0) globalThis.__TSR_CACHE__ = {
|
||||
routeTree: this.routeTree,
|
||||
caseSensitive: this.options.caseSensitive,
|
||||
processRouteTreeResult
|
||||
};
|
||||
}
|
||||
this.setRoutes(processRouteTreeResult);
|
||||
}
|
||||
if (!this.stores) {
|
||||
if (this.latestLocation) {
|
||||
const config = this.getStoreConfig(this);
|
||||
this.batch = config.batch;
|
||||
this.stores = require_stores.createRouterStores(this.latestLocation, config);
|
||||
if (!(_tanstack_router_core_isServer.isServer ?? this.isServer)) require_scroll_restoration.setupScrollRestoration(this);
|
||||
}
|
||||
} else if (rewriteChanged) this.stores.location.set(this.latestLocation);
|
||||
};
|
||||
this.updateLatestLocation = () => {
|
||||
this.latestLocation = this.parseLocation(this.history.location, this.latestLocation);
|
||||
};
|
||||
this.buildRouteTree = () => {
|
||||
const result = require_new_process_route_tree.processRouteTree(this.routeTree, this.options.caseSensitive);
|
||||
if (this.options.routeMasks) require_new_process_route_tree.processRouteMasks(this.options.routeMasks, result.processedTree);
|
||||
return {
|
||||
...result,
|
||||
resolvePathCache: require_sieve_cache.createSieveCache(1e3)
|
||||
};
|
||||
};
|
||||
this.subscribe = (eventType, fn) => {
|
||||
const listener = {
|
||||
eventType,
|
||||
fn
|
||||
};
|
||||
this.subscribers.add(listener);
|
||||
return () => {
|
||||
this.subscribers.delete(listener);
|
||||
};
|
||||
};
|
||||
this.emit = (routerEvent) => {
|
||||
for (const listener of this.subscribers) if (listener.eventType === routerEvent.type) try {
|
||||
listener.fn(routerEvent);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
};
|
||||
this.parseLocation = (locationToParse, previousLocation) => {
|
||||
const parse = ({ pathname, search, hash, href }, state) => {
|
||||
if (!this.rewrite && !/[ \x00-\x1f\x7f\u0080-\uffff]/.test(pathname)) {
|
||||
const parsedSearch = this.options.parseSearch(search);
|
||||
const searchStr = this.options.stringifySearch(parsedSearch);
|
||||
return {
|
||||
href: pathname + searchStr + hash,
|
||||
publicHref: pathname + searchStr + hash,
|
||||
pathname: require_utils.decodePath(pathname),
|
||||
external: false,
|
||||
searchStr,
|
||||
search: require_utils.nullReplaceEqualDeep(previousLocation?.search, parsedSearch),
|
||||
hash: require_utils.decodePath(hash.slice(1)),
|
||||
state: require_utils.replaceEqualDeep(previousLocation?.state, state)
|
||||
};
|
||||
}
|
||||
const url = require_rewrite.executeRewriteInput(this.rewrite, new URL(href, this.origin));
|
||||
const parsedSearch = this.options.parseSearch(url.search);
|
||||
const searchStr = this.options.stringifySearch(parsedSearch);
|
||||
url.search = searchStr;
|
||||
return {
|
||||
href: url.href.replace(url.origin, ""),
|
||||
publicHref: href,
|
||||
pathname: require_utils.decodePath((0, _tanstack_history.normalizeProtocolRelative)(url.pathname)),
|
||||
external: !!this.rewrite && isExternalUrl(url, this.origin),
|
||||
searchStr,
|
||||
search: require_utils.nullReplaceEqualDeep(previousLocation?.search, parsedSearch),
|
||||
hash: require_utils.decodePath(url.hash.slice(1)),
|
||||
state: require_utils.replaceEqualDeep(previousLocation?.state, state)
|
||||
};
|
||||
};
|
||||
const location = parse(locationToParse, locationToParse.state);
|
||||
const { __tempLocation, __tempKey } = location.state;
|
||||
if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {
|
||||
const parsedTempLocation = parse(__tempLocation, {
|
||||
...__tempLocation.state,
|
||||
__tempLocation: void 0,
|
||||
key: location.state.key,
|
||||
__TSR_key: location.state.__TSR_key
|
||||
});
|
||||
parsedTempLocation.maskedLocation = location;
|
||||
return parsedTempLocation;
|
||||
}
|
||||
return location;
|
||||
};
|
||||
this.matchRoutes = (pathnameOrNext, locationSearchOrOpts, opts) => {
|
||||
if (typeof pathnameOrNext === "string") return this.matchRoutesInternal({
|
||||
pathname: pathnameOrNext,
|
||||
search: locationSearchOrOpts
|
||||
}, opts);
|
||||
return this.matchRoutesInternal(pathnameOrNext, locationSearchOrOpts);
|
||||
};
|
||||
this.getMatchedRoutes = (pathname) => {
|
||||
const rawParams = Object.create(null);
|
||||
const match = require_new_process_route_tree.findRouteMatch(require_path.trimPathRight(pathname), this.processedTree, true);
|
||||
if (match) Object.assign(rawParams, match.rawParams);
|
||||
return [
|
||||
match?.branch || [this.routesById["__root__"]],
|
||||
rawParams,
|
||||
match?.route
|
||||
];
|
||||
};
|
||||
this.buildLocation = (opts) => {
|
||||
if (!(_tanstack_router_core_isServer.isServer ?? this.isServer)) {
|
||||
const cached = this.staticLocations.get(opts);
|
||||
if (cached) return cached;
|
||||
}
|
||||
let usedCurrent = false;
|
||||
const build = (dest = {}) => {
|
||||
if (dest.href) {
|
||||
const parsed = (0, _tanstack_history.parseHref)(dest.href, {});
|
||||
dest = {
|
||||
...dest,
|
||||
to: require_rewrite.executeRewriteInput(this.rewrite, new URL(parsed.pathname, this.origin)).pathname,
|
||||
search: this.options.parseSearch(parsed.search),
|
||||
hash: parsed.hash.slice(1)
|
||||
};
|
||||
}
|
||||
const currentLocation = dest._fromLocation || this._pendingLocation || this.latestLocation;
|
||||
let lightweight;
|
||||
const current = () => {
|
||||
usedCurrent = true;
|
||||
return currentLocation;
|
||||
};
|
||||
const currentMatch = () => {
|
||||
usedCurrent = true;
|
||||
return lightweight ??= this.matchRoutesLightweight(currentLocation);
|
||||
};
|
||||
if (process.env.NODE_ENV !== "production" && dest.from && dest._isNavigate) {
|
||||
const [allFromMatches] = this.getMatchedRoutes(dest.from);
|
||||
const [matchedRoutes, fullPath] = currentMatch();
|
||||
const matchedFrom = require_utils.findLast(matchedRoutes, (d) => {
|
||||
return comparePaths(d.fullPath, dest.from);
|
||||
});
|
||||
const matchedCurrent = require_utils.findLast(allFromMatches, (d) => {
|
||||
return comparePaths(d.fullPath, fullPath);
|
||||
});
|
||||
if (!matchedFrom && !matchedCurrent) console.warn(`Could not find match for from: ${dest.from}`);
|
||||
}
|
||||
const to = dest.to ? `${dest.to}` : ".";
|
||||
const nextTo = require_path.resolvePath(to[0] === "/" ? "" : dest.unsafeRelative === "path" ? current().pathname : dest.from ?? currentMatch()[1], to, this.options.trailingSlash, this.resolvePathCache);
|
||||
const destRoute = this.routesByPath[require_path.trimPathRight(nextTo)];
|
||||
const isTemplate = nextTo.includes("$");
|
||||
let destRoutes;
|
||||
if (destRoute) destRoutes = destRoute._branch ??= require_new_process_route_tree.buildRouteBranch(destRoute);
|
||||
else if (isTemplate) destRoutes = [];
|
||||
else {
|
||||
const [matchedRoutes, rawParams, foundRoute] = this.getMatchedRoutes(nextTo);
|
||||
destRoutes = matchedRoutes;
|
||||
if (this.options.notFoundRoute && (!foundRoute || foundRoute.path !== "/" && rawParams["**"])) destRoutes = [...destRoutes, this.options.notFoundRoute];
|
||||
}
|
||||
const interpolation = isTemplate ? destRoute?._interpolation ?? require_new_process_route_tree.parseSegments(false, { fullPath: nextTo }, 0) : void 0;
|
||||
let nextParams;
|
||||
for (const route of destRoutes) {
|
||||
const fn = route.options.params?.stringify ?? route.options.stringifyParams;
|
||||
if (fn) {
|
||||
const fromParams = currentMatch()[3];
|
||||
nextParams ??= resolveNextParams(dest.params, fromParams);
|
||||
if (!require_utils.hasKeys(nextParams)) break;
|
||||
if (nextParams === fromParams) nextParams = Object.assign(require_utils.createNull(), nextParams);
|
||||
try {
|
||||
Object.assign(nextParams, fn(nextParams));
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
nextParams ??= resolveNextParams(dest.params, needsInheritedParams(dest.params, interpolation) ? currentMatch()[3] : EMPTY_RECORD);
|
||||
const nextPathname = opts.leaveParams ? nextTo : (0, _tanstack_history.normalizeProtocolRelative)(require_utils.decodePath(interpolation ? require_path.interpolatePath(nextTo, interpolation, nextParams, this.pathParamsDecoder) : nextTo));
|
||||
if (process.env.NODE_ENV !== "production" && destRoute && !opts.leaveParams) try {
|
||||
const foundRoute = this.getMatchedRoutes(nextPathname)[2];
|
||||
if (foundRoute?.id !== destRoute.id) console.warn(`Generated path "${nextPathname}" for route "${destRoute.id}" matched route "${foundRoute?.id}" instead. This can happen when multiple route templates resolve to the same URL. Use the route template that matches the intended route, or adjust params.stringify if it changed the target path.`);
|
||||
} catch {}
|
||||
const middlewares = getSearchMiddlewares(destRoutes, opts._includeValidateSearch);
|
||||
const fromSearch = () => {
|
||||
let search = currentMatch()[2];
|
||||
if (opts._includeValidateSearch && this.options.search?.strict) {
|
||||
const validatedSearch = {};
|
||||
destRoutes.forEach((route) => {
|
||||
if (route.options.validateSearch) try {
|
||||
Object.assign(validatedSearch, validateSearch(route.options.validateSearch, {
|
||||
...validatedSearch,
|
||||
...search
|
||||
}));
|
||||
} catch {}
|
||||
});
|
||||
search = validatedSearch;
|
||||
}
|
||||
return search;
|
||||
};
|
||||
const nextSearch = middlewares.length ? applySearchMiddleware(middlewares, fromSearch(), dest) : dest.search === true ? fromSearch() : typeof dest.search === "function" ? dest.search(fromSearch()) : dest.search || EMPTY_RECORD;
|
||||
const searchStr = this.options.stringifySearch(nextSearch);
|
||||
const hash = dest.hash === true ? current().hash : typeof dest.hash === "function" ? dest.hash(current().hash) : dest.hash || void 0;
|
||||
const hashStr = hash ? `#${hash}` : "";
|
||||
const nextState = !dest.state ? EMPTY_RECORD : dest.state === true ? current().state : typeof dest.state === "function" ? dest.state(current().state) : dest.state;
|
||||
const fullPath = `${nextPathname}${searchStr}${hashStr}`;
|
||||
let href;
|
||||
let publicHref;
|
||||
let external = false;
|
||||
if (this.rewrite) {
|
||||
const url = new URL(fullPath, this.origin);
|
||||
const origin = url.origin;
|
||||
const rewrittenUrl = require_rewrite.executeRewriteOutput(this.rewrite, url);
|
||||
href = getUrlPath(url);
|
||||
if (isExternalUrl(rewrittenUrl, origin)) {
|
||||
publicHref = rewrittenUrl.href;
|
||||
external = true;
|
||||
} else publicHref = (0, _tanstack_history.normalizeProtocolRelative)(getUrlPath(rewrittenUrl));
|
||||
} else {
|
||||
href = require_utils.encodePathLikeUrl(fullPath);
|
||||
publicHref = href;
|
||||
}
|
||||
return {
|
||||
publicHref,
|
||||
href,
|
||||
pathname: nextPathname,
|
||||
search: nextSearch,
|
||||
searchStr,
|
||||
state: nextState,
|
||||
hash: hash ?? "",
|
||||
external,
|
||||
unmaskOnReload: dest.unmaskOnReload
|
||||
};
|
||||
};
|
||||
const next = build(opts);
|
||||
if (opts.mask) next.maskedLocation = build({
|
||||
from: opts.from,
|
||||
...opts.mask
|
||||
});
|
||||
else if (this.options.routeMasks) {
|
||||
const match = require_new_process_route_tree.findFlatMatch(next.pathname, this.processedTree);
|
||||
if (match) {
|
||||
const params = Object.assign(require_utils.createNull(), match.rawParams);
|
||||
const { from: _from, params: maskParams, ...maskProps } = match.route;
|
||||
const nextParams = resolveNextParams(maskParams, params);
|
||||
next.maskedLocation = build({
|
||||
from: opts.from,
|
||||
...maskProps,
|
||||
params: nextParams
|
||||
});
|
||||
}
|
||||
}
|
||||
if (!(_tanstack_router_core_isServer.isServer ?? this.isServer) && !usedCurrent && opts._fromLocation && !next.maskedLocation) this.staticLocations.set(opts, next);
|
||||
return next;
|
||||
};
|
||||
this.commitLocation = async ({ viewTransition, ignoreBlocker, ...next }) => {
|
||||
if (_tanstack_router_core_isServer.isServer ?? this.isServer) return;
|
||||
const nextLocation = next.maskedLocation ?? next;
|
||||
if (nextLocation.external && !(_tanstack_router_core_isServer.isServer ?? this.isServer)) return documentNavigation(this, nextLocation.publicHref, {
|
||||
replace: next.replace,
|
||||
ignoreBlocker
|
||||
});
|
||||
let historyAction;
|
||||
const isSameLocation = require_path.trimPathRight(this.latestLocation.href) === require_path.trimPathRight(next.href) && require_utils.deepEqual(_getUserHistoryState(next.state), _getUserHistoryState(this.latestLocation.state));
|
||||
const previousCommitPromise = this._commitPromise;
|
||||
let resolve;
|
||||
const commitPromise = new Promise((done) => {
|
||||
resolve = done;
|
||||
});
|
||||
commitPromise.resolve = () => {
|
||||
resolve();
|
||||
previousCommitPromise?.resolve();
|
||||
};
|
||||
this._commitPromise = commitPromise;
|
||||
if (isSameLocation) this.load();
|
||||
else {
|
||||
let { maskedLocation, hashScrollIntoView, ...nextHistory } = next;
|
||||
if (maskedLocation) {
|
||||
nextHistory = {
|
||||
...maskedLocation,
|
||||
state: {
|
||||
...maskedLocation.state,
|
||||
__tempKey: void 0,
|
||||
__tempLocation: {
|
||||
...nextHistory,
|
||||
search: nextHistory.searchStr,
|
||||
state: {
|
||||
...nextHistory.state,
|
||||
__tempKey: void 0,
|
||||
__tempLocation: void 0,
|
||||
__TSR_key: void 0,
|
||||
key: void 0
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if (nextHistory.unmaskOnReload ?? this.options.unmaskOnReload ?? false) nextHistory.state.__tempKey = this.tempLocationKey;
|
||||
}
|
||||
nextHistory.state = {
|
||||
...nextHistory.state,
|
||||
__hashScrollIntoViewOptions: hashScrollIntoView ?? this.options.defaultHashScrollIntoView ?? true
|
||||
};
|
||||
this.shouldViewTransition = viewTransition;
|
||||
historyAction = next.replace ? "REPLACE" : "PUSH";
|
||||
this.history[historyAction === "REPLACE" ? "replace" : "push"](nextHistory.publicHref, nextHistory.state, { ignoreBlocker });
|
||||
if (!this.history.subscribers.size) this.load({ action: { type: historyAction } });
|
||||
}
|
||||
this._scroll.next = next.resetScroll ?? true;
|
||||
return this._commitPromise;
|
||||
};
|
||||
this.buildAndCommitLocation = ({ replace, resetScroll, hashScrollIntoView, viewTransition, ignoreBlocker, ...rest } = {}) => {
|
||||
if (_tanstack_router_core_isServer.isServer ?? this.isServer) return Promise.resolve();
|
||||
const location = this.buildLocation({
|
||||
...rest,
|
||||
_includeValidateSearch: true
|
||||
});
|
||||
this._pendingLocation = location;
|
||||
const commitPromise = this.commitLocation({
|
||||
...location,
|
||||
viewTransition,
|
||||
replace,
|
||||
resetScroll,
|
||||
hashScrollIntoView,
|
||||
ignoreBlocker
|
||||
});
|
||||
queueMicrotask(() => {
|
||||
if (this._pendingLocation === location) this._pendingLocation = void 0;
|
||||
});
|
||||
return commitPromise;
|
||||
};
|
||||
this.navigate = async ({ to, reloadDocument, href, publicHref, ...rest }) => {
|
||||
if (_tanstack_router_core_isServer.isServer ?? this.isServer) return;
|
||||
const hrefScheme = href ? require_utils.getUrlScheme(href) : void 0;
|
||||
if (hrefScheme || reloadDocument) {
|
||||
if (to !== void 0 || !href) {
|
||||
const location = this.buildLocation({
|
||||
to,
|
||||
...rest
|
||||
});
|
||||
const publicLocation = location.maskedLocation ?? location;
|
||||
href ??= publicLocation.publicHref;
|
||||
publicHref ??= publicLocation.publicHref;
|
||||
}
|
||||
const reloadHref = !hrefScheme && publicHref ? publicHref : href;
|
||||
return documentNavigation(this, reloadHref, rest);
|
||||
}
|
||||
return this.buildAndCommitLocation({
|
||||
...rest,
|
||||
href,
|
||||
to,
|
||||
_isNavigate: true
|
||||
});
|
||||
};
|
||||
this.load = async (opts) => {
|
||||
if (_tanstack_router_core_isServer.isServer ?? this.isServer) return (0, _tanstack_router_core_isServer.loadServerRoute)(this, opts);
|
||||
this.updateLatestLocation();
|
||||
if (opts?.action) this._scroll.hash = opts.action.type === "PUSH" || opts.action.type === "REPLACE";
|
||||
await require_load_client.loadClientRoute(this, opts);
|
||||
};
|
||||
this.startViewTransition = (fn) => {
|
||||
const shouldViewTransition = this.shouldViewTransition ?? this.options.defaultViewTransition;
|
||||
this.shouldViewTransition = void 0;
|
||||
if (shouldViewTransition && !(_tanstack_router_core_isServer.isServer ?? typeof document === "undefined") && typeof document.startViewTransition === "function") {
|
||||
let startViewTransitionParams;
|
||||
if (typeof shouldViewTransition === "object" && window.CSS?.supports?.("selector(:active-view-transition-type(a))")) {
|
||||
const next = this.latestLocation;
|
||||
const prevLocation = this.stores.resolvedLocation.get();
|
||||
const resolvedViewTransitionTypes = typeof shouldViewTransition.types === "function" ? shouldViewTransition.types(getLocationChangeInfo(next, prevLocation)) : shouldViewTransition.types;
|
||||
if (resolvedViewTransitionTypes === false) return fn();
|
||||
startViewTransitionParams = {
|
||||
update: fn,
|
||||
types: resolvedViewTransitionTypes
|
||||
};
|
||||
} else startViewTransitionParams = fn;
|
||||
return document.startViewTransition(startViewTransitionParams).updateCallbackDone;
|
||||
}
|
||||
return fn();
|
||||
};
|
||||
this.invalidate = (opts) => {
|
||||
const committedMatches = this._committed;
|
||||
const filter = opts?.filter;
|
||||
const preloads = this._preloads;
|
||||
const invalidIds = /* @__PURE__ */ new Set();
|
||||
const consider = (match) => {
|
||||
if (!filter || filter(match)) invalidIds.add(match.id);
|
||||
};
|
||||
committedMatches.forEach(consider);
|
||||
this._cache.forEach(consider);
|
||||
preloads?.forEach((matches) => matches.forEach(consider));
|
||||
this._tx?.[3].forEach(consider);
|
||||
const discardedPreloads = [];
|
||||
for (const [controller, matches] of preloads ?? []) if (matches.some((match) => invalidIds.has(match.id))) {
|
||||
preloads.delete(controller);
|
||||
discardedPreloads.push(controller);
|
||||
}
|
||||
const invalidate = (d) => {
|
||||
if (invalidIds.has(d.id)) {
|
||||
const route = this.routesById[d.routeId];
|
||||
const next = {
|
||||
...d,
|
||||
invalid: true,
|
||||
...(opts?.forcePending || d.status === "error" || d.status === "notFound") && routeNeedsLoad(route) ? {
|
||||
status: "pending",
|
||||
error: void 0
|
||||
} : void 0
|
||||
};
|
||||
d._flight = void 0;
|
||||
return next;
|
||||
}
|
||||
return d;
|
||||
};
|
||||
this._committed = committedMatches.map(invalidate);
|
||||
for (const [id, match] of this._cache) if (invalidIds.has(id)) {
|
||||
match.invalid = true;
|
||||
if (opts?.forcePending) match.status = "pending";
|
||||
}
|
||||
for (const id of invalidIds) this._flights?.delete(id);
|
||||
for (const controller of discardedPreloads) controller.abort();
|
||||
this.shouldViewTransition = false;
|
||||
return this.load({ sync: opts?.sync });
|
||||
};
|
||||
this.resolveRedirect = (redirect) => {
|
||||
const options = redirect.options;
|
||||
let href = redirect.headers.get("Location") || options.href;
|
||||
if (!href) {
|
||||
const location = this.buildLocation(options);
|
||||
href = (location.maskedLocation ?? location).publicHref || "/";
|
||||
}
|
||||
let scheme;
|
||||
if (require_utils.protocolRelativePrefixRegex.test(href) || (scheme = require_utils.getUrlScheme(href)) && !this.protocolAllowlist.has(scheme)) throw new Error(process.env.NODE_ENV !== "production" ? `Redirect blocked: unsafe protocol in href "${href}". Allowed protocols: ${Array.from(this.protocolAllowlist).join(", ")}.` : "Redirect blocked: unsafe protocol");
|
||||
if (scheme === "http:" || scheme === "https:") {
|
||||
const url = new URL(href);
|
||||
if (url.pathname.startsWith("//")) href = url.href;
|
||||
else if (!isExternalUrl(url, this.origin)) {
|
||||
href = getUrlPath(url);
|
||||
scheme = void 0;
|
||||
}
|
||||
}
|
||||
if (scheme) options.reloadDocument = true;
|
||||
options.href = href;
|
||||
redirect.headers.set("Location", href);
|
||||
return redirect;
|
||||
};
|
||||
this.clearCache = (opts) => {
|
||||
const cached = this._cache;
|
||||
const preloads = this._preloads;
|
||||
const filter = opts?.filter;
|
||||
const discarded = [];
|
||||
const discardedIds = [];
|
||||
for (const [id, match] of cached) if (!filter || filter(match)) {
|
||||
discardedIds.push(id);
|
||||
discarded.push(match);
|
||||
}
|
||||
const abort = [];
|
||||
for (const [controller, matches] of preloads ?? []) if (!filter || matches.some(filter)) {
|
||||
abort.push(controller);
|
||||
discarded.push(...matches);
|
||||
}
|
||||
for (const id of discardedIds) cached.delete(id);
|
||||
for (const controller of abort) preloads.delete(controller);
|
||||
for (const match of discarded) {
|
||||
const flight = match._flight;
|
||||
match._flight = void 0;
|
||||
if (flight && !--flight[2]) {
|
||||
if (this._flights?.get(match.id) === flight) this._flights.delete(match.id);
|
||||
abort.push(flight[1]);
|
||||
}
|
||||
}
|
||||
for (const controller of abort) controller.abort();
|
||||
};
|
||||
this.loadRouteChunk = require_load_client.loadRouteChunk;
|
||||
this.preloadRoute = (opts) => require_load_client.preloadClientRoute(this, opts);
|
||||
this.matchRoute = (location, opts) => {
|
||||
const matchLocation = {
|
||||
...location,
|
||||
to: location.to ? require_path.resolvePath(location.from || "", location.to, this.options.trailingSlash, this.resolvePathCache) : void 0,
|
||||
params: location.params || {},
|
||||
leaveParams: true
|
||||
};
|
||||
const next = this.buildLocation(matchLocation);
|
||||
const isPending = this.stores.status.get() === "pending";
|
||||
if (opts?.pending && !isPending) return false;
|
||||
const baseLocation = opts?.pending ?? !isPending ? this.latestLocation : this.stores.resolvedLocation.get() || this.stores.location.get();
|
||||
const match = require_new_process_route_tree.findSingleMatch(next.pathname, opts?.caseSensitive ?? false, opts?.fuzzy ?? false, baseLocation.pathname, this.processedTree);
|
||||
if (!match) return false;
|
||||
if (location.params) {
|
||||
if (!require_utils.deepEqual(match.rawParams, location.params, true)) return false;
|
||||
}
|
||||
if (opts?.includeSearch ?? true) return require_utils.deepEqual(baseLocation.search, next.search, true) ? match.rawParams : false;
|
||||
return match.rawParams;
|
||||
};
|
||||
this.getStoreConfig = getStoreConfig;
|
||||
if (options.pathParamsAllowedCharacters?.length) this.pathParamsDecoder = require_path.compileDecodeCharMap(options.pathParamsAllowedCharacters);
|
||||
this.update({
|
||||
defaultPreloadDelay: 50,
|
||||
defaultPendingMs: 1e3,
|
||||
defaultPendingMinMs: 500,
|
||||
context: void 0,
|
||||
...options,
|
||||
caseSensitive: options.caseSensitive ?? false,
|
||||
notFoundMode: options.notFoundMode ?? "fuzzy",
|
||||
stringifySearch: options.stringifySearch ?? require_searchParams.defaultStringifySearch,
|
||||
parseSearch: options.parseSearch ?? require_searchParams.defaultParseSearch,
|
||||
protocolAllowlist: options.protocolAllowlist ?? require_utils.DEFAULT_PROTOCOL_ALLOWLIST
|
||||
});
|
||||
if (!(_tanstack_router_core_isServer.isServer ?? typeof document === "undefined")) self.__TSR_ROUTER__ = this;
|
||||
}
|
||||
isShell() {
|
||||
return !!this.options.isShell;
|
||||
}
|
||||
get state() {
|
||||
return this.stores.__store.get();
|
||||
}
|
||||
setRoutes(caches) {
|
||||
Object.assign(this, caches);
|
||||
this.lightweightCache = /* @__PURE__ */ new WeakMap();
|
||||
if (!(_tanstack_router_core_isServer.isServer ?? this.isServer)) this.staticLocations = /* @__PURE__ */ new WeakMap();
|
||||
const notFoundRoute = this.options.notFoundRoute;
|
||||
if (notFoundRoute) {
|
||||
notFoundRoute.init(99999999999);
|
||||
if (this.routesById[notFoundRoute.id] !== notFoundRoute) notFoundRoute._interpolation = require_new_process_route_tree.parseSegments(false, notFoundRoute, 0);
|
||||
this.routesById[notFoundRoute.id] = notFoundRoute;
|
||||
}
|
||||
}
|
||||
matchRoutesInternal(next, opts) {
|
||||
const [initialMatchedRoutes, rawParams, foundRoute] = this.getMatchedRoutes(next.pathname);
|
||||
let matchedRoutes = initialMatchedRoutes;
|
||||
let isGlobalNotFound = false;
|
||||
if (foundRoute ? foundRoute.path !== "/" && rawParams["**"] : require_path.trimPathRight(next.pathname)) if (this.options.notFoundRoute) matchedRoutes = [...matchedRoutes, this.options.notFoundRoute];
|
||||
else isGlobalNotFound = true;
|
||||
const _notFoundRouteId = isGlobalNotFound ? findGlobalNotFoundRouteId(this.options.notFoundMode, matchedRoutes) : void 0;
|
||||
const matches = new Array(matchedRoutes.length);
|
||||
const committed = this._committed;
|
||||
const previousAt = (route, index) => {
|
||||
const match = committed[index];
|
||||
return match?.routeId === route.id ? match : route === this.options.notFoundRoute ? committed.find((candidate) => candidate.routeId === route.id) : void 0;
|
||||
};
|
||||
let strictParams;
|
||||
for (let index = 0; index < matchedRoutes.length; index++) {
|
||||
const route = matchedRoutes[index];
|
||||
const parentMatch = matches[index - 1];
|
||||
let preMatchSearch;
|
||||
let strictMatchSearch;
|
||||
let searchError;
|
||||
{
|
||||
const parentSearch = parentMatch?.search ?? next.search;
|
||||
const parentStrictSearch = parentMatch?._strictSearch ?? void 0;
|
||||
try {
|
||||
const strictSearch = validateSearch(route.options.validateSearch, { ...parentSearch }) ?? void 0;
|
||||
preMatchSearch = {
|
||||
...parentSearch,
|
||||
...strictSearch
|
||||
};
|
||||
strictMatchSearch = {
|
||||
...parentStrictSearch,
|
||||
...strictSearch
|
||||
};
|
||||
} catch (err) {
|
||||
let searchParamError = err;
|
||||
if (!(err instanceof SearchParamError)) searchParamError = new SearchParamError(err.message, { cause: err });
|
||||
if (opts?.throwOnError) throw searchParamError;
|
||||
preMatchSearch = parentSearch;
|
||||
strictMatchSearch = {};
|
||||
searchError = searchParamError;
|
||||
}
|
||||
}
|
||||
let loaderDeps = "";
|
||||
let loaderDepsHash = "";
|
||||
try {
|
||||
loaderDeps = route.options.loaderDeps?.({ search: preMatchSearch }) ?? "";
|
||||
loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) || "" : "";
|
||||
} catch (cause) {
|
||||
if (opts?.throwOnError) throw cause;
|
||||
searchError ??= cause;
|
||||
}
|
||||
const usedParams = require_utils.createNull();
|
||||
const interpolatedPath = route._interpolation ? require_path.interpolatePath(route.fullPath, route._interpolation, rawParams, this.pathParamsDecoder, usedParams) : route.fullPath;
|
||||
const matchId = route.id + interpolatedPath + loaderDepsHash;
|
||||
const previousMatch = previousAt(route, index);
|
||||
const existingMatch = process.env.NODE_ENV !== "production" && opts?._rematerialize ? void 0 : this._cache.get(matchId) ?? (previousMatch?.id === matchId ? previousMatch : void 0);
|
||||
strictParams = existingMatch?._strictParams ?? Object.assign(usedParams, strictParams);
|
||||
let paramsError;
|
||||
if (!existingMatch) try {
|
||||
extractStrictParams(route, strictParams);
|
||||
} catch (err) {
|
||||
if (require_not_found.isNotFound(err) || require_redirect.isRedirect(err)) paramsError = err;
|
||||
else paramsError = new PathParamError(err.message, { cause: err });
|
||||
if (opts?.throwOnError) throw paramsError;
|
||||
}
|
||||
const cause = previousMatch ? "stay" : "enter";
|
||||
let match;
|
||||
if (existingMatch) match = {
|
||||
...existingMatch,
|
||||
cause,
|
||||
search: previousMatch ? require_utils.nullReplaceEqualDeep(previousMatch.search, preMatchSearch) : require_utils.nullReplaceEqualDeep(existingMatch.search, preMatchSearch),
|
||||
_strictSearch: strictMatchSearch,
|
||||
searchError
|
||||
};
|
||||
else {
|
||||
const status = routeNeedsLoad(route) ? "pending" : "success";
|
||||
match = {
|
||||
id: matchId,
|
||||
ssr: _tanstack_router_core_isServer.isServer ?? this.isServer ? void 0 : route.options.ssr,
|
||||
index,
|
||||
routeId: route.id,
|
||||
params: previousMatch?.params ?? strictParams,
|
||||
_strictParams: strictParams,
|
||||
pathname: interpolatedPath,
|
||||
updatedAt: Date.now(),
|
||||
search: previousMatch ? require_utils.nullReplaceEqualDeep(previousMatch.search, preMatchSearch) : preMatchSearch,
|
||||
_strictSearch: strictMatchSearch,
|
||||
searchError,
|
||||
status,
|
||||
isFetching: false,
|
||||
error: void 0,
|
||||
paramsError,
|
||||
context: {},
|
||||
abortController: opts?._controller ?? new AbortController(),
|
||||
cause,
|
||||
loaderDeps: previousMatch ? require_utils.replaceEqualDeep(previousMatch.loaderDeps, loaderDeps) : loaderDeps,
|
||||
invalid: false,
|
||||
preload: false,
|
||||
staticData: route.options.staticData || {},
|
||||
fullPath: route.fullPath
|
||||
};
|
||||
}
|
||||
const _notFound = _notFoundRouteId === route.id;
|
||||
if (match._notFound && !_notFound) match.error = void 0;
|
||||
match._notFound = _notFound;
|
||||
matches[index] = match;
|
||||
}
|
||||
for (let index = 0; index < matches.length; index++) {
|
||||
const match = matches[index];
|
||||
match.params = match.cause === "stay" ? require_utils.nullReplaceEqualDeep(match.params, strictParams) : strictParams;
|
||||
if (opts?._controller) match.context = {};
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
/**
|
||||
* Lightweight route matching for buildLocation.
|
||||
* Only computes fullPath, accumulated search, and params - skipping expensive
|
||||
* operations like AbortController, loaderDeps, and full match objects.
|
||||
*/
|
||||
matchRoutesLightweight(location) {
|
||||
const lastRouteId = require_utils.last(this.stores.ids.get());
|
||||
const lastStateMatch = lastRouteId ? this.stores.byRoute.get(lastRouteId).get() : void 0;
|
||||
const lastStateMatchId = lastStateMatch?.id;
|
||||
const cached = this.lightweightCache.get(location);
|
||||
if (cached && cached[0] === lastStateMatchId) return cached[1];
|
||||
const [matchedRoutes, rawParams] = this.getMatchedRoutes(location.pathname);
|
||||
const lastRoute = require_utils.last(matchedRoutes);
|
||||
const accumulatedSearch = { ...location.search };
|
||||
for (const route of matchedRoutes) try {
|
||||
Object.assign(accumulatedSearch, validateSearch(route.options.validateSearch, accumulatedSearch));
|
||||
} catch {}
|
||||
const canReuseParams = lastStateMatch && lastStateMatch.routeId === lastRoute.id && lastStateMatch.pathname === location.pathname;
|
||||
let params;
|
||||
if (canReuseParams) params = lastStateMatch.params;
|
||||
else {
|
||||
const strictParams = rawParams;
|
||||
for (const route of matchedRoutes) try {
|
||||
extractStrictParams(route, strictParams);
|
||||
} catch {}
|
||||
params = strictParams;
|
||||
}
|
||||
const result = [
|
||||
matchedRoutes,
|
||||
lastRoute.fullPath,
|
||||
accumulatedSearch,
|
||||
params
|
||||
];
|
||||
this.lightweightCache.set(location, [lastStateMatchId, result]);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
async function documentNavigation(router, href, { replace, ignoreBlocker }) {
|
||||
if (require_utils.isDangerousProtocol(href, router.protocolAllowlist)) {
|
||||
if (process.env.NODE_ENV !== "production") console.warn(`Blocked navigation to dangerous protocol: ${href}`);
|
||||
return;
|
||||
}
|
||||
if (!ignoreBlocker) {
|
||||
const blockers = router.history._getBlockers();
|
||||
for (const blocker of blockers) if (blocker?.blockerFn) {
|
||||
if (await blocker.blockerFn({
|
||||
currentLocation: router.history.location,
|
||||
nextLocation: router.history.location,
|
||||
action: replace ? "REPLACE" : "PUSH"
|
||||
})) return;
|
||||
}
|
||||
}
|
||||
router.history._ignoreNextBeforeUnload?.(href);
|
||||
if (replace) window.location.replace(href);
|
||||
else window.location.href = href;
|
||||
}
|
||||
/**
|
||||
* In non-production environments,
|
||||
* augment the RouterCore class with a `_refreshRoute` method
|
||||
* dedicated to HMR.
|
||||
*/
|
||||
if (process.env.NODE_ENV !== "production") {
|
||||
RouterCore.prototype._replaceRouteChunk = require_load_client.replaceRouteChunk;
|
||||
RouterCore.prototype._refreshRoute = async function() {
|
||||
this._serverResult = void 0;
|
||||
this.updateLatestLocation();
|
||||
await require_load_client.refreshClientRoute(this);
|
||||
};
|
||||
}
|
||||
/** Error thrown when search parameter validation fails. */
|
||||
var SearchParamError = class extends Error {};
|
||||
/** Error thrown when path parameter parsing/validation fails. */
|
||||
var PathParamError = class extends Error {};
|
||||
const normalize = (str) => str.endsWith("/") && str.length > 1 ? str.slice(0, -1) : str;
|
||||
function comparePaths(a, b) {
|
||||
return normalize(a) === normalize(b);
|
||||
}
|
||||
/**
|
||||
* Lazily import a module function and forward arguments to it, retaining
|
||||
* parameter and return types for the selected export key.
|
||||
*/
|
||||
function lazyFn(fn, key) {
|
||||
return async (...args) => {
|
||||
return (await fn())[key || "default"](...args);
|
||||
};
|
||||
}
|
||||
/** Create an initial RouterState from a parsed location. */
|
||||
function getInitialRouterState(location) {
|
||||
return {
|
||||
isLoading: false,
|
||||
status: "idle",
|
||||
resolvedLocation: void 0,
|
||||
location,
|
||||
matches: []
|
||||
};
|
||||
}
|
||||
function validateSearch(validateSearch, input) {
|
||||
if (validateSearch == null) return {};
|
||||
if ("~standard" in validateSearch) {
|
||||
const result = validateSearch["~standard"].validate(input);
|
||||
if (result instanceof Promise) throw new SearchParamError("Async validation not supported");
|
||||
if (result.issues) throw new SearchParamError(JSON.stringify(result.issues, void 0, 2), { cause: result });
|
||||
return result.value;
|
||||
}
|
||||
if ("parse" in validateSearch) return validateSearch.parse(input);
|
||||
if (typeof validateSearch === "function") return validateSearch(input);
|
||||
return {};
|
||||
}
|
||||
function resolveNextParams(spec, base) {
|
||||
if (spec === void 0 || spec === true) return base;
|
||||
const next = Object.create(null);
|
||||
if (spec === false || spec === null) return next;
|
||||
if (typeof spec === "function") {
|
||||
Object.assign(next, base);
|
||||
return Object.assign(next, spec(next));
|
||||
}
|
||||
return Object.assign(next, base, spec);
|
||||
}
|
||||
function needsInheritedParams(spec, interpolation) {
|
||||
if (typeof spec === "function") return true;
|
||||
if (!interpolation || spec === false || spec === null) return false;
|
||||
return spec === void 0 || spec === true || interpolation.some((part) => typeof part !== "string" && !require_utils.hasOwn.call(spec, part[1]));
|
||||
}
|
||||
const EMPTY_RECORD = Object.freeze({});
|
||||
function getSearchMiddlewares(destRoutes, includeValidateSearch) {
|
||||
const middlewares = [];
|
||||
for (let i = 0; i < destRoutes.length; i++) {
|
||||
const routeOptions = destRoutes[i].options;
|
||||
if ("search" in routeOptions) {
|
||||
if (routeOptions.search?.middlewares) middlewares.push(...routeOptions.search.middlewares);
|
||||
} else if (routeOptions.preSearchFilters || routeOptions.postSearchFilters) {
|
||||
const legacyMiddleware = ({ search, next }) => {
|
||||
const result = next(routeOptions.preSearchFilters ? routeOptions.preSearchFilters.reduce((prev, next) => next(prev), search) : search);
|
||||
return routeOptions.postSearchFilters ? routeOptions.postSearchFilters.reduce((prev, next) => next(prev), result) : result;
|
||||
};
|
||||
middlewares.push(legacyMiddleware);
|
||||
}
|
||||
const routeValidateSearch = routeOptions.validateSearch;
|
||||
if (includeValidateSearch && routeValidateSearch) {
|
||||
const validate = ({ search, next, meta }) => {
|
||||
const result = next(search);
|
||||
try {
|
||||
const validated = validateSearch(routeValidateSearch, result);
|
||||
if (meta && validated) {
|
||||
for (const key in validated) if (!(key in result)) (meta.defaulted ||= /* @__PURE__ */ new Map()).set(key, validated[key]);
|
||||
}
|
||||
return {
|
||||
...result,
|
||||
...validated
|
||||
};
|
||||
} catch {}
|
||||
return result;
|
||||
};
|
||||
middlewares.push(validate);
|
||||
}
|
||||
}
|
||||
return middlewares;
|
||||
}
|
||||
function applySearchMiddleware(middlewares, search, dest) {
|
||||
const applyNext = (index, currentSearch, meta) => {
|
||||
if (index >= middlewares.length) {
|
||||
if (!dest.search) return {};
|
||||
if (dest.search === true) return currentSearch;
|
||||
const result = require_utils.functionalUpdate(dest.search, currentSearch);
|
||||
if (meta) meta.explicit = result;
|
||||
return result;
|
||||
}
|
||||
const next = (newSearch, collectMeta) => {
|
||||
if (collectMeta) {
|
||||
const nextMeta = meta || {};
|
||||
return {
|
||||
search: applyNext(index + 1, newSearch, nextMeta),
|
||||
meta: nextMeta
|
||||
};
|
||||
}
|
||||
return applyNext(index + 1, newSearch, meta);
|
||||
};
|
||||
return middlewares[index]({
|
||||
search: currentSearch,
|
||||
next,
|
||||
meta
|
||||
});
|
||||
};
|
||||
return applyNext(0, search);
|
||||
}
|
||||
function findGlobalNotFoundRouteId(notFoundMode, routes) {
|
||||
if (notFoundMode !== "root") {
|
||||
let fallback;
|
||||
for (let i = routes.length - 1; i >= 0; i--) {
|
||||
const route = routes[i];
|
||||
if (route.options.notFoundComponent) return route.id;
|
||||
fallback ||= route.children && route.id;
|
||||
}
|
||||
if (fallback) return fallback;
|
||||
}
|
||||
return require_root.rootRouteId;
|
||||
}
|
||||
function extractStrictParams(route, accumulatedParams) {
|
||||
const parseParams = route.options.params?.parse ?? route.options.parseParams;
|
||||
if (parseParams) Object.assign(accumulatedParams, parseParams(accumulatedParams));
|
||||
}
|
||||
//#endregion
|
||||
exports.PathParamError = PathParamError;
|
||||
exports.RouterCore = RouterCore;
|
||||
exports.SearchParamError = SearchParamError;
|
||||
exports.defaultSerializeError = defaultSerializeError;
|
||||
exports.getInitialRouterState = getInitialRouterState;
|
||||
exports.getLocationChangeInfo = getLocationChangeInfo;
|
||||
exports.lazyFn = lazyFn;
|
||||
exports.lifecycleEnd = lifecycleEnd;
|
||||
exports.runRouteLifecycle = runRouteLifecycle;
|
||||
exports.trailingSlashOptions = trailingSlashOptions;
|
||||
|
||||
//# sourceMappingURL=router.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"router.cjs","names":[],"sources":["../../src/router.ts"],"sourcesContent":["import {\n createBrowserHistory,\n normalizeProtocolRelative,\n parseHref,\n} from '@tanstack/history'\nimport { isServer, loadServerRoute } from '@tanstack/router-core/isServer'\nimport {\n DEFAULT_PROTOCOL_ALLOWLIST,\n createNull,\n decodePath,\n deepEqual,\n encodePathLikeUrl,\n findLast,\n functionalUpdate,\n getUrlScheme,\n hasKeys,\n hasOwn,\n isDangerousProtocol,\n last,\n nullReplaceEqualDeep,\n protocolRelativePrefixRegex,\n replaceEqualDeep,\n} from './utils'\nimport {\n buildRouteBranch,\n findFlatMatch,\n findRouteMatch,\n findSingleMatch,\n parseSegments,\n processRouteMasks,\n processRouteTree,\n} from './new-process-route-tree'\nimport {\n compileDecodeCharMap,\n interpolatePath,\n resolvePath,\n trimPath,\n trimPathRight,\n} from './path'\nimport { createSieveCache } from './sieve-cache'\nimport { isNotFound } from './not-found'\nimport { setupScrollRestoration } from './scroll-restoration'\nimport { defaultParseSearch, defaultStringifySearch } from './searchParams'\nimport { rootRouteId } from './root'\nimport { isRedirect } from './redirect'\nimport {\n loadClientRoute,\n loadRouteChunk,\n preloadClientRoute,\n refreshClientRoute,\n replaceRouteChunk,\n} from './load-client'\nimport {\n executeRewriteInput,\n executeRewriteOutput,\n rewriteBasepath,\n} from './rewrite'\nimport { createRouterStores } from './stores'\nimport type { SieveCache } from './sieve-cache'\nimport type { RouteInterpolation } from './path'\nimport type {\n ProcessRouteTreeResult,\n ProcessedTree,\n} from './new-process-route-tree'\nimport type { SearchParser, SearchSerializer } from './searchParams'\nimport type { AnyRedirect, ResolvedRedirect } from './redirect'\nimport type {\n LoadTransaction,\n LoaderFlight,\n PendingSession,\n} from './load-client'\nimport type { ServerLoadResult } from './load-server'\nimport type {\n HistoryAction,\n HistoryLocation,\n HistoryState,\n ParsedHistoryState,\n RouterHistory,\n} from '@tanstack/history'\n\nimport type {\n Awaitable,\n Constrain,\n NoInfer,\n NonNullableUpdater,\n PickAsRequired,\n Updater,\n} from './utils'\nimport type { ParsedLocation } from './location'\nimport type {\n AnyContext,\n AnyRoute,\n AnyRouteWithContext,\n LoaderStaleReloadMode,\n MakeRemountDepsOptionsUnion,\n RouteMask,\n SearchMiddleware,\n SearchMiddlewareMeta,\n} from './route'\nimport type {\n FullSearchSchema,\n RouteById,\n RoutePaths,\n RoutesById,\n RoutesByPath,\n} from './routeInfo'\nimport type {\n AnyRouteMatch,\n MakeRouteMatch,\n MakeRouteMatchUnion,\n MatchRouteOptions,\n} from './Matches'\nimport type {\n BuildLocationFn,\n CommitLocationOptions,\n NavigateFn,\n} from './RouterProvider'\nimport type { Manifest, ManifestRouteAssets } from './manifest'\nimport type { AnySchema, AnyValidator } from './validators'\nimport type { NavigateOptions, ResolveRelativePath, ToOptions } from './link'\nimport type {\n AnySerializationAdapter,\n ValidateSerializableInput,\n} from './ssr/serializer/transformer'\nimport type {\n HydrationScriptOutput,\n InitialHydrationScriptTags,\n} from './ssr/hydrationScripts'\nimport type { GetStoreConfig, RouterStores } from './stores'\n\nfunction isExternalUrl(url: URL, origin: string) {\n return (\n (url.protocol !== 'http:' && url.protocol !== 'https:') ||\n url.origin !== origin ||\n !!url.username ||\n !!url.password\n )\n}\n\nfunction getUrlPath(url: URL) {\n return url.pathname + url.search + url.hash\n}\n\nexport type ControllablePromise<T = any> = Promise<T> & {\n resolve: (value: T) => void\n reject: (value?: any) => void\n}\n\nexport interface Register {\n // Lots of things on here like...\n // router\n // config\n // ssr\n}\n\nexport type RegisteredSsr<TRegister = Register> = TRegister extends {\n ssr: infer TSSR\n}\n ? TSSR\n : false\n\nexport type RegisteredRouter<TRegister = Register> = TRegister extends {\n router: infer TRouter\n}\n ? TRouter\n : AnyRouter\n\nexport type RegisteredConfigType<TRegister, TKey> = TRegister extends {\n config: infer TConfig\n}\n ? TConfig extends {\n '~types': infer TTypes\n }\n ? TKey extends keyof TTypes\n ? TTypes[TKey]\n : unknown\n : unknown\n : unknown\n\nexport type DefaultRemountDepsFn<TRouteTree extends AnyRoute> = (\n opts: MakeRemountDepsOptionsUnion<TRouteTree>,\n) => any\n\nexport interface DefaultRouterOptionsExtensions {}\n\nexport interface RouterOptionsExtensions extends DefaultRouterOptionsExtensions {}\n\nexport type SSROption = boolean | 'data-only'\n\nexport interface RouterOptions<\n TRouteTree extends AnyRoute,\n TTrailingSlashOption extends TrailingSlashOption,\n TDefaultStructuralSharingOption extends boolean = false,\n TRouterHistory extends RouterHistory = RouterHistory,\n TDehydrated = undefined,\n> extends RouterOptionsExtensions {\n /**\n * The historLine truncated
|
||||
+789
@@ -0,0 +1,789 @@
|
||||
import { SieveCache } from './sieve-cache.cjs';
|
||||
import { ProcessRouteTreeResult, ProcessedTree } from './new-process-route-tree.cjs';
|
||||
import { SearchParser, SearchSerializer } from './searchParams.cjs';
|
||||
import { AnyRedirect, ResolvedRedirect } from './redirect.cjs';
|
||||
import { LoadTransaction, LoaderFlight, PendingSession } from './load-client.cjs';
|
||||
import { ServerLoadResult } from './load-server.cjs';
|
||||
import { HistoryAction, HistoryLocation, HistoryState, ParsedHistoryState, RouterHistory } from '@tanstack/history';
|
||||
import { Awaitable, Constrain, NoInfer, NonNullableUpdater, PickAsRequired, Updater } from './utils.cjs';
|
||||
import { ParsedLocation } from './location.cjs';
|
||||
import { AnyContext, AnyRoute, AnyRouteWithContext, LoaderStaleReloadMode, MakeRemountDepsOptionsUnion, RouteMask } from './route.cjs';
|
||||
import { FullSearchSchema, RouteById, RoutePaths, RoutesById, RoutesByPath } from './routeInfo.cjs';
|
||||
import { AnyRouteMatch, MakeRouteMatchUnion, MatchRouteOptions } from './Matches.cjs';
|
||||
import { BuildLocationFn, CommitLocationOptions, NavigateFn } from './RouterProvider.cjs';
|
||||
import { Manifest, ManifestRouteAssets } from './manifest.cjs';
|
||||
import { AnySchema } from './validators.cjs';
|
||||
import { NavigateOptions, ResolveRelativePath, ToOptions } from './link.cjs';
|
||||
import { AnySerializationAdapter, ValidateSerializableInput } from './ssr/serializer/transformer.cjs';
|
||||
import { InitialHydrationScriptTags } from './ssr/hydrationScripts.cjs';
|
||||
import { GetStoreConfig, RouterStores } from './stores.cjs';
|
||||
export type ControllablePromise<T = any> = Promise<T> & {
|
||||
resolve: (value: T) => void;
|
||||
reject: (value?: any) => void;
|
||||
};
|
||||
export interface Register {
|
||||
}
|
||||
export type RegisteredSsr<TRegister = Register> = TRegister extends {
|
||||
ssr: infer TSSR;
|
||||
} ? TSSR : false;
|
||||
export type RegisteredRouter<TRegister = Register> = TRegister extends {
|
||||
router: infer TRouter;
|
||||
} ? TRouter : AnyRouter;
|
||||
export type RegisteredConfigType<TRegister, TKey> = TRegister extends {
|
||||
config: infer TConfig;
|
||||
} ? TConfig extends {
|
||||
'~types': infer TTypes;
|
||||
} ? TKey extends keyof TTypes ? TTypes[TKey] : unknown : unknown : unknown;
|
||||
export type DefaultRemountDepsFn<TRouteTree extends AnyRoute> = (opts: MakeRemountDepsOptionsUnion<TRouteTree>) => any;
|
||||
export interface DefaultRouterOptionsExtensions {
|
||||
}
|
||||
export interface RouterOptionsExtensions extends DefaultRouterOptionsExtensions {
|
||||
}
|
||||
export type SSROption = boolean | 'data-only';
|
||||
export interface RouterOptions<TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption, TDefaultStructuralSharingOption extends boolean = false, TRouterHistory extends RouterHistory = RouterHistory, TDehydrated = undefined> extends RouterOptionsExtensions {
|
||||
/**
|
||||
* The history object that will be used to manage the browser history.
|
||||
*
|
||||
* If not provided, a new createBrowserHistory instance will be created and used.
|
||||
*
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#history-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/history-types)
|
||||
*/
|
||||
history?: TRouterHistory;
|
||||
/**
|
||||
* A function that will be used to stringify search params when generating links.
|
||||
*
|
||||
* @default defaultStringifySearch
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#stringifysearch-method)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization)
|
||||
*/
|
||||
stringifySearch?: SearchSerializer;
|
||||
/**
|
||||
* A function that will be used to parse search params when parsing the current location.
|
||||
*
|
||||
* @default defaultParseSearch
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#parsesearch-method)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization)
|
||||
*/
|
||||
parseSearch?: SearchParser;
|
||||
/**
|
||||
* If `false`, routes will not be preloaded by default in any way.
|
||||
*
|
||||
* If `'intent'`, routes will be preloaded by default when the user hovers over a link or a `touchstart` event is detected on a `<Link>`.
|
||||
*
|
||||
* If `'viewport'`, routes will be preloaded by default when they are within the viewport.
|
||||
*
|
||||
* @default false
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreload-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/preloading)
|
||||
*/
|
||||
defaultPreload?: false | 'intent' | 'viewport' | 'render';
|
||||
/**
|
||||
* The delay in milliseconds before intent focus/hover and viewport preloading.
|
||||
* Touch intent preloads immediately.
|
||||
*
|
||||
* @default 50
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreloaddelay-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/preloading#preload-delay)
|
||||
*/
|
||||
defaultPreloadDelay?: number;
|
||||
/**
|
||||
* The default `preloadIntentProximity` a route should use if no preloadIntentProximity is provided.
|
||||
*
|
||||
* @default 0
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreloadintentproximity-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/preloading#preload-intent-proximity)
|
||||
*/
|
||||
defaultPreloadIntentProximity?: number;
|
||||
/**
|
||||
* The default `pendingMs` a route should use if no pendingMs is provided.
|
||||
*
|
||||
* @default 1000
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpendingms-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#avoiding-pending-component-flash)
|
||||
*/
|
||||
defaultPendingMs?: number;
|
||||
/**
|
||||
* The default `pendingMinMs` a route should use if no pendingMinMs is provided.
|
||||
*
|
||||
* @default 500
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpendingminms-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#avoiding-pending-component-flash)
|
||||
*/
|
||||
defaultPendingMinMs?: number;
|
||||
/**
|
||||
* The default `staleTime` a route should use if no staleTime is provided. This is the time in milliseconds that a route will be considered fresh.
|
||||
*
|
||||
* @default 0
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultstaletime-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#key-options)
|
||||
*/
|
||||
defaultStaleTime?: number;
|
||||
/**
|
||||
* The default stale reload mode a route loader should use if no `loader.staleReloadMode` is provided.
|
||||
*
|
||||
* `'background'` preserves the current stale-while-revalidate behavior.
|
||||
* `'blocking'` waits for stale loader reloads to complete before resolving navigation.
|
||||
*
|
||||
* @default 'background'
|
||||
*/
|
||||
defaultStaleReloadMode?: LoaderStaleReloadMode;
|
||||
/**
|
||||
* The default `preloadStaleTime` a route should use if no preloadStaleTime is provided.
|
||||
*
|
||||
* @default 30_000 `(30 seconds)`
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreloadstaletime-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/preloading)
|
||||
*/
|
||||
defaultPreloadStaleTime?: number;
|
||||
/**
|
||||
* The default `preloadGcTime` a route should use if none is provided.
|
||||
*
|
||||
* @default 300_000 `(5 minutes)`
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultpreloadgctime-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/preloading)
|
||||
*/
|
||||
defaultPreloadGcTime?: number;
|
||||
/**
|
||||
* If `true`, route navigations will called using `document.startViewTransition()`.
|
||||
*
|
||||
* If the browser does not support this api, this option will be ignored.
|
||||
*
|
||||
* See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) for more information on how this function works.
|
||||
*
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultviewtransition-property)
|
||||
*/
|
||||
defaultViewTransition?: boolean | ViewTransitionOptions;
|
||||
/**
|
||||
* The default `hashScrollIntoView` a route should use if no hashScrollIntoView is provided while navigating
|
||||
*
|
||||
* See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) for more information on `ScrollIntoViewOptions`.
|
||||
*
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaulthashscrollintoview-property)
|
||||
*/
|
||||
defaultHashScrollIntoView?: boolean | ScrollIntoViewOptions;
|
||||
/**
|
||||
* @default 'fuzzy'
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#notfoundmode-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/not-found-errors#the-notfoundmode-option)
|
||||
*/
|
||||
notFoundMode?: 'root' | 'fuzzy';
|
||||
/**
|
||||
* The default `gcTime` a route should use if no gcTime is provided.
|
||||
*
|
||||
* @default 300_000 `(5 minutes)`
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultgctime-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/data-loading#key-options)
|
||||
*/
|
||||
defaultGcTime?: number;
|
||||
/**
|
||||
* If `true`, all routes will be matched as case-sensitive.
|
||||
*
|
||||
* @default false
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#casesensitive-property)
|
||||
*/
|
||||
caseSensitive?: boolean;
|
||||
/**
|
||||
*
|
||||
* The route tree that will be used to configure the router instance.
|
||||
*
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#routetree-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/routing/route-trees)
|
||||
*/
|
||||
routeTree?: TRouteTree;
|
||||
/**
|
||||
* The basepath for then entire router. This is useful for mounting a router instance at a subpath.
|
||||
* ```
|
||||
* @default '/'
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#basepath-property)
|
||||
*/
|
||||
basepath?: string;
|
||||
/**
|
||||
* The root context that will be provided to all routes in the route tree.
|
||||
*
|
||||
* This can be used to provide a context to all routes in the tree without having to provide it to each route individually.
|
||||
*
|
||||
* Optional or required if the root route was created with [`createRootRouteWithContext()`](https://tanstack.com/router/latest/docs/framework/react/api/router/createRootRouteWithContextFunction).
|
||||
*
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#context-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/router-context)
|
||||
*/
|
||||
context?: InferRouterContext<TRouteTree>;
|
||||
additionalContext?: any;
|
||||
/**
|
||||
* A function that will be called when the router is dehydrated.
|
||||
*
|
||||
* The return value of this function will be serialized and stored in the router's dehydrated state.
|
||||
*
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#dehydrate-method)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/external-data-loading#critical-dehydrationhydration)
|
||||
*/
|
||||
dehydrate?: () => Awaitable<Constrain<TDehydrated, ValidateSerializableInput<Register, TDehydrated>>>;
|
||||
/**
|
||||
* A function that will be called when the router is hydrated.
|
||||
*
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#hydrate-method)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/external-data-loading#critical-dehydrationhydration)
|
||||
*/
|
||||
hydrate?: (dehydrated: TDehydrated) => Awaitable<void>;
|
||||
/**
|
||||
* An array of route masks that will be used to mask routes in the route tree.
|
||||
*
|
||||
* Route masking is when you display a route at a different path than the one it is configured to match, like a modal popup that when shared will unmask to the modal's content instead of the modal's context.
|
||||
*
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#routemasks-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/route-masking)
|
||||
*/
|
||||
routeMasks?: Array<RouteMask<TRouteTree>>;
|
||||
/**
|
||||
* If `true`, route masks will, by default, be removed when the page is reloaded.
|
||||
*
|
||||
* This can be overridden on a per-mask basis by setting the `unmaskOnReload` option on the mask, or on a per-navigation basis by setting the `unmaskOnReload` option in the `Navigate` options.
|
||||
*
|
||||
* @default false
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#unmaskonreload-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/route-masking#unmasking-on-page-reload)
|
||||
*/
|
||||
unmaskOnReload?: boolean;
|
||||
/**
|
||||
* Use `notFoundComponent` instead.
|
||||
*
|
||||
* @deprecated
|
||||
* See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#notfoundroute-property)
|
||||
*/
|
||||
notFoundRoute?: AnyRoute;
|
||||
/**
|
||||
* Configures how trailing slashes are treated.
|
||||
*
|
||||
* - `'always'` will add a trailing slash if not present
|
||||
* - `'never'` will remove the trailing slash if present
|
||||
* - `'preserve'` will not modify the trailing slash.
|
||||
*
|
||||
* @default 'never'
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#trailingslash-property)
|
||||
*/
|
||||
trailingSlash?: TTrailingSlashOption;
|
||||
/**
|
||||
* While usually automatic, sometimes it can be useful to force the router into a server-side state, e.g. when using the router in a non-browser environment that has access to a global.document object.
|
||||
*
|
||||
* @default typeof document !== 'undefined'
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#isserver-property)
|
||||
*/
|
||||
isServer?: boolean;
|
||||
/**
|
||||
* @default false
|
||||
*/
|
||||
isShell?: boolean;
|
||||
/**
|
||||
* @default false
|
||||
*/
|
||||
isPrerendering?: boolean;
|
||||
/**
|
||||
* The default `ssr` a route should use if no `ssr` is provided.
|
||||
*
|
||||
* @default true
|
||||
*/
|
||||
defaultSsr?: SSROption;
|
||||
search?: {
|
||||
/**
|
||||
* Configures how unknown search params (= not returned by any `validateSearch`) are treated.
|
||||
*
|
||||
* @default false
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#search.strict-property)
|
||||
*/
|
||||
strict?: boolean;
|
||||
};
|
||||
/**
|
||||
* Configures whether structural sharing is enabled by default for fine-grained selectors.
|
||||
*
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#defaultstructuralsharing-property)
|
||||
*/
|
||||
defaultStructuralSharing?: TDefaultStructuralSharingOption;
|
||||
/**
|
||||
* Configures which URI characters are allowed in path params that would ordinarily be escaped by encodeURIComponent.
|
||||
* This is read only during initialization. Create a new router to change it.
|
||||
*
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#pathparamsallowedcharacters-property)
|
||||
* @link [Guide](https://tanstack.com/router/latest/docs/framework/react/guide/path-params#allowed-characters)
|
||||
*/
|
||||
readonly pathParamsAllowedCharacters?: ReadonlyArray<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>;
|
||||
defaultRemountDeps?: DefaultRemountDepsFn<TRouteTree>;
|
||||
/**
|
||||
* If `true`, scroll restoration will be enabled
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
scrollRestoration?: boolean | ((opts: {
|
||||
location: ParsedLocation;
|
||||
}) => boolean);
|
||||
/**
|
||||
* A function that will be called to get the key for the scroll restoration cache.
|
||||
*
|
||||
* @default (location) => location.href
|
||||
*/
|
||||
getScrollRestorationKey?: (location: ParsedLocation) => string;
|
||||
/**
|
||||
* The default behavior for scroll restoration.
|
||||
*
|
||||
* @default 'auto'
|
||||
*/
|
||||
scrollRestorationBehavior?: ScrollBehavior;
|
||||
/**
|
||||
* An array of selectors that will be used to scroll to the top of the page in addition to `window`
|
||||
*
|
||||
* @default ['window']
|
||||
*/
|
||||
scrollToTopSelectors?: Array<string | (() => Element | null | undefined)>;
|
||||
/**
|
||||
* When `true`, disables the global catch boundary that normally wraps all route matches.
|
||||
* This allows unhandled errors to bubble up to top-level error handlers in the browser.
|
||||
*
|
||||
* Useful for testing tools (like Storybook Test Runner), error reporting services,
|
||||
* and debugging scenarios where you want errors to reach the browser's global error handlers.
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
disableGlobalCatchBoundary?: boolean;
|
||||
/**
|
||||
* An array of URL protocols to allow in links, redirects, and navigation.
|
||||
* Absolute URLs with protocols not in this list will be rejected.
|
||||
*
|
||||
* @default DEFAULT_PROTOCOL_ALLOWLIST (http:, https:, mailto:, tel:)
|
||||
* @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RouterOptionsType#protocolallowlist-property)
|
||||
*/
|
||||
protocolAllowlist?: Array<string>;
|
||||
serializationAdapters?: ReadonlyArray<AnySerializationAdapter>;
|
||||
/**
|
||||
* Configures how the router will rewrite the location between the actual href and the internal href of the router.
|
||||
*
|
||||
* @default undefined
|
||||
* @description You can provide a custom rewrite pair (in/out).
|
||||
* This is useful for shifting data from the origin to the path (for things like subdomain routing), or other advanced use cases.
|
||||
*/
|
||||
rewrite?: LocationRewrite;
|
||||
/**
|
||||
* The origin used to resolve URLs. Pass a normalized origin, such as
|
||||
* `https://example.com` or `http://localhost:3000`, without a path or trailing slash.
|
||||
* Defaults to the browser origin, or `http://localhost` on the server.
|
||||
*/
|
||||
origin?: string;
|
||||
ssr?: {
|
||||
nonce?: string;
|
||||
};
|
||||
}
|
||||
export type LocationRewrite = {
|
||||
/**
|
||||
* A function that will be called to rewrite the URL before it is interpreted by the router from the history instance.
|
||||
*
|
||||
* @default undefined
|
||||
*/
|
||||
input?: LocationRewriteFunction;
|
||||
/**
|
||||
* A function that will be called to rewrite the URL before it is committed to the actual history instance from the router.
|
||||
*
|
||||
* @default undefined
|
||||
*/
|
||||
output?: LocationRewriteFunction;
|
||||
};
|
||||
/**
|
||||
* A function that will be called to rewrite the URL.
|
||||
*
|
||||
* @param url The URL to rewrite.
|
||||
* @returns The rewritten URL (as a URL instance or full href string) or undefined if no rewrite is needed.
|
||||
*/
|
||||
export type LocationRewriteFunction = ({ url, }: {
|
||||
url: URL;
|
||||
}) => undefined | string | URL;
|
||||
export interface RouterState<in out TRouteTree extends AnyRoute = AnyRoute, in out TRouteMatch = MakeRouteMatchUnion> {
|
||||
status: 'pending' | 'idle';
|
||||
isLoading: boolean;
|
||||
matches: Array<TRouteMatch>;
|
||||
location: ParsedLocation<FullSearchSchema<TRouteTree>>;
|
||||
resolvedLocation?: ParsedLocation<FullSearchSchema<TRouteTree>>;
|
||||
}
|
||||
export interface BuildNextOptions {
|
||||
to?: string | number | null;
|
||||
params?: true | Updater<unknown>;
|
||||
search?: true | Updater<unknown>;
|
||||
hash?: true | Updater<string>;
|
||||
state?: true | NonNullableUpdater<ParsedHistoryState, HistoryState>;
|
||||
mask?: {
|
||||
to?: string | number | null;
|
||||
params?: true | Updater<unknown>;
|
||||
search?: true | Updater<unknown>;
|
||||
hash?: true | Updater<string>;
|
||||
state?: true | NonNullableUpdater<ParsedHistoryState, HistoryState>;
|
||||
unmaskOnReload?: boolean;
|
||||
};
|
||||
from?: string;
|
||||
href?: string;
|
||||
_fromLocation?: ParsedLocation;
|
||||
unsafeRelative?: 'path';
|
||||
_isNavigate?: boolean;
|
||||
}
|
||||
type NavigationEventInfo = {
|
||||
fromLocation?: ParsedLocation;
|
||||
toLocation: ParsedLocation;
|
||||
pathChanged: boolean;
|
||||
hrefChanged: boolean;
|
||||
hashChanged: boolean;
|
||||
};
|
||||
export interface RouterEvents {
|
||||
onBeforeNavigate: {
|
||||
type: 'onBeforeNavigate';
|
||||
} & NavigationEventInfo;
|
||||
onBeforeLoad: {
|
||||
type: 'onBeforeLoad';
|
||||
} & NavigationEventInfo;
|
||||
onLoad: {
|
||||
type: 'onLoad';
|
||||
} & NavigationEventInfo;
|
||||
onResolved: {
|
||||
type: 'onResolved';
|
||||
} & NavigationEventInfo;
|
||||
onBeforeRouteMount: {
|
||||
type: 'onBeforeRouteMount';
|
||||
} & NavigationEventInfo;
|
||||
onRendered: {
|
||||
type: 'onRendered';
|
||||
} & NavigationEventInfo;
|
||||
}
|
||||
export type RouterEvent = RouterEvents[keyof RouterEvents];
|
||||
export type ListenerFn<TEvent extends RouterEvent> = (event: TEvent) => void;
|
||||
export type RouterListener<TRouterEvent extends RouterEvent> = {
|
||||
eventType: TRouterEvent['type'];
|
||||
fn: ListenerFn<TRouterEvent>;
|
||||
};
|
||||
export type SubscribeFn = <TType extends keyof RouterEvents>(eventType: TType, fn: ListenerFn<RouterEvents[TType]>) => () => void;
|
||||
export interface MatchRoutesOpts {
|
||||
throwOnError?: boolean;
|
||||
}
|
||||
export type InferRouterContext<TRouteTree extends AnyRoute> = TRouteTree['types']['routerContext'];
|
||||
export type RouterContextOptions<TRouteTree extends AnyRoute> = AnyContext extends InferRouterContext<TRouteTree> ? {
|
||||
context?: InferRouterContext<TRouteTree>;
|
||||
} : {
|
||||
context: InferRouterContext<TRouteTree>;
|
||||
};
|
||||
export type RouterConstructorOptions<TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption, TDefaultStructuralSharingOption extends boolean, TRouterHistory extends RouterHistory, TDehydrated extends Record<string, any>> = Omit<RouterOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>, 'context' | 'serializationAdapters' | 'defaultSsr'> & RouterContextOptions<TRouteTree>;
|
||||
export type PreloadRouteFn<TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption, TDefaultStructuralSharingOption extends boolean, TRouterHistory extends RouterHistory, TDehydrated extends Record<string, any> = Record<string, any>> = <TFrom extends RoutePaths<TRouteTree> | string = string, TTo extends string | undefined = undefined, TMaskFrom extends RoutePaths<TRouteTree> | string = TFrom, TMaskTo extends string = ''>(opts: NavigateOptions<RouterCore<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>, TFrom, TTo, TMaskFrom, TMaskTo>) => Promise<Array<AnyRouteMatch> | undefined>;
|
||||
export type MatchRouteFn<TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption, TDefaultStructuralSharingOption extends boolean, TRouterHistory extends RouterHistory> = <TFrom extends RoutePaths<TRouteTree> = '/', TTo extends string | undefined = undefined, TResolved = ResolveRelativePath<TFrom, NoInfer<TTo>>>(location: ToOptions<RouterCore<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory>, TFrom, TTo>, opts?: MatchRouteOptions) => false | RouteById<TRouteTree, TResolved>['types']['allParams'];
|
||||
export type UpdateFn<TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption, TDefaultStructuralSharingOption extends boolean, TRouterHistory extends RouterHistory, TDehydrated extends Record<string, any>> = (newOptions: Omit<RouterConstructorOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>, 'pathParamsAllowedCharacters'>) => void;
|
||||
export type InvalidateFn<TRouter extends AnyRouter> = (opts?: {
|
||||
filter?: (d: MakeRouteMatchUnion<TRouter>) => boolean;
|
||||
sync?: boolean;
|
||||
forcePending?: boolean;
|
||||
}) => Promise<void>;
|
||||
export type ParseLocationFn<TRouteTree extends AnyRoute> = (locationToParse: HistoryLocation, previousLocation?: ParsedLocation<FullSearchSchema<TRouteTree>>) => ParsedLocation<FullSearchSchema<TRouteTree>>;
|
||||
export type GetMatchRoutesFn = (pathname: string) => [
|
||||
matchedRoutes: ReadonlyArray<AnyRoute>,
|
||||
/** exhaustive params, still in their string form */
|
||||
rawParams: Record<string, string>,
|
||||
foundRoute: AnyRoute | undefined
|
||||
];
|
||||
export type EmitFn = (routerEvent: RouterEvent) => void;
|
||||
export type LoadFn = (opts?: {
|
||||
sync?: boolean;
|
||||
action?: {
|
||||
type: HistoryAction;
|
||||
};
|
||||
_signal?: AbortSignal;
|
||||
}) => Promise<void>;
|
||||
export type CommitLocationFn = ({ viewTransition, ignoreBlocker, ...next }: ParsedLocation & CommitLocationOptions) => Promise<void>;
|
||||
export type StartTransitionFn = (fn: () => void, expected: Array<AnyRouteMatch>) => Promise<boolean>;
|
||||
export interface MatchRoutesFn {
|
||||
(pathname: string, locationSearch?: AnySchema, opts?: MatchRoutesOpts): Array<MakeRouteMatchUnion>;
|
||||
/**
|
||||
* @deprecated use the following signature instead
|
||||
*/
|
||||
(next: ParsedLocation, opts?: MatchRoutesOpts): Array<AnyRouteMatch>;
|
||||
(pathnameOrNext: string | ParsedLocation, locationSearchOrOpts?: AnySchema | MatchRoutesOpts, opts?: MatchRoutesOpts): Array<AnyRouteMatch>;
|
||||
}
|
||||
export type LoadRouteChunkFn = (route: AnyRoute) => Promise<Array<void>>;
|
||||
export type ResolveRedirect = (err: AnyRedirect) => ResolvedRedirect;
|
||||
export type ClearCacheFn<TRouter extends AnyRouter> = (opts?: {
|
||||
filter?: (d: MakeRouteMatchUnion<TRouter>) => boolean;
|
||||
}) => void;
|
||||
/**
|
||||
* Server-side SSR request contract.
|
||||
*
|
||||
* Tiering rule: the flat methods are the adapter/framework contract;
|
||||
* `hydrationScripts` is transport for the core SSR stream merger only.
|
||||
* New members must land on the matching tier.
|
||||
*/
|
||||
export interface ServerSsr {
|
||||
/** Framework-only. */
|
||||
onRenderFinished: (listener: () => void) => void;
|
||||
/** Framework-only. */
|
||||
setRenderFinished: () => void;
|
||||
/** Framework-only. */
|
||||
cleanup: () => void;
|
||||
/**
|
||||
* Register a listener invoked when the SSR request lifecycle ends (success,
|
||||
* error, abort, or stream lifetime expiry). Use to tear down per-request
|
||||
* resources whose references would otherwise pin the router (e.g. query
|
||||
* cache subscriptions, gcTime timers, abort controllers).
|
||||
*
|
||||
* `settled` is true when every value the router dehydrated has settled, so
|
||||
* no loader work can still be pending. It is false when the response ended
|
||||
* early (abort, cancellation, timeout) or never consumed the loader data.
|
||||
*
|
||||
* Listeners run synchronously and exactly once. Errors are caught and logged.
|
||||
* A listener registered after cleanup already ran is invoked immediately.
|
||||
*/
|
||||
onCleanup: (listener: (settled: boolean) => void) => void;
|
||||
/** Framework-only. */
|
||||
dehydrate: (opts?: {
|
||||
requestAssets?: ManifestRouteAssets;
|
||||
signal?: AbortSignal;
|
||||
}) => Promise<void>;
|
||||
/**
|
||||
* Framework-only: opt this request out of hydration output entirely (for
|
||||
* example a `hydrate: false` page). Call instead of `dehydrate()`, before
|
||||
* rendering starts. No hydration scripts are emitted, `<Scripts>` renders
|
||||
* no boundary, and the response takes the pass-through stream path.
|
||||
*/
|
||||
disableHydration: () => void;
|
||||
/** Framework-only. */
|
||||
takeInitialHydrationScriptTags: () => InitialHydrationScriptTags | undefined;
|
||||
}
|
||||
export interface RouterSsrLifecycle {
|
||||
onServerSsrAttach?: Array<(serverSsr: ServerSsr) => void>;
|
||||
}
|
||||
export type AnyRouterWithContext<TContext> = RouterCore<AnyRouteWithContext<TContext>, any, any, any, any>;
|
||||
export type AnyRouter = RouterCore<any, any, any, any, any>;
|
||||
export interface ViewTransitionOptions {
|
||||
types: Array<string> | ((locationChangeInfo: {
|
||||
fromLocation?: ParsedLocation;
|
||||
toLocation: ParsedLocation;
|
||||
pathChanged: boolean;
|
||||
hrefChanged: boolean;
|
||||
hashChanged: boolean;
|
||||
}) => Array<string> | false);
|
||||
}
|
||||
/**
|
||||
* Convert an unknown error into a minimal, serializable object.
|
||||
* Includes name and message (and stack in development).
|
||||
*/
|
||||
export declare function defaultSerializeError(err: unknown): {
|
||||
name: string;
|
||||
message: string;
|
||||
} | {
|
||||
data: unknown;
|
||||
};
|
||||
/** Options for configuring trailing-slash behavior. */
|
||||
export declare const trailingSlashOptions: {
|
||||
readonly always: "always";
|
||||
readonly never: "never";
|
||||
readonly preserve: "preserve";
|
||||
};
|
||||
export type TrailingSlashOption = (typeof trailingSlashOptions)[keyof typeof trailingSlashOptions];
|
||||
/**
|
||||
* Compute whether path, href or hash changed between previous and current
|
||||
* resolved locations.
|
||||
*/
|
||||
export declare function getLocationChangeInfo(location: ParsedLocation, resolvedLocation?: ParsedLocation): {
|
||||
fromLocation: ParsedLocation<{}> | undefined;
|
||||
toLocation: ParsedLocation<{}>;
|
||||
pathChanged: boolean;
|
||||
hrefChanged: boolean;
|
||||
hashChanged: boolean;
|
||||
};
|
||||
/**
|
||||
* Return only state owned by the application, excluding volatile history
|
||||
* bookkeeping. Mask payloads (`__tempLocation`/`__tempKey`) are kept: they
|
||||
* distinguish otherwise-identical locations.
|
||||
*/
|
||||
export declare function _getUserHistoryState({ key: _key, __TSR_key: _tsrKey, __TSR_index: _tsrIndex, __hashScrollIntoViewOptions: _hashScroll, ...state }: ParsedHistoryState): HistoryState;
|
||||
export declare function lifecycleEnd(matches: Array<AnyRouteMatch>): number;
|
||||
/** Run route lifecycle callbacks in leave/enter/stay phases. */
|
||||
export declare function runRouteLifecycle(router: AnyRouter, previous: Array<AnyRouteMatch>, matches: Array<AnyRouteMatch>, previousEnd: number | undefined, nextEnd: number, owner?: LoadTransaction): void;
|
||||
/** Indexes and caches rebuilt together when the route tree changes. */
|
||||
type RouteTreeCaches<TRouteTree extends AnyRoute> = ProcessRouteTreeResult<TRouteTree> & {
|
||||
resolvePathCache: SieveCache<string, string>;
|
||||
};
|
||||
export type CreateRouterFn = <TRouteTree extends AnyRoute, TTrailingSlashOption extends TrailingSlashOption = 'never', TDefaultStructuralSharingOption extends boolean = false, TRouterHistory extends RouterHistory = RouterHistory, TDehydrated extends Record<string, any> = Record<string, any>>(options: undefined extends number ? 'strictNullChecks must be enabled in tsconfig.json' : RouterConstructorOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>) => RouterCore<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>;
|
||||
declare global {
|
||||
var __TSR_CACHE__: {
|
||||
routeTree: AnyRoute;
|
||||
caseSensitive: boolean | undefined;
|
||||
processRouteTreeResult: RouteTreeCaches<AnyRoute>;
|
||||
} | undefined;
|
||||
}
|
||||
export interface RouterCore<in out TRouteTree extends AnyRoute, in out TTrailingSlashOption extends TrailingSlashOption, in out TDefaultStructuralSharingOption extends boolean, in out TRouterHistory extends RouterHistory = RouterHistory, in out TDehydrated extends Record<string, any> = Record<string, any>> {
|
||||
shouldViewTransition?: boolean | ViewTransitionOptions;
|
||||
/**
|
||||
* Foreground lifecycle boundary survives invalidation/background statuses.
|
||||
* Zero or undefined means the whole branch participates.
|
||||
*/
|
||||
_lifecycleEnd?: number;
|
||||
/** Current client load transaction and owner of navigation writes. */
|
||||
_tx?: LoadTransaction;
|
||||
/** Joinable in-flight loader generations keyed by match ID. */
|
||||
_flights?: Map<string, LoaderFlight>;
|
||||
/** Active speculative lanes retained for cancellation, invalidation, and cache clearing. */
|
||||
_preloads?: Map<AbortController, Array<AnyRouteMatch>>;
|
||||
/** Owns cancellable work before a client transaction publishes. */
|
||||
_preflight?: AbortController;
|
||||
/** Transfers one reconstructed SSR prefix into its initial client load. */
|
||||
_handoff?: HydrationHandoff;
|
||||
/** Pending-boundary reveal and minimum-visible timing state. */
|
||||
_pending?: PendingSession;
|
||||
/** Result of the latest server load, used to render or redirect. */
|
||||
_serverResult?: ServerLoadResult;
|
||||
/** Framework publication waiting for an exact render acknowledgement. */
|
||||
_rendered?: [
|
||||
offered?: Array<AnyRouteMatch>,
|
||||
settle?: (rendered: boolean) => void
|
||||
];
|
||||
/** Development-only HMR reload for a route and its descendants. */
|
||||
_refreshRoute: (() => Promise<void>) | undefined;
|
||||
/** Development-only replacement for a route's lazy chunk owner. */
|
||||
_replaceRouteChunk: ((route: AnyRoute, lazyFn: AnyRoute['lazyFn']) => void) | undefined;
|
||||
}
|
||||
export type HydrationHandoff = [
|
||||
claim: () => AbortController | undefined,
|
||||
finish: (matches?: Array<AnyRouteMatch>) => number | undefined
|
||||
];
|
||||
/**
|
||||
* Core, framework-agnostic router engine that powers TanStack Router.
|
||||
*
|
||||
* Provides navigation, matching, loading, preloading, caching and event APIs
|
||||
* used by framework adapters (React/Solid). Prefer framework helpers like
|
||||
* `createRouter` in app code.
|
||||
*
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/RouterType
|
||||
*/
|
||||
export declare class RouterCore<in out TRouteTree extends AnyRoute, in out TTrailingSlashOption extends TrailingSlashOption, in out TDefaultStructuralSharingOption extends boolean, in out TRouterHistory extends RouterHistory = RouterHistory, in out TDehydrated extends Record<string, any> = Record<string, any>> {
|
||||
tempLocationKey: string | undefined;
|
||||
_scroll: {
|
||||
next: boolean;
|
||||
hash?: boolean;
|
||||
restoring?: boolean;
|
||||
restoration?: boolean;
|
||||
reset?: boolean;
|
||||
};
|
||||
subscribers: Set<RouterListener<RouterEvent>>;
|
||||
/** Accepted off-screen loader generations keyed by match ID. */
|
||||
_cache: Map<string, AnyRouteMatch>;
|
||||
/** Accepted semantic lane, excluding temporary pending presentation. */
|
||||
_committed: Array<AnyRouteMatch>;
|
||||
stores: RouterStores<TRouteTree>;
|
||||
private getStoreConfig;
|
||||
batch: (fn: () => void) => void;
|
||||
options: PickAsRequired<RouterOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>, 'stringifySearch' | 'parseSearch' | 'context'>;
|
||||
history: TRouterHistory;
|
||||
rewrite?: LocationRewrite;
|
||||
origin: string;
|
||||
latestLocation: ParsedLocation<FullSearchSchema<TRouteTree>>;
|
||||
_pendingLocation?: ParsedLocation<FullSearchSchema<TRouteTree>>;
|
||||
basepath: string;
|
||||
routeTree: TRouteTree;
|
||||
routesById: RoutesById<TRouteTree>;
|
||||
routesByPath: RoutesByPath<TRouteTree>;
|
||||
processedTree: ProcessedTree<TRouteTree, any, any>;
|
||||
resolvePathCache: SieveCache<string, string>;
|
||||
private lightweightCache;
|
||||
private staticLocations;
|
||||
isServer: boolean;
|
||||
readonly pathParamsDecoder?: (encoded: string) => string;
|
||||
protocolAllowlist: Set<string>;
|
||||
/**
|
||||
* @deprecated Use the `createRouter` function instead
|
||||
*/
|
||||
constructor(options: RouterConstructorOptions<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>, getStoreConfig: GetStoreConfig);
|
||||
startTransition: StartTransitionFn;
|
||||
isShell(): boolean;
|
||||
update: UpdateFn<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>;
|
||||
get state(): RouterState<TRouteTree>;
|
||||
updateLatestLocation: () => void;
|
||||
buildRouteTree: () => RouteTreeCaches<TRouteTree>;
|
||||
setRoutes(caches: RouteTreeCaches<TRouteTree>): void;
|
||||
/**
|
||||
* Subscribe to router lifecycle events like `onBeforeNavigate`, `onLoad`,
|
||||
* `onResolved`, etc. Returns an unsubscribe function.
|
||||
*
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/RouterEventsType
|
||||
*/
|
||||
subscribe: SubscribeFn;
|
||||
emit: EmitFn;
|
||||
/**
|
||||
* Parse a HistoryLocation into a strongly-typed ParsedLocation using the
|
||||
* current router options, rewrite rules and search parser/stringifier.
|
||||
*/
|
||||
parseLocation: ParseLocationFn<TRouteTree>;
|
||||
matchRoutes: MatchRoutesFn;
|
||||
private matchRoutesInternal;
|
||||
getMatchedRoutes: GetMatchRoutesFn;
|
||||
/**
|
||||
* Lightweight route matching for buildLocation.
|
||||
* Only computes fullPath, accumulated search, and params - skipping expensive
|
||||
* operations like AbortController, loaderDeps, and full match objects.
|
||||
*/
|
||||
private matchRoutesLightweight;
|
||||
/**
|
||||
* Build the next ParsedLocation from navigation options without committing.
|
||||
* Resolves `to`/`from`, params/search/hash/state, applies search validation
|
||||
* and middlewares, and returns a stringified location object. The built
|
||||
* `search` and `state` are not structurally shared with the current
|
||||
* location; `parseLocation` stabilizes them once the location is committed.
|
||||
*
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/RouterType#buildlocation-method
|
||||
*/
|
||||
buildLocation: BuildLocationFn;
|
||||
_commitPromise: (Promise<void> & {
|
||||
resolve: () => void;
|
||||
}) | undefined;
|
||||
/**
|
||||
* Commit a previously built location to history (push/replace), optionally
|
||||
* using view transitions and scroll restoration options.
|
||||
*/
|
||||
commitLocation: CommitLocationFn;
|
||||
/** Convenience helper: build a location from options, then commit it. */
|
||||
buildAndCommitLocation: ({ replace, resetScroll, hashScrollIntoView, viewTransition, ignoreBlocker, ...rest }?: BuildNextOptions & CommitLocationOptions) => Promise<void>;
|
||||
/**
|
||||
* Imperatively navigate using standard `NavigateOptions`. When `reloadDocument`
|
||||
* or an absolute `href` is provided, performs a full document navigation.
|
||||
* Otherwise, builds and commits a client-side location.
|
||||
*
|
||||
* @link https://tanstack.com/router/latest/docs/framework/react/api/router/NavigateOptionsType
|
||||
*/
|
||||
navigate: NavigateFn;
|
||||
load: LoadFn;
|
||||
startViewTransition: (fn: () => Promise<void>) => any;
|
||||
/**
|
||||
* Invalidate selected match generations and optionally force current matches
|
||||
* back into a pending state.
|
||||
*
|
||||
* - Marks committed and cached matches whose IDs are selected as invalid.
|
||||
* - Retires selected active preloads so older work cannot publish fresh data.
|
||||
*
|
||||
* The next load decides when to publish pending UI, so invalidation does not
|
||||
* mutate the currently rendered status.
|
||||
*/
|
||||
invalidate: InvalidateFn<RouterCore<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>>;
|
||||
resolveRedirect: (redirect: AnyRedirect) => AnyRedirect;
|
||||
clearCache: ClearCacheFn<this>;
|
||||
loadRouteChunk: (route: AnyRoute, componentType?: 'errorComponent' | 'notFoundComponent' | false) => Promise<void> | undefined;
|
||||
preloadRoute: PreloadRouteFn<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, TDehydrated>;
|
||||
matchRoute: MatchRouteFn<TRouteTree, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory>;
|
||||
ssr?: {
|
||||
manifest: Manifest | undefined;
|
||||
};
|
||||
serverSsr?: ServerSsr;
|
||||
serverSsrLifecycle?: RouterSsrLifecycle;
|
||||
}
|
||||
/** Error thrown when search parameter validation fails. */
|
||||
export declare class SearchParamError extends Error {
|
||||
}
|
||||
/** Error thrown when path parameter parsing/validation fails. */
|
||||
export declare class PathParamError extends Error {
|
||||
}
|
||||
/**
|
||||
* Lazily import a module function and forward arguments to it, retaining
|
||||
* parameter and return types for the selected export key.
|
||||
*/
|
||||
export declare function lazyFn<T extends Record<string, (...args: Array<any>) => any>, TKey extends keyof T = 'default'>(fn: () => Promise<T>, key?: TKey): (...args: Parameters<T[TKey]>) => Promise<Awaited<ReturnType<T[TKey]>>>;
|
||||
/** Create an initial RouterState from a parsed location. */
|
||||
export declare function getInitialRouterState(location: ParsedLocation): RouterState<any>;
|
||||
export {};
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
//#region src/scroll-restoration-inline.ts?script-string
|
||||
var scroll_restoration_inline_default = "function(a,f){let l;try{l=JSON.parse(sessionStorage.getItem(a)||\"{}\")}catch{return}const n=l?.[f||history.state?.__TSR_key];let c=!1;for(const t in n){const e=n[t],o=e?.scrollX,s=e?.scrollY;if(Number.isFinite(o)&&Number.isFinite(s)){if(t===\"window\")scrollTo(o,s),c=!0;else if(t)try{const r=document.querySelector(t);r&&(r.scrollLeft=o,r.scrollTop=s)}catch{}}}if(c)return;const i=location.hash.slice(1);if(i){const t=history.state?.__hashScrollIntoViewOptions??!0;if(t){const e=document.getElementById(i);e&&e.scrollIntoView(t)}return}scrollTo(0,0)}";
|
||||
//#endregion
|
||||
exports.default = scroll_restoration_inline_default;
|
||||
|
||||
//# sourceMappingURL=scroll-restoration-inline.cjs.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"scroll-restoration-inline.cjs","names":[],"sources":["../../src/scroll-restoration-inline.ts?script-string"],"sourcesContent":["export default function (storageKey: string, key?: string) {\n let byKey\n\n try {\n byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}')\n } catch {\n return\n }\n\n const elementEntries = byKey?.[key || history.state?.__TSR_key]\n let windowRestored = false\n\n for (const elementSelector in elementEntries) {\n const entry = elementEntries[elementSelector]\n const scrollX = entry?.scrollX\n const scrollY = entry?.scrollY\n\n if (Number.isFinite(scrollX) && Number.isFinite(scrollY)) {\n if (elementSelector === 'window') {\n scrollTo(scrollX, scrollY)\n windowRestored = true\n } else if (elementSelector) {\n try {\n const element = document.querySelector(elementSelector)\n if (element) {\n element.scrollLeft = scrollX\n element.scrollTop = scrollY\n }\n } catch {}\n }\n }\n }\n\n if (windowRestored) return\n\n const hash = location.hash.slice(1)\n\n if (hash) {\n const hashScrollIntoViewOptions =\n history.state?.__hashScrollIntoViewOptions ?? true\n\n if (hashScrollIntoViewOptions) {\n const el = document.getElementById(hash)\n if (el) {\n el.scrollIntoView(hashScrollIntoViewOptions)\n }\n }\n\n return\n }\n\n scrollTo(0, 0)\n}\n"],"mappings":";AAAA,IAAA,oCAAe"}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export default function (storageKey: string, key?: string): void;
|
||||
Generated
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
//#region src/scroll-restoration-script/client.ts
|
||||
function getScrollRestorationScriptForRouter(_router) {
|
||||
return null;
|
||||
}
|
||||
//#endregion
|
||||
exports.getScrollRestorationScriptForRouter = getScrollRestorationScriptForRouter;
|
||||
|
||||
//# sourceMappingURL=client.cjs.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"client.cjs","names":[],"sources":["../../../src/scroll-restoration-script/client.ts"],"sourcesContent":["import type { AnyRouter } from '../router'\n\nexport function getScrollRestorationScriptForRouter(_router: AnyRouter) {\n return null\n}\n"],"mappings":";;AAEA,SAAgB,oCAAoC,SAAoB;CACtE,OAAO;AACT"}
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
import { AnyRouter } from '../router.cjs';
|
||||
export declare function getScrollRestorationScriptForRouter(_router: AnyRouter): null;
|
||||
Generated
Vendored
+23
@@ -0,0 +1,23 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_utils = require("../utils.cjs");
|
||||
const require_scroll_restoration = require("../scroll-restoration.cjs");
|
||||
const require_scroll_restoration_inline = require("../scroll-restoration-inline.cjs");
|
||||
//#region src/scroll-restoration-script/server.ts
|
||||
const defaultInlineScrollRestorationScript = `(${require_scroll_restoration_inline.default})(${require_utils.escapeHtml(JSON.stringify(require_scroll_restoration.storageKey))})`;
|
||||
function getScrollRestorationScript(key) {
|
||||
if (key === void 0) return defaultInlineScrollRestorationScript;
|
||||
return `(${require_scroll_restoration_inline.default})(${require_utils.escapeHtml(JSON.stringify(require_scroll_restoration.storageKey))},${require_utils.escapeHtml(JSON.stringify(key))})`;
|
||||
}
|
||||
function getScrollRestorationScriptForRouter(router) {
|
||||
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);
|
||||
if (userKey === require_scroll_restoration.defaultGetScrollRestorationKey(location)) return defaultInlineScrollRestorationScript;
|
||||
return getScrollRestorationScript(userKey);
|
||||
}
|
||||
//#endregion
|
||||
exports.getScrollRestorationScriptForRouter = getScrollRestorationScriptForRouter;
|
||||
|
||||
//# sourceMappingURL=server.cjs.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"server.cjs","names":[],"sources":["../../../src/scroll-restoration-script/server.ts"],"sourcesContent":["import minifiedScrollRestorationScript from '../scroll-restoration-inline?script-string'\nimport {\n defaultGetScrollRestorationKey,\n storageKey,\n} from '../scroll-restoration'\nimport { escapeHtml } from '../utils'\nimport type { AnyRouter } from '../router'\n\nconst defaultInlineScrollRestorationScript = `(${minifiedScrollRestorationScript})(${escapeHtml(\n JSON.stringify(storageKey),\n)})`\n\nfunction getScrollRestorationScript(key?: string) {\n if (key === undefined) {\n return defaultInlineScrollRestorationScript\n }\n\n return `(${minifiedScrollRestorationScript})(${escapeHtml(JSON.stringify(storageKey))},${escapeHtml(JSON.stringify(key))})`\n}\n\nexport function getScrollRestorationScriptForRouter(router: AnyRouter) {\n if (\n typeof router.options.scrollRestoration === 'function' &&\n !router.options.scrollRestoration({ location: router.latestLocation })\n ) {\n return null\n }\n\n const getKey = router.options.getScrollRestorationKey\n if (!getKey) {\n return defaultInlineScrollRestorationScript\n }\n\n const location = router.latestLocation\n const userKey = getKey(location)\n const defaultKey = defaultGetScrollRestorationKey(location)\n\n if (userKey === defaultKey) {\n return defaultInlineScrollRestorationScript\n }\n\n return getScrollRestorationScript(userKey)\n}\n"],"mappings":";;;;;AAQA,MAAM,uCAAuC,IAAI,kCAAA,QAAgC,IAAI,cAAA,WACnF,KAAK,UAAU,2BAAA,UAAU,CAC3B,EAAE;AAEF,SAAS,2BAA2B,KAAc;CAChD,IAAI,QAAQ,KAAA,GACV,OAAO;CAGT,OAAO,IAAI,kCAAA,QAAgC,IAAI,cAAA,WAAW,KAAK,UAAU,2BAAA,UAAU,CAAC,EAAE,GAAG,cAAA,WAAW,KAAK,UAAU,GAAG,CAAC,EAAE;AAC3H;AAEA,SAAgB,oCAAoC,QAAmB;CACrE,IACE,OAAO,OAAO,QAAQ,sBAAsB,cAC5C,CAAC,OAAO,QAAQ,kBAAkB,EAAE,UAAU,OAAO,eAAe,CAAC,GAErE,OAAO;CAGT,MAAM,SAAS,OAAO,QAAQ;CAC9B,IAAI,CAAC,QACH,OAAO;CAGT,MAAM,WAAW,OAAO;CACxB,MAAM,UAAU,OAAO,QAAQ;CAG/B,IAAI,YAFe,2BAAA,+BAA+B,QAElC,GACd,OAAO;CAGT,OAAO,2BAA2B,OAAO;AAC3C"}
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
import { AnyRouter } from '../router.cjs';
|
||||
export declare function getScrollRestorationScriptForRouter(router: AnyRouter): string | null;
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
let _tanstack_router_core_isServer = require("@tanstack/router-core/isServer");
|
||||
//#region src/scroll-restoration.ts
|
||||
function getSafeSessionStorage() {
|
||||
try {
|
||||
return sessionStorage;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
const storageKey = "tsr-scroll-restoration-v1_3";
|
||||
const safeSessionStorage = getSafeSessionStorage();
|
||||
function createScrollRestorationCache() {
|
||||
try {
|
||||
return JSON.parse(safeSessionStorage?.getItem("tsr-scroll-restoration-v1_3") || "{}");
|
||||
} catch {
|
||||
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.
|
||||
*/
|
||||
const defaultGetScrollRestorationKey = (location) => {
|
||||
return location.state.__TSR_key || location.href;
|
||||
};
|
||||
function getScrollRestorationSelector(element) {
|
||||
const attrId = element.getAttribute(scrollRestorationIdAttribute);
|
||||
if (attrId) return `[${scrollRestorationIdAttribute}="${attrId}"]`;
|
||||
let selector = "";
|
||||
let el = element;
|
||||
let parent;
|
||||
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;
|
||||
}
|
||||
function getElementScrollRestorationEntry(router, options) {
|
||||
const entries = scrollRestorationCache[(options.getKey || defaultGetScrollRestorationKey)(router.latestLocation)];
|
||||
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)];
|
||||
}
|
||||
let ignoreScroll = false;
|
||||
const windowScrollTarget = "window";
|
||||
function getElement(selector) {
|
||||
try {
|
||||
return typeof selector === "function" ? selector() : document.querySelector(selector);
|
||||
} catch {}
|
||||
}
|
||||
function getScrollToTopElements(scrollToTopSelectors) {
|
||||
const elements = /* @__PURE__ */ new Set();
|
||||
for (const selector of scrollToTopSelectors) {
|
||||
if (selector === windowScrollTarget) continue;
|
||||
const element = getElement(selector);
|
||||
if (element) elements.add(element);
|
||||
}
|
||||
return elements;
|
||||
}
|
||||
function setupScrollRestoration(router, force) {
|
||||
const shouldSetupScrollRestoration = force ?? router.options.scrollRestoration;
|
||||
const scroll = router._scroll;
|
||||
if (shouldSetupScrollRestoration) scroll.restoring = true;
|
||||
if (_tanstack_router_core_isServer.isServer ?? router.isServer) return;
|
||||
const getKey = router.options.getScrollRestorationKey || defaultGetScrollRestorationKey;
|
||||
const trackedScrollTargets = /* @__PURE__ */ new Set();
|
||||
const snapshotCurrentScrollTargets = (restoreKey) => {
|
||||
const keyEntry = scrollRestorationCache[restoreKey] ||= {};
|
||||
for (const target of trackedScrollTargets) if (target === document) keyEntry[windowScrollTarget] = {
|
||||
scrollX,
|
||||
scrollY
|
||||
};
|
||||
else if (target.isConnected) keyEntry[getScrollRestorationSelector(target)] = {
|
||||
scrollX: target.scrollLeft,
|
||||
scrollY: target.scrollTop
|
||||
};
|
||||
};
|
||||
if (shouldSetupScrollRestoration && !scroll.restoration) {
|
||||
scroll.restoration = true;
|
||||
ignoreScroll = false;
|
||||
history.scrollRestoration = "manual";
|
||||
document.addEventListener("scroll", (event) => {
|
||||
if (ignoreScroll) return;
|
||||
trackedScrollTargets.add(event.target);
|
||||
}, 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;
|
||||
router.subscribe("onRendered", (event) => {
|
||||
const behavior = router.options.scrollRestorationBehavior;
|
||||
const scrollToTopSelectors = router.options.scrollToTopSelectors;
|
||||
const shouldResetScroll = scroll.next;
|
||||
const hashNavigation = scroll.hash;
|
||||
let scrollToTopElements;
|
||||
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] = {};
|
||||
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] : void 0;
|
||||
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;
|
||||
}
|
||||
});
|
||||
}
|
||||
//#endregion
|
||||
exports.defaultGetScrollRestorationKey = defaultGetScrollRestorationKey;
|
||||
exports.getElementScrollRestorationEntry = getElementScrollRestorationEntry;
|
||||
exports.setupScrollRestoration = setupScrollRestoration;
|
||||
exports.storageKey = storageKey;
|
||||
|
||||
//# sourceMappingURL=scroll-restoration.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"scroll-restoration.cjs","names":[],"sources":["../../src/scroll-restoration.ts"],"sourcesContent":["import { isServer } from '@tanstack/router-core/isServer'\nimport type { AnyRouter } from './router'\nimport type { ParsedLocation } from './location'\n\nexport type ScrollRestorationEntry = { scrollX: number; scrollY: number }\n\ntype ScrollRestorationByElement = Record<string, ScrollRestorationEntry>\n\ntype ScrollRestorationByKey = Record<string, ScrollRestorationByElement>\n\nexport type ScrollRestorationOptions = {\n getKey?: (location: ParsedLocation) => string\n scrollBehavior?: ScrollToOptions['behavior']\n}\n\nfunction getSafeSessionStorage() {\n try {\n // Accessing sessionStorage itself can throw SecurityError in locked-down\n // contexts, e.g. sandboxed/opaque origins or blocked storage policies.\n return sessionStorage\n } catch {\n return\n }\n}\n\n// SessionStorage key used to store scroll positions across navigations.\nexport const storageKey = 'tsr-scroll-restoration-v1_3'\nconst safeSessionStorage = getSafeSessionStorage()\n\nfunction createScrollRestorationCache() {\n try {\n return JSON.parse(\n safeSessionStorage?.getItem(storageKey) || '{}',\n ) as ScrollRestorationByKey\n } catch {\n // ignore invalid session storage payloads\n return {}\n }\n}\n\nfunction persistScrollRestorationCache() {\n try {\n safeSessionStorage?.setItem(\n storageKey,\n JSON.stringify(scrollRestorationCache),\n )\n } catch {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n '[ts-router] Could not persist scroll restoration state to sessionStorage.',\n )\n }\n }\n}\n\nconst scrollRestorationCache = /* @__PURE__ */ createScrollRestorationCache()\nconst scrollRestorationIdAttribute = 'data-scroll-restoration-id'\n\n/**\n * The default `getKey` function for `useScrollRestoration`.\n * It returns the `key` from the location state or the `href` of the location.\n *\n * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.\n */\nexport const defaultGetScrollRestorationKey = (location: ParsedLocation) => {\n return location.state.__TSR_key! || location.href\n}\n\nfunction getScrollRestorationSelector(element: Element): string {\n const attrId = element.getAttribute(scrollRestorationIdAttribute)\n if (attrId) {\n return `[${scrollRestorationIdAttribute}=\"${attrId}\"]`\n }\n\n let selector = ''\n let el: any = element\n let parent: HTMLElement\n\n while ((parent = el.parentNode)) {\n let index = 1\n let sibling = el\n while ((sibling = sibling.previousElementSibling)) {\n index++\n }\n\n const part = `${el.localName}:nth-child(${index})`\n selector = selector ? `${part} > ${selector}` : part\n el = parent\n }\n\n return selector\n}\n\nexport function getElementScrollRestorationEntry(\n router: AnyRouter,\n options: (\n | {\n id: string\n getElement?: () => Window | Element | undefined | null\n }\n | {\n id?: string\n getElement: () => Window | Element | undefined | null\n }\n ) & {\n getKey?: (location: ParsedLocation) => string\n },\n): ScrollRestorationEntry | undefined {\n const getKey = options.getKey || defaultGetScrollRestorationKey\n const restoreKey = getKey(router.latestLocation)\n const entries = scrollRestorationCache[restoreKey]\n\n if (!entries) {\n return\n }\n\n if (options.id) {\n return entries[`[${scrollRestorationIdAttribute}=\"${options.id}\"]`]\n }\n\n const element = options.getElement?.()\n if (!element) {\n return\n }\n\n return entries[\n element === window\n ? windowScrollTarget\n : getScrollRestorationSelector(element as Element)\n ]\n}\n\nlet ignoreScroll = false\nconst windowScrollTarget = 'window'\n\nfunction getElement(selector: string | (() => Element | null | undefined)) {\n try {\n return typeof selector === 'function'\n ? selector()\n : document.querySelector(selector)\n } catch {}\n return\n}\n\nfunction getScrollToTopElements(\n scrollToTopSelectors: NonNullable<\n AnyRouter['options']['scrollToTopSelectors']\n >,\n) {\n const elements = new Set<Element>()\n\n for (const selector of scrollToTopSelectors) {\n if (selector === windowScrollTarget) {\n continue\n }\n\n const element = getElement(selector)\n if (element) {\n elements.add(element)\n }\n }\n\n return elements\n}\n\nexport function setupScrollRestoration(router: AnyRouter, force?: boolean) {\n // Keep hash/top scrolling active even when sessionStorage is unavailable.\n const shouldSetupScrollRestoration = force ?? router.options.scrollRestoration\n const scroll = router._scroll\n\n if (shouldSetupScrollRestoration) {\n scroll.restoring = true\n }\n\n if (isServer ?? router.isServer) {\n return\n }\n\n const getKey =\n router.options.getScrollRestorLine truncated
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import { AnyRouter } from './router.cjs';
|
||||
import { ParsedLocation } from './location.cjs';
|
||||
export type ScrollRestorationEntry = {
|
||||
scrollX: number;
|
||||
scrollY: number;
|
||||
};
|
||||
export type ScrollRestorationOptions = {
|
||||
getKey?: (location: ParsedLocation) => string;
|
||||
scrollBehavior?: ScrollToOptions['behavior'];
|
||||
};
|
||||
export declare const storageKey = "tsr-scroll-restoration-v1_3";
|
||||
/**
|
||||
* 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 declare const defaultGetScrollRestorationKey: (location: ParsedLocation) => string;
|
||||
export declare 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;
|
||||
export declare function setupScrollRestoration(router: AnyRouter, force?: boolean): void;
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
const require_utils = require("./utils.cjs");
|
||||
//#region src/searchMiddleware.ts
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
function retainSearchParams(keys) {
|
||||
return ({ search, next }) => {
|
||||
const { search: resultSearch, meta } = next(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 && require_utils.hasOwn.call(explicit, key) || require_utils.deepEqual(search[key], removed.get(key))) delete copy[key];
|
||||
for (const key of meta.removedAny || []) delete copy[key];
|
||||
for (const key of meta.defaulted?.keys() || []) if (key in search && !meta.removedAny?.has(key) && !(meta.removed?.has(key) && (explicit && require_utils.hasOwn.call(explicit, key) || require_utils.deepEqual(search[key], meta.removed.get(key))))) copy[key] = search[key];
|
||||
return copy;
|
||||
}
|
||||
const copy = { ...resultSearch };
|
||||
const explicit = meta.explicit;
|
||||
for (const key of keys) {
|
||||
const stringKey = key;
|
||||
if (!(meta.removedAny?.has(stringKey) || meta.removed?.has(stringKey) && (explicit && require_utils.hasOwn.call(explicit, stringKey) || require_utils.deepEqual(search[key], meta.removed.get(stringKey)))) && (!(key in copy) || key in search && meta.defaulted?.has(stringKey) && require_utils.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
|
||||
*/
|
||||
function stripSearchParams(input) {
|
||||
return (({ search, next, meta }) => {
|
||||
if (input === true) {
|
||||
Object.keys(search).forEach((key) => {
|
||||
if (meta) (meta.removedAny ||= /* @__PURE__ */ new Set()).add(key);
|
||||
});
|
||||
return {};
|
||||
}
|
||||
const result = { ...next(search) };
|
||||
if (Array.isArray(input)) input.forEach((key) => {
|
||||
delete result[key];
|
||||
if (meta) (meta.removedAny ||= /* @__PURE__ */ new Set()).add(key);
|
||||
});
|
||||
else Object.entries(input).forEach(([key, value]) => {
|
||||
if (require_utils.deepEqual(result[key], value)) {
|
||||
delete result[key];
|
||||
if (meta) (meta.removed ||= /* @__PURE__ */ new Map()).set(key, value);
|
||||
}
|
||||
});
|
||||
return result;
|
||||
});
|
||||
}
|
||||
//#endregion
|
||||
exports.retainSearchParams = retainSearchParams;
|
||||
exports.stripSearchParams = stripSearchParams;
|
||||
|
||||
//# sourceMappingURL=searchMiddleware.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"searchMiddleware.cjs","names":[],"sources":["../../src/searchMiddleware.ts"],"sourcesContent":["import { deepEqual, hasOwn } from './utils'\nimport type { NoInfer, PickOptional } from './utils'\nimport type {\n SearchMiddleware,\n SearchMiddlewareContext,\n SearchMiddlewareMeta,\n} from './route'\nimport type { IsRequiredParams } from './link'\n\ntype SearchMiddlewareNextWithMeta<TSearchSchema> = (\n newSearch: TSearchSchema,\n collectMeta: true,\n) => { search: TSearchSchema; meta: SearchMiddlewareMeta }\n\n/**\n * Retain specified search params across navigations.\n *\n * If `keys` is `true`, retain all current params. Otherwise, copy only the\n * listed keys from the current search into the next search.\n *\n * @param keys `true` to retain all, or a list of keys to retain.\n * @returns A search middleware suitable for route `search.middlewares`.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/retainSearchParamsFunction\n */\nexport function retainSearchParams<TSearchSchema extends object>(\n keys: Array<keyof TSearchSchema> | true,\n): SearchMiddleware<TSearchSchema> {\n return ({ search, next }) => {\n const { search: resultSearch, meta } = (\n next as unknown as SearchMiddlewareNextWithMeta<TSearchSchema>\n )(search, true)\n\n if (keys === true) {\n const copy = { ...search, ...resultSearch }\n const removed = meta.removed\n const explicit = meta.explicit\n for (const key of removed?.keys() || []) {\n if (\n (explicit && hasOwn.call(explicit, key)) ||\n deepEqual(search[key as keyof TSearchSchema], removed!.get(key))\n ) {\n delete copy[key as keyof TSearchSchema]\n }\n }\n for (const key of meta.removedAny || []) {\n delete copy[key as keyof TSearchSchema]\n }\n for (const key of meta.defaulted?.keys() || []) {\n if (\n key in search &&\n !meta.removedAny?.has(key) &&\n !(\n meta.removed?.has(key) &&\n ((explicit && hasOwn.call(explicit, key)) ||\n deepEqual(\n search[key as keyof TSearchSchema],\n meta.removed.get(key),\n ))\n )\n ) {\n copy[key as keyof TSearchSchema] = search[key as keyof TSearchSchema]\n }\n }\n return copy\n }\n\n const copy = { ...resultSearch }\n const explicit = meta.explicit\n // add missing keys from search to copy\n for (const key of keys) {\n const stringKey = key as string\n const removed =\n meta.removedAny?.has(stringKey) ||\n (meta.removed?.has(stringKey) &&\n ((explicit && hasOwn.call(explicit, stringKey)) ||\n deepEqual(search[key], meta.removed.get(stringKey))))\n if (\n !removed &&\n (!(key in copy) ||\n (key in search &&\n meta.defaulted?.has(stringKey) &&\n deepEqual(copy[key], meta.defaulted.get(stringKey))))\n ) {\n copy[key] = search[key]\n }\n }\n return copy\n }\n}\n\n/**\n * Remove optional or default-valued search params from navigations.\n *\n * - Pass `true` (only if there are no required search params) to strip all.\n * - Pass an array to always remove those optional keys.\n * - Pass an object of default values; keys equal (deeply) to the defaults are removed.\n *\n * @returns A search middleware suitable for route `search.middlewares`.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/stripSearchParamsFunction\n */\nexport function stripSearchParams<\n TSearchSchema,\n TOptionalProps = PickOptional<NoInfer<TSearchSchema>>,\n const TValues = Partial<NoInfer<TSearchSchema>> | Array<keyof TOptionalProps>,\n const TInput = IsRequiredParams<TSearchSchema> extends never\n ? TValues | true\n : TValues,\n>(input: NoInfer<TInput>): SearchMiddleware<TSearchSchema> {\n return (({ search, next, meta }: SearchMiddlewareContext<TSearchSchema>) => {\n if (input === true) {\n Object.keys(search as object).forEach((key) => {\n if (meta) {\n ;(meta.removedAny ||= new Set()).add(key)\n }\n })\n return {}\n }\n const nextResult = next(search)\n const result = { ...nextResult } as Record<string, unknown>\n if (Array.isArray(input)) {\n input.forEach((key) => {\n delete result[key as string]\n if (meta) {\n ;(meta.removedAny ||= new Set()).add(key as string)\n }\n })\n } else {\n Object.entries(input as Record<string, unknown>).forEach(\n ([key, value]) => {\n if (deepEqual(result[key], value)) {\n delete result[key]\n if (meta) {\n ;(meta.removed ||= new Map()).set(key, value)\n }\n }\n },\n )\n }\n return result as any\n }) as SearchMiddleware<TSearchSchema>\n}\n"],"mappings":";;;;;;;;;;;;AAwBA,SAAgB,mLine truncated
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import { NoInfer, PickOptional } from './utils.cjs';
|
||||
import { SearchMiddleware } from './route.cjs';
|
||||
import { IsRequiredParams } from './link.cjs';
|
||||
/**
|
||||
* 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 declare function retainSearchParams<TSearchSchema extends object>(keys: Array<keyof TSearchSchema> | true): SearchMiddleware<TSearchSchema>;
|
||||
/**
|
||||
* 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 declare 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>;
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
const require_qss = require("./qss.cjs");
|
||||
//#region src/searchParams.ts
|
||||
const jsonStart = /^(?:\s|["[{\d-]|fa|nu|tr)/;
|
||||
/** Default `parseSearch` that strips leading '?' and JSON-parses values. */
|
||||
const defaultParseSearch = parseSearchWith(JSON.parse);
|
||||
/** Default `stringifySearch` using JSON.stringify for complex values. */
|
||||
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
|
||||
*/
|
||||
function parseSearchWith(parser) {
|
||||
const isJsonParser = parser === JSON.parse;
|
||||
return (searchStr) => {
|
||||
if (searchStr[0] === "?") searchStr = searchStr.substring(1);
|
||||
const query = require_qss.decode(searchStr);
|
||||
for (const key in query) {
|
||||
const value = query[key];
|
||||
if (typeof value === "string") {
|
||||
if (isJsonParser && !jsonStart.test(value)) continue;
|
||||
try {
|
||||
query[key] = parser(value);
|
||||
} catch (_err) {}
|
||||
}
|
||||
}
|
||||
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
|
||||
*/
|
||||
function stringifySearchWith(stringify, parser) {
|
||||
const isJsonParser = parser === JSON.parse;
|
||||
function stringifyValue(val) {
|
||||
if (val && typeof val === "object") try {
|
||||
return stringify(val);
|
||||
} catch (_err) {}
|
||||
else if (parser && typeof val === "string") {
|
||||
if (isJsonParser && !jsonStart.test(val)) return val;
|
||||
try {
|
||||
parser(val);
|
||||
return stringify(val);
|
||||
} catch (_err) {}
|
||||
}
|
||||
return val;
|
||||
}
|
||||
return (search) => {
|
||||
const searchStr = require_qss.encode(search, stringifyValue);
|
||||
return searchStr ? `?${searchStr}` : "";
|
||||
};
|
||||
}
|
||||
//#endregion
|
||||
exports.defaultParseSearch = defaultParseSearch;
|
||||
exports.defaultStringifySearch = defaultStringifySearch;
|
||||
exports.parseSearchWith = parseSearchWith;
|
||||
exports.stringifySearchWith = stringifySearchWith;
|
||||
|
||||
//# sourceMappingURL=searchParams.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"searchParams.cjs","names":[],"sources":["../../src/searchParams.ts"],"sourcesContent":["import { decode, encode } from './qss'\nimport type { AnySchema } from './validators'\n\n// JSON can start with whitespace, \", [, {, -, a digit, or fa/nu/tr.\n// False positives safely fall through to JSON.parse.\nconst jsonStart = /^(?:\\s|[\"[{\\d-]|fa|nu|tr)/\n\n/** Default `parseSearch` that strips leading '?' and JSON-parses values. */\nexport const defaultParseSearch = parseSearchWith(JSON.parse)\n/** Default `stringifySearch` using JSON.stringify for complex values. */\nexport const defaultStringifySearch = stringifySearchWith(\n JSON.stringify,\n JSON.parse,\n)\n\n/**\n * Build a `parseSearch` function using a provided JSON-like parser.\n *\n * The returned function strips a leading `?`, decodes values, and attempts to\n * JSON-parse string values using the given `parser`.\n *\n * @param parser Function to parse a string value (e.g. `JSON.parse`).\n * @returns A `parseSearch` function compatible with `Router` options.\n * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization\n */\nexport function parseSearchWith(parser: (str: string) => any) {\n const isJsonParser = parser === JSON.parse\n return (searchStr: string): AnySchema => {\n if (searchStr[0] === '?') {\n searchStr = searchStr.substring(1)\n }\n\n const query: Record<string, unknown> = decode(searchStr)\n\n // Try to parse any query params that might be json\n for (const key in query) {\n const value = query[key]\n if (typeof value === 'string') {\n // Skip JSON.parse when the value cannot begin valid JSON.\n if (isJsonParser && !jsonStart.test(value)) {\n continue\n }\n try {\n query[key] = parser(value)\n } catch (_err) {\n // silent\n }\n }\n }\n\n return query\n }\n}\n\n/**\n * Build a `stringifySearch` function using a provided serializer.\n *\n * Non-primitive values are serialized with `stringify`. If a `parser` is\n * supplied, string values that are parseable are re-serialized to ensure\n * symmetry with `parseSearch`.\n *\n * @param stringify Function to serialize a value (e.g. `JSON.stringify`).\n * @param parser Optional parser to detect parseable strings.\n * @returns A `stringifySearch` function compatible with `Router` options.\n * @link https://tanstack.com/router/latest/docs/framework/react/guide/custom-search-param-serialization\n */\nexport function stringifySearchWith(\n stringify: (search: any) => string,\n parser?: (str: string) => any,\n) {\n const isJsonParser = parser === JSON.parse\n function stringifyValue(val: any) {\n if (val && typeof val === 'object') {\n try {\n return stringify(val)\n } catch (_err) {\n // silent\n }\n } else if (parser && typeof val === 'string') {\n // Skip JSON.parse when the value cannot begin valid JSON.\n if (isJsonParser && !jsonStart.test(val)) {\n return val\n }\n try {\n // Check if it's a valid parseable string.\n // If it is, then stringify it again.\n parser(val)\n return stringify(val)\n } catch (_err) {\n // silent\n }\n }\n return val\n }\n\n return (search: Record<string, any>) => {\n const searchStr = encode(search, stringifyValue)\n return searchStr ? `?${searchStr}` : ''\n }\n}\n\nexport type SearchSerializer = (searchObj: Record<string, any>) => string\nexport type SearchParser = (searchStr: string) => Record<string, any>\n"],"mappings":";;AAKA,MAAM,YAAY;;AAGlB,MAAa,qBAAqB,gBAAgB,KAAK,KAAK;;AAE5D,MAAa,yBAAyB,oBACpC,KAAK,WACL,KAAK,KACP;;;;;;;;;;;AAYA,SAAgB,gBAAgB,QAA8B;CAC5D,MAAM,eAAe,WAAW,KAAK;CACrC,QAAQ,cAAiC;EACvC,IAAI,UAAU,OAAO,KACnB,YAAY,UAAU,UAAU,CAAC;EAGnC,MAAM,QAAiC,YAAA,OAAO,SAAS;EAGvD,KAAK,MAAM,OAAO,OAAO;GACvB,MAAM,QAAQ,MAAM;GACpB,IAAI,OAAO,UAAU,UAAU;IAE7B,IAAI,gBAAgB,CAAC,UAAU,KAAK,KAAK,GACvC;IAEF,IAAI;KACF,MAAM,OAAO,OAAO,KAAK;IAC3B,SAAS,MAAM,CAEf;GACF;EACF;EAEA,OAAO;CACT;AACF;;;;;;;;;;;;;AAcA,SAAgB,oBACd,WACA,QACA;CACA,MAAM,eAAe,WAAW,KAAK;CACrC,SAAS,eAAe,KAAU;EAChC,IAAI,OAAO,OAAO,QAAQ,UACxB,IAAI;GACF,OAAO,UAAU,GAAG;EACtB,SAAS,MAAM,CAEf;OACK,IAAI,UAAU,OAAO,QAAQ,UAAU;GAE5C,IAAI,gBAAgB,CAAC,UAAU,KAAK,GAAG,GACrC,OAAO;GAET,IAAI;IAGF,OAAO,GAAG;IACV,OAAO,UAAU,GAAG;GACtB,SAAS,MAAM,CAEf;EACF;EACA,OAAO;CACT;CAEA,QAAQ,WAAgC;EACtC,MAAM,YAAY,YAAA,OAAO,QAAQ,cAAc;EAC/C,OAAO,YAAY,IAAI,cAAc;CACvC;AACF"}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import { AnySchema } from './validators.cjs';
|
||||
/** Default `parseSearch` that strips leading '?' and JSON-parses values. */
|
||||
export declare const defaultParseSearch: (searchStr: string) => AnySchema;
|
||||
/** Default `stringifySearch` using JSON.stringify for complex values. */
|
||||
export declare const defaultStringifySearch: (search: Record<string, any>) => string;
|
||||
/**
|
||||
* 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 declare function parseSearchWith(parser: (str: string) => any): (searchStr: string) => AnySchema;
|
||||
/**
|
||||
* 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 declare function stringifySearchWith(stringify: (search: any) => string, parser?: (str: string) => any): (search: Record<string, any>) => string;
|
||||
export type SearchSerializer = (searchObj: Record<string, any>) => string;
|
||||
export type SearchParser = (searchStr: string) => Record<string, any>;
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
//#region src/sieve-cache.ts
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
function createSieveCache(max) {
|
||||
const cache = /* @__PURE__ */ new Map();
|
||||
let hand;
|
||||
let newest;
|
||||
return {
|
||||
get(key) {
|
||||
const entry = cache.get(key);
|
||||
if (!entry) return;
|
||||
entry.visited = true;
|
||||
return entry.value;
|
||||
},
|
||||
set(key, value) {
|
||||
const existing = cache.get(key);
|
||||
if (existing) {
|
||||
existing.value = value;
|
||||
return;
|
||||
}
|
||||
if (cache.size >= max) {
|
||||
let node = hand?.next().value;
|
||||
while (!node || node.visited) {
|
||||
if (node) node.visited = false;
|
||||
else hand = cache.values();
|
||||
node = hand.next().value;
|
||||
}
|
||||
if (node === newest) hand = void 0;
|
||||
cache.delete(node.key);
|
||||
}
|
||||
const entry = {
|
||||
key,
|
||||
value,
|
||||
visited: false
|
||||
};
|
||||
newest = entry;
|
||||
cache.set(key, entry);
|
||||
},
|
||||
clear() {
|
||||
cache.clear();
|
||||
hand = void 0;
|
||||
newest = void 0;
|
||||
}
|
||||
};
|
||||
}
|
||||
//#endregion
|
||||
exports.createSieveCache = createSieveCache;
|
||||
|
||||
//# sourceMappingURL=sieve-cache.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"sieve-cache.cjs","names":[],"sources":["../../src/sieve-cache.ts"],"sourcesContent":["export type SieveCache<TKey, TValue> = {\n get: (key: TKey) => TValue | undefined\n set: (key: TKey, value: TValue) => void\n clear: () => void\n}\n\n/**\n * A fixed-capacity cache using the SIEVE eviction algorithm\n * (https://cachemon.github.io/SIEVE-website/).\n *\n * Entries live in the Map's FIFO insertion order; a hit only flips a `visited`\n * bit instead of relinking the entry, which makes `get` (by far the hottest\n * operation here) one `Map.get` plus a boolean store. Eviction sweeps a `hand`\n * from the oldest entry towards the newest, clearing `visited` bits until it\n * finds an unvisited entry to drop, so entries touched since the last sweep\n * survive one more round. This keeps LRU-like hit ratios while being\n * scan-resistant.\n */\nexport function createSieveCache<TKey, TValue>(\n max: number,\n): SieveCache<TKey, TValue> {\n type Node = {\n key: TKey\n value: TValue\n visited: boolean\n }\n const cache = new Map<TKey, Node>()\n let hand: IterableIterator<Node> | undefined\n let newest: Node | undefined\n\n return {\n get(key) {\n const entry = cache.get(key)\n if (!entry) {\n return undefined\n }\n entry.visited = true\n return entry.value\n },\n set(key, value) {\n const existing = cache.get(key)\n if (existing) {\n existing.value = value\n return\n }\n if (cache.size >= max) {\n // sweep from `hand` towards `newest` (wrapping around to `oldest`),\n // clearing `visited` bits, and evict the first unvisited entry\n let node = hand?.next().value\n while (!node || node.visited) {\n if (node) {\n node.visited = false\n } else {\n hand = cache.values()\n }\n node = hand!.next().value\n }\n // Live Map iterators see later insertions. Reset at the boundary so the\n // next sweep wraps to the oldest entry instead of visiting a replacement.\n if (node === newest) {\n hand = undefined\n }\n cache.delete(node.key)\n }\n const entry: Node = { key, value, visited: false }\n newest = entry\n cache.set(key, entry)\n },\n clear() {\n cache.clear()\n hand = undefined\n newest = undefined\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAkBA,SAAgB,iBACd,KAC0B;CAM1B,MAAM,wBAAQ,IAAI,IAAgB;CAClC,IAAI;CACJ,IAAI;CAEJ,OAAO;EACL,IAAI,KAAK;GACP,MAAM,QAAQ,MAAM,IAAI,GAAG;GAC3B,IAAI,CAAC,OACH;GAEF,MAAM,UAAU;GAChB,OAAO,MAAM;EACf;EACA,IAAI,KAAK,OAAO;GACd,MAAM,WAAW,MAAM,IAAI,GAAG;GAC9B,IAAI,UAAU;IACZ,SAAS,QAAQ;IACjB;GACF;GACA,IAAI,MAAM,QAAQ,KAAK;IAGrB,IAAI,OAAO,MAAM,KAAK,EAAE;IACxB,OAAO,CAAC,QAAQ,KAAK,SAAS;KAC5B,IAAI,MACF,KAAK,UAAU;UAEf,OAAO,MAAM,OAAO;KAEtB,OAAO,KAAM,KAAK,EAAE;IACtB;IAGA,IAAI,SAAS,QACX,OAAO,KAAA;IAET,MAAM,OAAO,KAAK,GAAG;GACvB;GACA,MAAM,QAAc;IAAE;IAAK;IAAO,SAAS;GAAM;GACjD,SAAS;GACT,MAAM,IAAI,KAAK,KAAK;EACtB;EACA,QAAQ;GACN,MAAM,MAAM;GACZ,OAAO,KAAA;GACP,SAAS,KAAA;EACX;CACF;AACF"}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
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 declare function createSieveCache<TKey, TValue>(max: number): SieveCache<TKey, TValue>;
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
const require_load_client = require("../load-client.cjs");
|
||||
//#region src/ssr/bodyScripts.ts
|
||||
function getSsrBodyScriptParts(matches, manifest, nonce, routeScriptAttrs) {
|
||||
const assetMatches = require_load_client._getAssetMatches(matches);
|
||||
const routeScripts = [];
|
||||
const manifestScripts = [];
|
||||
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];
|
||||
}
|
||||
function composeSsrBodyScripts([routeScripts, manifestScripts], initialHydrationScripts) {
|
||||
if (!initialHydrationScripts) return [...routeScripts, ...manifestScripts];
|
||||
return [
|
||||
...initialHydrationScripts.before,
|
||||
...routeScripts,
|
||||
...manifestScripts,
|
||||
initialHydrationScripts.boundary
|
||||
];
|
||||
}
|
||||
//#endregion
|
||||
exports.composeSsrBodyScripts = composeSsrBodyScripts;
|
||||
exports.getSsrBodyScriptParts = getSsrBodyScriptParts;
|
||||
|
||||
//# sourceMappingURL=bodyScripts.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"bodyScripts.cjs","names":[],"sources":["../../../src/ssr/bodyScripts.ts"],"sourcesContent":["import { _getAssetMatches } from '../load-client'\nimport type { Manifest, RouterManagedTag } from '../manifest'\nimport type { AnyRouteMatch } from '../Matches'\nimport type { InitialHydrationScriptTags } from './hydrationScripts'\n\ntype ScriptTags = Array<RouterManagedTag>\nexport type SsrBodyScriptParts = readonly [ScriptTags, ScriptTags]\n\nexport function getSsrBodyScriptParts(\n matches: Array<AnyRouteMatch>,\n manifest: Manifest | undefined,\n nonce: string | undefined,\n routeScriptAttrs?: Record<string, unknown>,\n): SsrBodyScriptParts {\n const assetMatches = _getAssetMatches(matches)\n const routeScripts: ScriptTags = []\n const manifestScripts: ScriptTags = []\n for (const match of assetMatches) {\n for (const script of Array.isArray(match.scripts) ? match.scripts : []) {\n if (!script) {\n continue\n }\n const { children, ...attrs } = script\n routeScripts.push({\n tag: 'script',\n attrs: { ...attrs, ...routeScriptAttrs, nonce },\n children,\n })\n }\n }\n if (manifest) {\n for (const match of assetMatches) {\n for (const asset of manifest.routes[match.routeId]?.scripts ?? []) {\n manifestScripts.push({\n tag: 'script',\n attrs: { ...asset.attrs, nonce },\n children: asset.children,\n })\n }\n }\n }\n return [routeScripts, manifestScripts]\n}\nexport function composeSsrBodyScripts(\n [routeScripts, manifestScripts]: SsrBodyScriptParts,\n initialHydrationScripts?: InitialHydrationScriptTags,\n): Array<RouterManagedTag> {\n if (!initialHydrationScripts) {\n return [...routeScripts, ...manifestScripts]\n }\n return [\n ...initialHydrationScripts.before,\n ...routeScripts,\n ...manifestScripts,\n initialHydrationScripts.boundary,\n ]\n}\n"],"mappings":";;AAQA,SAAgB,sBACd,SACA,UACA,OACA,kBACoB;CACpB,MAAM,eAAe,oBAAA,iBAAiB,OAAO;CAC7C,MAAM,eAA2B,CAAC;CAClC,MAAM,kBAA8B,CAAC;CACrC,KAAK,MAAM,SAAS,cAClB,KAAK,MAAM,UAAU,MAAM,QAAQ,MAAM,OAAO,IAAI,MAAM,UAAU,CAAC,GAAG;EACtE,IAAI,CAAC,QACH;EAEF,MAAM,EAAE,UAAU,GAAG,UAAU;EAC/B,aAAa,KAAK;GAChB,KAAK;GACL,OAAO;IAAE,GAAG;IAAO,GAAG;IAAkB;GAAM;GAC9C;EACF,CAAC;CACH;CAEF,IAAI,UACF,KAAK,MAAM,SAAS,cAClB,KAAK,MAAM,SAAS,SAAS,OAAO,MAAM,UAAU,WAAW,CAAC,GAC9D,gBAAgB,KAAK;EACnB,KAAK;EACL,OAAO;GAAE,GAAG,MAAM;GAAO;EAAM;EAC/B,UAAU,MAAM;CAClB,CAAC;CAIP,OAAO,CAAC,cAAc,eAAe;AACvC;AACA,SAAgB,sBACd,CAAC,cAAc,kBACf,yBACyB;CACzB,IAAI,CAAC,yBACH,OAAO,CAAC,GAAG,cAAc,GAAG,eAAe;CAE7C,OAAO;EACL,GAAG,wBAAwB;EAC3B,GAAG;EACH,GAAG;EACH,wBAAwB;CAC1B;AACF"}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import { Manifest, RouterManagedTag } from '../manifest.cjs';
|
||||
import { AnyRouteMatch } from '../Matches.cjs';
|
||||
import { InitialHydrationScriptTags } from './hydrationScripts.cjs';
|
||||
type ScriptTags = Array<RouterManagedTag>;
|
||||
export type SsrBodyScriptParts = readonly [ScriptTags, ScriptTags];
|
||||
export declare function getSsrBodyScriptParts(matches: Array<AnyRouteMatch>, manifest: Manifest | undefined, nonce: string | undefined, routeScriptAttrs?: Record<string, unknown>): SsrBodyScriptParts;
|
||||
export declare function composeSsrBodyScripts([routeScripts, manifestScripts]: SsrBodyScriptParts, initialHydrationScripts?: InitialHydrationScriptTags): Array<RouterManagedTag>;
|
||||
export {};
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
const require_load_client = require("../load-client.cjs");
|
||||
const require_makeSerovalPlugin = require("./serializer/makeSerovalPlugin.cjs");
|
||||
const require_headers = require("./headers.cjs");
|
||||
const require_json = require("./json.cjs");
|
||||
const require_seroval_plugins = require("./serializer/seroval-plugins.cjs");
|
||||
const require_RawStreamRPCPlugin = require("./serializer/RawStreamRPCPlugin.cjs");
|
||||
exports.createDefaultSerovalPlugins = require_seroval_plugins.createDefaultSerovalPlugins;
|
||||
exports.createRawStreamDeserializePlugin = require_RawStreamRPCPlugin.createRawStreamDeserializePlugin;
|
||||
exports.defaultSerovalDeserializerPlugins = require_seroval_plugins.defaultSerovalDeserializerPlugins;
|
||||
exports.defaultSerovalPlugins = require_seroval_plugins.defaultSerovalPlugins;
|
||||
exports.hydrate = require_load_client.hydrate;
|
||||
exports.json = require_json.json;
|
||||
exports.makeSerovalPlugin = require_makeSerovalPlugin.makeSerovalPlugin;
|
||||
exports.mergeHeaders = require_headers.mergeHeaders;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
export { mergeHeaders } from './headers.cjs';
|
||||
export { json } from './json.cjs';
|
||||
export type { JsonResponse } from './json.cjs';
|
||||
export { hydrate } from './ssr-client.cjs';
|
||||
export * from './ssr-client.cjs';
|
||||
export type { TsrSsrGlobal, DehydratedMatch, DehydratedRouter } from './types.cjs';
|
||||
export { createDefaultSerovalPlugins, defaultSerovalPlugins, defaultSerovalDeserializerPlugins, } from './serializer/seroval-plugins.cjs';
|
||||
export { makeSerovalPlugin } from './serializer/makeSerovalPlugin.cjs';
|
||||
export type { AnySerializationAdapter } from './serializer/transformer.cjs';
|
||||
export { createRawStreamDeserializePlugin } from './serializer/RawStreamRPCPlugin.cjs';
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
//#region src/ssr/constants.ts
|
||||
const GLOBAL_TSR = "$_TSR";
|
||||
//#endregion
|
||||
exports.GLOBAL_TSR = GLOBAL_TSR;
|
||||
|
||||
//# sourceMappingURL=constants.cjs.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"constants.cjs","names":[],"sources":["../../../src/ssr/constants.ts"],"sourcesContent":["export const GLOBAL_TSR = '$_TSR'\nexport declare const GLOBAL_SEROVAL: '$R'\n"],"mappings":";AAAA,MAAa,aAAa"}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
export declare const GLOBAL_TSR = "$_TSR";
|
||||
export declare const GLOBAL_SEROVAL: '$R';
|
||||
Loaded 100 of 4271 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user