@tanstack/react-router 1.15.2 → 1.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const invariant = require("tiny-invariant");
4
+ const XTSROrigin = "x-tsr-origin";
5
+ function createServerFn(method, fn) {
6
+ const compiledFn = fn;
7
+ console.log(
8
+ compiledFn,
9
+ compiledFn.toString(),
10
+ JSON.stringify(compiledFn, null, 2)
11
+ );
12
+ invariant(
13
+ compiledFn.url,
14
+ `createServerFn must be called with a function that is marked with the 'use server' pragma.`
15
+ );
16
+ return Object.assign(
17
+ async (payload, opts) => {
18
+ return compiledFn({
19
+ method,
20
+ type: payload instanceof Request ? "request" : "payload",
21
+ payload,
22
+ requestInit: opts == null ? void 0 : opts.requestInit
23
+ });
24
+ },
25
+ {
26
+ url: fn.url
27
+ }
28
+ );
29
+ }
30
+ exports.XTSROrigin = XTSROrigin;
31
+ exports.createServerFn = createServerFn;
32
+ //# sourceMappingURL=createServerFn.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createServerFn.cjs","sources":["../../src/createServerFn.ts"],"sourcesContent":["import invariant from 'tiny-invariant'\n\nexport const XTSROrigin = 'x-tsr-origin'\n\nexport interface JsonResponse<TData> extends Response {\n json(): Promise<TData>\n}\n\nexport type FetcherOptionsBase = {\n method?: 'GET' | 'POST'\n}\n\nexport type FetcherOptions = FetcherOptionsBase & {\n requestInit?: RequestInit\n}\n\nexport type FetchFnCtx = {\n method: 'GET' | 'POST'\n request: Request\n}\n\nexport type FetchFn<TPayload, TResponse> = {\n (payload: TPayload, ctx: FetchFnCtx): TResponse\n url?: string\n}\n\n// export type AnyFetchFn = FetchFn<any, any>\n\n// export type FetchFnReturn<T extends AnyFetchFn> =\n// Awaited<ReturnType<T>> extends JsonResponse<infer R> ? R : ReturnType<T>\n\n// export type FetcherFn<T extends AnyFetchFn> = Parameters<T>[0] extends undefined\n// ? (\n// payload?: Parameters<T>['0'],\n// opts?: FetchFnCtx,\n// ) => Promise<Awaited<FetchFnReturn<T>>>\n// : (\n// payload: Parameters<T>['0'],\n// opts?: FetchFnCtx,\n// ) => Promise<Awaited<FetchFnReturn<T>>>\n\n// export type FetcherMethods<T extends AnyFetchFn> = {\n// url: string\n// fetch: (\n// init: RequestInit,\n// opts?: FetcherOptions,\n// ) => Promise<Awaited<FetchFnReturn<T>>>\n// }\n\n// export type Fetcher<T extends AnyFetchFn> = FetcherFn<T> & FetcherMethods<T>\n\nexport type CompiledFetcherFnOptions<TPayload> = {\n method: 'GET' | 'POST'\n type: 'request' | 'payload'\n payload: TPayload\n requestInit?: RequestInit\n}\n\nexport type CompiledFetcherFn<TPayload, TResponse> = {\n (opts: CompiledFetcherFnOptions<TPayload>): Promise<TResponse>\n url: string\n}\n\nexport type Fetcher<TPayload, TResponse> = (TPayload extends undefined\n ? {\n (payload?: TPayload, opts?: FetcherOptions): Promise<TResponse>\n }\n : {\n (payload: TPayload, opts?: FetcherOptions): Promise<TResponse>\n }) & {\n url: string\n}\n\nexport function createServerFn<TPayload, TResponse>(\n method: 'GET' | 'POST',\n fn: FetchFn<TPayload, TResponse>,\n): Fetcher<TPayload, TResponse> {\n // Cast the compiled function that will be injected by vinxi\n const compiledFn = fn as unknown as CompiledFetcherFn<TPayload, TResponse>\n\n console.log(\n compiledFn,\n compiledFn.toString(),\n JSON.stringify(compiledFn, null, 2),\n )\n\n invariant(\n compiledFn.url,\n `createServerFn must be called with a function that is marked with the 'use server' pragma.`,\n )\n\n return Object.assign(\n async (payload: TPayload, opts?: FetcherOptions) => {\n return compiledFn({\n method,\n type: payload instanceof Request ? 'request' : 'payload',\n payload,\n requestInit: opts?.requestInit,\n })\n },\n {\n url: fn.url!,\n },\n ) as Fetcher<TPayload, TResponse>\n}\n"],"names":[],"mappings":";;;AAEO,MAAM,aAAa;AAuEV,SAAA,eACd,QACA,IAC8B;AAE9B,QAAM,aAAa;AAEX,UAAA;AAAA,IACN;AAAA,IACA,WAAW,SAAS;AAAA,IACpB,KAAK,UAAU,YAAY,MAAM,CAAC;AAAA,EAAA;AAGpC;AAAA,IACE,WAAW;AAAA,IACX;AAAA,EAAA;AAGF,SAAO,OAAO;AAAA,IACZ,OAAO,SAAmB,SAA0B;AAClD,aAAO,WAAW;AAAA,QAChB;AAAA,QACA,MAAM,mBAAmB,UAAU,YAAY;AAAA,QAC/C;AAAA,QACA,aAAa,6BAAM;AAAA,MAAA,CACpB;AAAA,IACH;AAAA,IACA;AAAA,MACE,KAAK,GAAG;AAAA,IACV;AAAA,EAAA;AAEJ;;;"}
@@ -0,0 +1,36 @@
1
+ export declare const XTSROrigin = "x-tsr-origin";
2
+ export interface JsonResponse<TData> extends Response {
3
+ json(): Promise<TData>;
4
+ }
5
+ export type FetcherOptionsBase = {
6
+ method?: 'GET' | 'POST';
7
+ };
8
+ export type FetcherOptions = FetcherOptionsBase & {
9
+ requestInit?: RequestInit;
10
+ };
11
+ export type FetchFnCtx = {
12
+ method: 'GET' | 'POST';
13
+ request: Request;
14
+ };
15
+ export type FetchFn<TPayload, TResponse> = {
16
+ (payload: TPayload, ctx: FetchFnCtx): TResponse;
17
+ url?: string;
18
+ };
19
+ export type CompiledFetcherFnOptions<TPayload> = {
20
+ method: 'GET' | 'POST';
21
+ type: 'request' | 'payload';
22
+ payload: TPayload;
23
+ requestInit?: RequestInit;
24
+ };
25
+ export type CompiledFetcherFn<TPayload, TResponse> = {
26
+ (opts: CompiledFetcherFnOptions<TPayload>): Promise<TResponse>;
27
+ url: string;
28
+ };
29
+ export type Fetcher<TPayload, TResponse> = (TPayload extends undefined ? {
30
+ (payload?: TPayload, opts?: FetcherOptions): Promise<TResponse>;
31
+ } : {
32
+ (payload: TPayload, opts?: FetcherOptions): Promise<TResponse>;
33
+ }) & {
34
+ url: string;
35
+ };
36
+ export declare function createServerFn<TPayload, TResponse>(method: 'GET' | 'POST', fn: FetchFn<TPayload, TResponse>): Fetcher<TPayload, TResponse>;
@@ -28,6 +28,7 @@ const useRouter = require("./useRouter.cjs");
28
28
  const useRouterState = require("./useRouterState.cjs");
29
29
  const utils = require("./utils.cjs");
30
30
  const notFound = require("./not-found.cjs");
31
+ const createServerFn = require("./createServerFn.cjs");
31
32
  exports.invariant = invariant;
32
33
  exports.warning = warning;
33
34
  exports.Await = awaited.Await;
@@ -130,6 +131,8 @@ exports.CatchNotFound = notFound.CatchNotFound;
130
131
  exports.DefaultGlobalNotFound = notFound.DefaultGlobalNotFound;
131
132
  exports.isNotFound = notFound.isNotFound;
132
133
  exports.notFound = notFound.notFound;
134
+ exports.XTSROrigin = createServerFn.XTSROrigin;
135
+ exports.createServerFn = createServerFn.createServerFn;
133
136
  Object.keys(history).forEach((k) => {
134
137
  if (k !== "default" && !Object.prototype.hasOwnProperty.call(exports, k))
135
138
  Object.defineProperty(exports, k, {
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -29,3 +29,4 @@ export * from './useRouter.cjs';
29
29
  export * from './useRouterState.cjs';
30
30
  export * from './utils.cjs';
31
31
  export * from './not-found.cjs';
32
+ export * from './createServerFn.cjs';
@@ -651,7 +651,10 @@ class Router {
651
651
  return true;
652
652
  }
653
653
  if (notFound.isNotFound(err)) {
654
- this.updateMatchesWithNotFound(matches, match, err);
654
+ if (!preload) {
655
+ this.updateMatchesWithNotFound(matches, match, err);
656
+ }
657
+ return true;
655
658
  }
656
659
  return false;
657
660
  };
@@ -717,7 +720,7 @@ class Router {
717
720
  const loaderData = await loadPromise;
718
721
  if (latestPromise = checkLatest())
719
722
  return await latestPromise;
720
- if (redirects.isRedirect(loaderData)) {
723
+ if (redirects.isRedirect(loaderData) || notFound.isNotFound(loaderData)) {
721
724
  if (handleErrorAndRedirect(loaderData))
722
725
  return;
723
726
  }
@@ -1 +1 @@
1
- {"version":3,"file":"router.cjs","sources":["../../src/router.ts"],"sourcesContent":["import {\n HistoryLocation,\n HistoryState,\n RouterHistory,\n createBrowserHistory,\n createMemoryHistory,\n} from '@tanstack/history'\nimport { Store } from '@tanstack/react-store'\n\n//\n\nimport {\n AnySearchSchema,\n AnyRoute,\n AnyContext,\n AnyPathParams,\n RouteMask,\n Route,\n LoaderFnContext,\n rootRouteId,\n} from './route'\nimport {\n FullSearchSchema,\n RouteById,\n RoutePaths,\n RoutesById,\n RoutesByPath,\n} from './routeInfo'\nimport { defaultParseSearch, defaultStringifySearch } from './searchParams'\nimport {\n PickAsRequired,\n Updater,\n NonNullableUpdater,\n replaceEqualDeep,\n deepEqual,\n escapeJSON,\n functionalUpdate,\n last,\n pick,\n Timeout,\n} from './utils'\nimport { RouteComponent } from './route'\nimport { AnyRouteMatch, MatchRouteOptions, RouteMatch } from './Matches'\nimport { ParsedLocation } from './location'\nimport { SearchSerializer, SearchParser } from './searchParams'\nimport {\n BuildLocationFn,\n CommitLocationOptions,\n InjectedHtmlEntry,\n NavigateFn,\n getRouteMatch,\n} from './RouterProvider'\n\nimport {\n cleanPath,\n interpolatePath,\n joinPaths,\n matchPathname,\n parsePathname,\n resolvePath,\n trimPath,\n trimPathLeft,\n trimPathRight,\n} from './path'\nimport invariant from 'tiny-invariant'\nimport { isRedirect } from './redirects'\nimport { NotFoundError, isNotFound } from './not-found'\nimport { ResolveRelativePath, ToOptions } from './link'\nimport { NoInfer } from '@tanstack/react-store'\n// import warning from 'tiny-warning'\n\n//\n\ndeclare global {\n interface Window {\n __TSR_DEHYDRATED__?: { data: string }\n __TSR_ROUTER_CONTEXT__?: React.Context<Router<any>>\n }\n}\n\nexport interface Register {\n // router: Router\n}\n\nexport type AnyRouter = Router<AnyRoute, any>\n\nexport type RegisteredRouter = Register extends {\n router: infer TRouter extends AnyRouter\n}\n ? TRouter\n : AnyRouter\n\nexport type HydrationCtx = {\n router: DehydratedRouter\n payload: Record<string, any>\n}\n\nexport type RouterContextOptions<TRouteTree extends AnyRoute> =\n AnyContext extends TRouteTree['types']['routerContext']\n ? {\n context?: TRouteTree['types']['routerContext']\n }\n : {\n context: TRouteTree['types']['routerContext']\n }\n\nexport interface RouterOptions<\n TRouteTree extends AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n> {\n history?: RouterHistory\n stringifySearch?: SearchSerializer\n parseSearch?: SearchParser\n defaultPreload?: false | 'intent'\n defaultPreloadDelay?: number\n defaultComponent?: RouteComponent\n defaultErrorComponent?: RouteComponent\n defaultPendingComponent?: RouteComponent\n defaultPendingMs?: number\n defaultPendingMinMs?: number\n defaultStaleTime?: number\n defaultPreloadStaleTime?: number\n defaultPreloadGcTime?: number\n defaultGcTime?: number\n caseSensitive?: boolean\n routeTree?: TRouteTree\n basepath?: string\n context?: TRouteTree['types']['routerContext']\n dehydrate?: () => TDehydrated\n hydrate?: (dehydrated: TDehydrated) => void\n routeMasks?: RouteMask<TRouteTree>[]\n unmaskOnReload?: boolean\n Wrap?: (props: { children: any }) => JSX.Element\n InnerWrap?: (props: { children: any }) => JSX.Element\n /**\n * @deprecated\n * Use `notFoundComponent` instead.\n * See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.\n */\n notFoundRoute?: AnyRoute\n transformer?: RouterTransformer\n errorSerializer?: RouterErrorSerializer<TSerializedError>\n globalNotFound?: RouteComponent\n}\n\nexport interface RouterTransformer {\n stringify: (obj: unknown) => string\n parse: (str: string) => unknown\n}\nexport interface RouterErrorSerializer<TSerializedError> {\n serialize: (err: unknown) => TSerializedError\n deserialize: (err: TSerializedError) => unknown\n}\n\nexport interface RouterState<TRouteTree extends AnyRoute = AnyRoute> {\n status: 'pending' | 'idle'\n isLoading: boolean\n isTransitioning: boolean\n matches: RouteMatch<TRouteTree>[]\n pendingMatches?: RouteMatch<TRouteTree>[]\n cachedMatches: RouteMatch<TRouteTree>[]\n location: ParsedLocation<FullSearchSchema<TRouteTree>>\n resolvedLocation: ParsedLocation<FullSearchSchema<TRouteTree>>\n lastUpdated: number\n}\n\nexport type ListenerFn<TEvent extends RouterEvent> = (event: TEvent) => void\n\nexport interface BuildNextOptions {\n to?: string | number | null\n params?: true | Updater<unknown>\n search?: true | Updater<unknown>\n hash?: true | Updater<string>\n state?: true | NonNullableUpdater<HistoryState>\n mask?: {\n to?: string | number | null\n params?: true | Updater<unknown>\n search?: true | Updater<unknown>\n hash?: true | Updater<string>\n state?: true | NonNullableUpdater<HistoryState>\n unmaskOnReload?: boolean\n }\n from?: string\n}\n\nexport interface DehydratedRouterState {\n dehydratedMatches: DehydratedRouteMatch[]\n}\n\nexport type DehydratedRouteMatch = Pick<\n RouteMatch,\n 'id' | 'status' | 'updatedAt' | 'notFoundError' | 'loaderData'\n>\n\nexport interface DehydratedRouter {\n state: DehydratedRouterState\n}\n\nexport type RouterConstructorOptions<\n TRouteTree extends AnyRoute,\n TDehydrated extends Record<string, any>,\n TSerializedError extends Record<string, any>,\n> = Omit<RouterOptions<TRouteTree, TDehydrated, TSerializedError>, 'context'> &\n RouterContextOptions<TRouteTree>\n\nexport const componentTypes = [\n 'component',\n 'errorComponent',\n 'pendingComponent',\n 'notFoundComponent',\n] as const\n\nexport type RouterEvents = {\n onBeforeLoad: {\n type: 'onBeforeLoad'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n onLoad: {\n type: 'onLoad'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n onResolved: {\n type: 'onResolved'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n}\n\nexport type RouterEvent = RouterEvents[keyof RouterEvents]\n\nexport type RouterListener<TRouterEvent extends RouterEvent> = {\n eventType: TRouterEvent['type']\n fn: ListenerFn<TRouterEvent>\n}\n\nexport function createRouter<\n TRouteTree extends AnyRoute = AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n>(\n options: RouterConstructorOptions<TRouteTree, TDehydrated, TSerializedError>,\n) {\n return new Router<TRouteTree, TDehydrated, TSerializedError>(options)\n}\n\nexport class Router<\n TRouteTree extends AnyRoute = AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n> {\n // Option-independent properties\n tempLocationKey: string | undefined = `${Math.round(\n Math.random() * 10000000,\n )}`\n resetNextScroll: boolean = true\n navigateTimeout: Timeout | null = null\n latestLoadPromise: Promise<void> = Promise.resolve()\n subscribers = new Set<RouterListener<RouterEvent>>()\n injectedHtml: InjectedHtmlEntry[] = []\n dehydratedData?: TDehydrated\n\n // Must build in constructor\n __store!: Store<RouterState<TRouteTree>>\n options!: PickAsRequired<\n Omit<\n RouterOptions<TRouteTree, TDehydrated, TSerializedError>,\n 'transformer'\n > & {\n transformer: RouterTransformer\n },\n 'stringifySearch' | 'parseSearch' | 'context'\n >\n history!: RouterHistory\n latestLocation!: ParsedLocation\n basepath!: string\n routeTree!: TRouteTree\n routesById!: RoutesById<TRouteTree>\n routesByPath!: RoutesByPath<TRouteTree>\n flatRoutes!: AnyRoute[]\n\n /**\n * @deprecated Use the `createRouter` function instead\n */\n constructor(\n options: RouterConstructorOptions<\n TRouteTree,\n TDehydrated,\n TSerializedError\n >,\n ) {\n this.update({\n defaultPreloadDelay: 50,\n defaultPendingMs: 1000,\n defaultPendingMinMs: 500,\n context: undefined!,\n ...options,\n stringifySearch: options?.stringifySearch ?? defaultStringifySearch,\n parseSearch: options?.parseSearch ?? defaultParseSearch,\n transformer: options?.transformer ?? JSON,\n })\n }\n\n // These are default implementations that can optionally be overridden\n // by the router provider once rendered. We provide these so that the\n // router can be used in a non-react environment if necessary\n startReactTransition: (fn: () => void) => void = (fn) => fn()\n\n update = (\n newOptions: RouterConstructorOptions<\n TRouteTree,\n TDehydrated,\n TSerializedError\n >,\n ) => {\n if (newOptions.notFoundRoute) {\n console.warn(\n 'The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.',\n )\n }\n\n const previousOptions = this.options\n this.options = {\n ...this.options,\n ...newOptions,\n }\n\n if (\n !this.basepath ||\n (newOptions.basepath && newOptions.basepath !== previousOptions.basepath)\n ) {\n if (\n newOptions.basepath === undefined ||\n newOptions.basepath === '' ||\n newOptions.basepath === '/'\n ) {\n this.basepath = '/'\n } else {\n this.basepath = `/${trimPath(newOptions.basepath)}`\n }\n }\n\n if (\n !this.history ||\n (this.options.history && this.options.history !== this.history)\n ) {\n this.history =\n this.options.history ??\n (typeof document !== 'undefined'\n ? createBrowserHistory()\n : createMemoryHistory({\n initialEntries: [this.options.basepath || '/'],\n }))\n this.latestLocation = this.parseLocation()\n }\n\n if (this.options.routeTree !== this.routeTree) {\n this.routeTree = this.options.routeTree as TRouteTree\n this.buildRouteTree()\n }\n\n if (!this.__store) {\n this.__store = new Store(getInitialRouterState(this.latestLocation), {\n onUpdate: () => {\n this.__store.state = {\n ...this.state,\n status:\n this.state.isTransitioning || this.state.isLoading\n ? 'pending'\n : 'idle',\n }\n },\n })\n }\n }\n\n get state() {\n return this.__store.state\n }\n\n buildRouteTree = () => {\n this.routesById = {} as RoutesById<TRouteTree>\n this.routesByPath = {} as RoutesByPath<TRouteTree>\n\n const notFoundRoute = this.options.notFoundRoute\n if (notFoundRoute) {\n notFoundRoute.init({ originalIndex: 99999999999 })\n ;(this.routesById as any)[notFoundRoute.id] = notFoundRoute\n }\n\n const recurseRoutes = (childRoutes: AnyRoute[]) => {\n childRoutes.forEach((childRoute, i) => {\n childRoute.init({ originalIndex: i })\n\n const existingRoute = (this.routesById as any)[childRoute.id]\n\n invariant(\n !existingRoute,\n `Duplicate routes found with id: ${String(childRoute.id)}`,\n )\n ;(this.routesById as any)[childRoute.id] = childRoute\n\n if (!childRoute.isRoot && childRoute.path) {\n const trimmedFullPath = trimPathRight(childRoute.fullPath)\n if (\n !(this.routesByPath as any)[trimmedFullPath] ||\n childRoute.fullPath.endsWith('/')\n ) {\n ;(this.routesByPath as any)[trimmedFullPath] = childRoute\n }\n }\n\n const children = childRoute.children as Route[]\n\n if (children?.length) {\n recurseRoutes(children)\n }\n })\n }\n\n recurseRoutes([this.routeTree])\n\n const scoredRoutes: {\n child: AnyRoute\n trimmed: string\n parsed: ReturnType<typeof parsePathname>\n index: number\n scores: number[]\n }[] = []\n\n ;(Object.values(this.routesById) as AnyRoute[]).forEach((d, i) => {\n if (d.isRoot || !d.path) {\n return\n }\n\n const trimmed = trimPathLeft(d.fullPath)\n const parsed = parsePathname(trimmed)\n\n while (parsed.length > 1 && parsed[0]?.value === '/') {\n parsed.shift()\n }\n\n const scores = parsed.map((d) => {\n if (d.value === '/') {\n return 0.75\n }\n\n if (d.type === 'param') {\n return 0.5\n }\n\n if (d.type === 'wildcard') {\n return 0.25\n }\n\n return 1\n })\n\n scoredRoutes.push({ child: d, trimmed, parsed, index: i, scores })\n })\n\n this.flatRoutes = scoredRoutes\n .sort((a, b) => {\n const minLength = Math.min(a.scores.length, b.scores.length)\n\n // Sort by min available score\n for (let i = 0; i < minLength; i++) {\n if (a.scores[i] !== b.scores[i]) {\n return b.scores[i]! - a.scores[i]!\n }\n }\n\n // Sort by length of score\n if (a.scores.length !== b.scores.length) {\n return b.scores.length - a.scores.length\n }\n\n // Sort by min available parsed value\n for (let i = 0; i < minLength; i++) {\n if (a.parsed[i]!.value !== b.parsed[i]!.value) {\n return a.parsed[i]!.value! > b.parsed[i]!.value! ? 1 : -1\n }\n }\n\n // Sort by original index\n return a.index - b.index\n })\n .map((d, i) => {\n d.child.rank = i\n return d.child\n })\n }\n\n subscribe = <TType extends keyof RouterEvents>(\n eventType: TType,\n fn: ListenerFn<RouterEvents[TType]>,\n ) => {\n const listener: RouterListener<any> = {\n eventType,\n fn,\n }\n\n this.subscribers.add(listener)\n\n return () => {\n this.subscribers.delete(listener)\n }\n }\n\n emit = (routerEvent: RouterEvent) => {\n this.subscribers.forEach((listener) => {\n if (listener.eventType === routerEvent.type) {\n listener.fn(routerEvent)\n }\n })\n }\n\n checkLatest = (promise: Promise<void>): undefined | Promise<void> => {\n return this.latestLoadPromise !== promise\n ? this.latestLoadPromise\n : undefined\n }\n\n parseLocation = (\n previousLocation?: ParsedLocation,\n ): ParsedLocation<FullSearchSchema<TRouteTree>> => {\n const parse = ({\n pathname,\n search,\n hash,\n state,\n }: HistoryLocation): ParsedLocation<FullSearchSchema<TRouteTree>> => {\n const parsedSearch = this.options.parseSearch(search)\n const searchStr = this.options.stringifySearch(parsedSearch)\n\n return {\n pathname: pathname,\n searchStr,\n search: replaceEqualDeep(previousLocation?.search, parsedSearch) as any,\n hash: hash.split('#').reverse()[0] ?? '',\n href: `${pathname}${searchStr}${hash}`,\n state: replaceEqualDeep(previousLocation?.state, state) as HistoryState,\n }\n }\n\n const location = parse(this.history.location)\n\n let { __tempLocation, __tempKey } = location.state\n\n if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {\n // Sync up the location keys\n const parsedTempLocation = parse(__tempLocation) as any\n parsedTempLocation.state.key = location.state.key\n\n delete parsedTempLocation.state.__tempLocation\n\n return {\n ...parsedTempLocation,\n maskedLocation: location,\n }\n }\n\n return location\n }\n\n resolvePathWithBase = (from: string, path: string) => {\n return resolvePath(this.basepath!, from, cleanPath(path))\n }\n\n get looseRoutesById() {\n return this.routesById as Record<string, AnyRoute>\n }\n\n matchRoutes = <TRouteTree extends AnyRoute>(\n pathname: string,\n locationSearch: AnySearchSchema,\n opts?: { throwOnError?: boolean; debug?: boolean },\n ): RouteMatch<TRouteTree>[] => {\n let routeParams: Record<string, string> = {}\n\n let foundRoute = this.flatRoutes.find((route) => {\n const matchedParams = matchPathname(\n this.basepath,\n trimPathRight(pathname),\n {\n to: route.fullPath,\n caseSensitive:\n route.options.caseSensitive ?? this.options.caseSensitive,\n fuzzy: true,\n },\n )\n\n if (matchedParams) {\n routeParams = matchedParams\n return true\n }\n\n return false\n })\n\n let routeCursor: AnyRoute =\n foundRoute || (this.routesById as any)['__root__']\n\n let matchedRoutes: AnyRoute[] = [routeCursor]\n\n let isGlobalNotFound = false\n\n // Check to see if the route needs a 404 entry\n if (\n // If we found a route, and it's not an index route and we have left over path\n foundRoute\n ? foundRoute.path !== '/' && routeParams['**']\n : // Or if we didn't find a route and we have left over path\n trimPathRight(pathname)\n ) {\n // If the user has defined an (old) 404 route, use it\n if (this.options.notFoundRoute) {\n matchedRoutes.push(this.options.notFoundRoute)\n } else {\n // If there is no routes found during path matching\n isGlobalNotFound = true\n }\n }\n\n while (routeCursor?.parentRoute) {\n routeCursor = routeCursor.parentRoute\n if (routeCursor) matchedRoutes.unshift(routeCursor)\n }\n\n // Existing matches are matches that are already loaded along with\n // pending matches that are still loading\n\n const parseErrors = matchedRoutes.map((route) => {\n let parsedParamsError\n\n if (route.options.parseParams) {\n try {\n const parsedParams = route.options.parseParams(routeParams)\n // Add the parsed params to the accumulated params bag\n Object.assign(routeParams, parsedParams)\n } catch (err: any) {\n parsedParamsError = new PathParamError(err.message, {\n cause: err,\n })\n\n if (opts?.throwOnError) {\n throw parsedParamsError\n }\n\n return parsedParamsError\n }\n }\n\n return\n })\n\n const matches: AnyRouteMatch[] = []\n\n matchedRoutes.forEach((route, index) => {\n // Take each matched route and resolve + validate its search params\n // This has to happen serially because each route's search params\n // can depend on the parent route's search params\n // It must also happen before we create the match so that we can\n // pass the search params to the route's potential key function\n // which is used to uniquely identify the route match in state\n\n const parentMatch = matches[index - 1]\n\n const [preMatchSearch, searchError]: [Record<string, any>, any] = (() => {\n // Validate the search params and stabilize them\n const parentSearch = parentMatch?.search ?? locationSearch\n\n try {\n const validator =\n typeof route.options.validateSearch === 'object'\n ? route.options.validateSearch.parse\n : route.options.validateSearch\n\n let search = validator?.(parentSearch) ?? {}\n\n return [\n {\n ...parentSearch,\n ...search,\n },\n undefined,\n ]\n } catch (err: any) {\n const searchError = new SearchParamError(err.message, {\n cause: err,\n })\n\n if (opts?.throwOnError) {\n throw searchError\n }\n\n return [parentSearch, searchError]\n }\n })()\n\n // This is where we need to call route.options.loaderDeps() to get any additional\n // deps that the route's loader function might need to run. We need to do this\n // before we create the match so that we can pass the deps to the route's\n // potential key function which is used to uniquely identify the route match in state\n\n const loaderDeps =\n route.options.loaderDeps?.({\n search: preMatchSearch,\n }) ?? ''\n\n const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : ''\n\n const interpolatedPath = interpolatePath({\n path: route.fullPath,\n params: routeParams,\n })\n const matchId =\n interpolatePath({\n path: route.id,\n params: routeParams,\n leaveWildcards: true,\n }) + loaderDepsHash\n\n // Waste not, want not. If we already have a match for this route,\n // reuse it. This is important for layout routes, which might stick\n // around between navigation actions that only change leaf routes.\n const existingMatch = getRouteMatch(this.state, matchId)\n\n const cause = this.state.matches.find((d) => d.id === matchId)\n ? 'stay'\n : 'enter'\n\n const match: AnyRouteMatch = existingMatch\n ? {\n ...existingMatch,\n cause,\n notFoundError:\n isGlobalNotFound && route.id === rootRouteId\n ? { global: true }\n : undefined,\n }\n : {\n id: matchId,\n routeId: route.id,\n params: routeParams,\n pathname: joinPaths([this.basepath, interpolatedPath]),\n updatedAt: Date.now(),\n search: {} as any,\n searchError: undefined,\n status: 'pending',\n showPending: false,\n isFetching: false,\n error: undefined,\n paramsError: parseErrors[index],\n loadPromise: Promise.resolve(),\n routeContext: undefined!,\n context: undefined!,\n abortController: new AbortController(),\n fetchCount: 0,\n cause,\n loaderDeps,\n invalid: false,\n preload: false,\n notFoundError:\n isGlobalNotFound && route.id === rootRouteId\n ? { global: true }\n : undefined,\n links: route.options.links?.(),\n scripts: route.options.scripts?.(),\n staticData: route.options.staticData || {},\n }\n\n // Regardless of whether we're reusing an existing match or creating\n // a new one, we need to update the match's search params\n match.search = replaceEqualDeep(match.search, preMatchSearch)\n // And also update the searchError if there is one\n match.searchError = searchError\n\n matches.push(match)\n })\n\n return matches as any\n }\n\n cancelMatch = (id: string) => {\n getRouteMatch(this.state, id)?.abortController?.abort()\n }\n\n cancelMatches = () => {\n this.state.pendingMatches?.forEach((match) => {\n this.cancelMatch(match.id)\n })\n }\n\n buildLocation: BuildLocationFn<TRouteTree> = (opts) => {\n const build = (\n dest: BuildNextOptions & {\n unmaskOnReload?: boolean\n } = {},\n matches?: AnyRouteMatch[],\n ): ParsedLocation => {\n const relevantMatches = this.state.pendingMatches || this.state.matches\n const fromSearch =\n relevantMatches[relevantMatches.length - 1]?.search ||\n this.latestLocation.search\n\n let pathname = this.resolvePathWithBase(\n dest.from ?? this.latestLocation.pathname,\n `${dest.to ?? ''}`,\n )\n\n const fromMatches = this.matchRoutes(\n this.latestLocation.pathname,\n fromSearch,\n )\n const stayingMatches = matches?.filter((d) =>\n fromMatches?.find((e) => e.routeId === d.routeId),\n )\n\n const prevParams = { ...last(fromMatches)?.params }\n\n let nextParams =\n (dest.params ?? true) === true\n ? prevParams\n : functionalUpdate(dest.params!, prevParams)\n\n if (nextParams) {\n matches\n ?.map((d) => this.looseRoutesById[d.routeId]!.options.stringifyParams)\n .filter(Boolean)\n .forEach((fn) => {\n nextParams = { ...nextParams!, ...fn!(nextParams!) }\n })\n }\n\n pathname = interpolatePath({\n path: pathname,\n params: nextParams ?? {},\n leaveWildcards: false,\n leaveParams: opts.leaveParams,\n })\n\n const preSearchFilters =\n stayingMatches\n ?.map(\n (match) =>\n this.looseRoutesById[match.routeId]!.options.preSearchFilters ??\n [],\n )\n .flat()\n .filter(Boolean) ?? []\n\n const postSearchFilters =\n stayingMatches\n ?.map(\n (match) =>\n this.looseRoutesById[match.routeId]!.options.postSearchFilters ??\n [],\n )\n .flat()\n .filter(Boolean) ?? []\n\n // Pre filters first\n const preFilteredSearch = preSearchFilters?.length\n ? preSearchFilters?.reduce(\n (prev, next) => next(prev) as any,\n fromSearch,\n )\n : fromSearch\n\n // Then the link/navigate function\n const destSearch =\n dest.search === true\n ? preFilteredSearch // Preserve resolvedFrom true\n : dest.search\n ? functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater\n : preSearchFilters?.length\n ? preFilteredSearch // Preserve resolvedFrom filters\n : {}\n\n // Then post filters\n const postFilteredSearch = postSearchFilters?.length\n ? postSearchFilters.reduce((prev, next) => next(prev), destSearch)\n : destSearch\n\n const search = replaceEqualDeep(fromSearch, postFilteredSearch)\n\n const searchStr = this.options.stringifySearch(search)\n\n const hash =\n dest.hash === true\n ? this.latestLocation.hash\n : dest.hash\n ? functionalUpdate(dest.hash!, this.latestLocation.hash)\n : undefined\n\n const hashStr = hash ? `#${hash}` : ''\n\n let nextState =\n dest.state === true\n ? this.latestLocation.state\n : dest.state\n ? functionalUpdate(dest.state, this.latestLocation.state)\n : {}\n\n nextState = replaceEqualDeep(this.latestLocation.state, nextState)\n\n return {\n pathname,\n search,\n searchStr,\n state: nextState as any,\n hash: hash ?? '',\n href: `${pathname}${searchStr}${hashStr}`,\n unmaskOnReload: dest.unmaskOnReload,\n }\n }\n\n const buildWithMatches = (\n dest: BuildNextOptions = {},\n maskedDest?: BuildNextOptions,\n ) => {\n let next = build(dest)\n let maskedNext = maskedDest ? build(maskedDest) : undefined\n\n if (!maskedNext) {\n let params = {}\n\n let foundMask = this.options.routeMasks?.find((d) => {\n const match = matchPathname(this.basepath, next.pathname, {\n to: d.from,\n caseSensitive: false,\n fuzzy: false,\n })\n\n if (match) {\n params = match\n return true\n }\n\n return false\n })\n\n if (foundMask) {\n maskedDest = {\n ...pick(opts, ['from']),\n ...foundMask,\n params,\n }\n maskedNext = build(maskedDest)\n }\n }\n\n const nextMatches = this.matchRoutes(next.pathname, next.search)\n const maskedMatches = maskedNext\n ? this.matchRoutes(maskedNext.pathname, maskedNext.search)\n : undefined\n const maskedFinal = maskedNext\n ? build(maskedDest, maskedMatches)\n : undefined\n\n const final = build(dest, nextMatches)\n\n if (maskedFinal) {\n final.maskedLocation = maskedFinal\n }\n\n return final\n }\n\n if (opts.mask) {\n return buildWithMatches(opts, {\n ...pick(opts, ['from']),\n ...opts.mask,\n })\n }\n\n return buildWithMatches(opts)\n }\n\n commitLocation = async ({\n startTransition,\n ...next\n }: ParsedLocation & CommitLocationOptions) => {\n if (this.navigateTimeout) clearTimeout(this.navigateTimeout)\n\n const isSameUrl = this.latestLocation.href === next.href\n\n // If the next urls are the same and we're not replacing,\n // do nothing\n if (!isSameUrl || !next.replace) {\n let { maskedLocation, ...nextHistory } = next\n\n if (maskedLocation) {\n nextHistory = {\n ...maskedLocation,\n state: {\n ...maskedLocation.state,\n __tempKey: undefined,\n __tempLocation: {\n ...nextHistory,\n search: nextHistory.searchStr,\n state: {\n ...nextHistory.state,\n __tempKey: undefined!,\n __tempLocation: undefined!,\n key: undefined!,\n },\n },\n },\n }\n\n if (\n nextHistory.unmaskOnReload ??\n this.options.unmaskOnReload ??\n false\n ) {\n nextHistory.state.__tempKey = this.tempLocationKey\n }\n }\n\n const apply = () => {\n this.history[next.replace ? 'replace' : 'push'](\n nextHistory.href,\n nextHistory.state,\n )\n }\n\n if (startTransition ?? true) {\n this.startReactTransition(apply)\n } else {\n apply()\n }\n }\n\n this.resetNextScroll = next.resetScroll ?? true\n\n return this.latestLoadPromise\n }\n\n buildAndCommitLocation = ({\n replace,\n resetScroll,\n startTransition,\n ...rest\n }: BuildNextOptions & CommitLocationOptions = {}) => {\n const location = this.buildLocation(rest as any)\n return this.commitLocation({\n ...location,\n startTransition,\n replace,\n resetScroll,\n })\n }\n\n navigate: NavigateFn<TRouteTree> = ({ from, to, ...rest }) => {\n // If this link simply reloads the current route,\n // make sure it has a new key so it will trigger a data refresh\n\n // If this `to` is a valid external URL, return\n // null for LinkUtils\n const toString = String(to)\n // const fromString = from !== undefined ? String(from) : from\n let isExternal\n\n try {\n new URL(`${toString}`)\n isExternal = true\n } catch (e) {}\n\n invariant(\n !isExternal,\n 'Attempting to navigate to external url with this.navigate!',\n )\n\n return this.buildAndCommitLocation({\n ...rest,\n from,\n to,\n // to: toString,\n })\n }\n\n loadMatches = async ({\n checkLatest,\n matches,\n preload,\n }: {\n checkLatest: () => Promise<void> | undefined\n matches: AnyRouteMatch[]\n preload?: boolean\n }): Promise<RouteMatch[]> => {\n let latestPromise\n let firstBadMatchIndex: number | undefined\n\n const updateMatch = (match: AnyRouteMatch) => {\n // const isPreload = this.state.cachedMatches.find((d) => d.id === match.id)\n const isPending = this.state.pendingMatches?.find(\n (d) => d.id === match.id,\n )\n\n const isMatched = this.state.matches.find((d) => d.id === match.id)\n\n const matchesKey = isPending\n ? 'pendingMatches'\n : isMatched\n ? 'matches'\n : 'cachedMatches'\n\n this.__store.setState((s) => ({\n ...s,\n [matchesKey]: s[matchesKey]?.map((d) =>\n d.id === match.id ? match : d,\n ),\n }))\n }\n\n // Check each match middleware to see if the route can be accessed\n try {\n for (let [index, match] of matches.entries()) {\n const parentMatch = matches[index - 1]\n const route = this.looseRoutesById[match.routeId]!\n const abortController = new AbortController()\n\n const handleErrorAndRedirect = (err: any, code: string) => {\n err.routerCode = code\n firstBadMatchIndex = firstBadMatchIndex ?? index\n\n if (isRedirect(err)) {\n throw err\n }\n\n if (isNotFound(err)) {\n this.updateMatchesWithNotFound(matches, match, err)\n }\n\n try {\n route.options.onError?.(err)\n } catch (errorHandlerErr) {\n err = errorHandlerErr\n\n if (isRedirect(errorHandlerErr)) {\n throw errorHandlerErr\n }\n }\n\n matches[index] = match = {\n ...match,\n error: err,\n status: 'error',\n updatedAt: Date.now(),\n abortController: new AbortController(),\n }\n }\n\n try {\n if (match.paramsError) {\n handleErrorAndRedirect(match.paramsError, 'PARSE_PARAMS')\n }\n\n if (match.searchError) {\n handleErrorAndRedirect(match.searchError, 'VALIDATE_SEARCH')\n }\n\n const parentContext =\n parentMatch?.context ?? this.options.context ?? {}\n\n const pendingMs =\n route.options.pendingMs ?? this.options.defaultPendingMs\n const pendingPromise =\n typeof pendingMs === 'number' && pendingMs <= 0\n ? Promise.resolve()\n : new Promise<void>((r) => setTimeout(r, pendingMs))\n\n const beforeLoadContext =\n (await route.options.beforeLoad?.({\n search: match.search,\n abortController,\n params: match.params,\n preload: !!preload,\n context: parentContext,\n location: this.state.location,\n // TOOD: just expose state and router, etc\n navigate: (opts) =>\n this.navigate({ ...opts, from: match.pathname } as any),\n buildLocation: this.buildLocation,\n cause: preload ? 'preload' : match.cause,\n })) ?? ({} as any)\n\n if (isRedirect(beforeLoadContext)) {\n throw beforeLoadContext\n }\n\n const context = {\n ...parentContext,\n ...beforeLoadContext,\n }\n\n matches[index] = match = {\n ...match,\n routeContext: replaceEqualDeep(\n match.routeContext,\n beforeLoadContext,\n ),\n context: replaceEqualDeep(match.context, context),\n abortController,\n pendingPromise,\n }\n } catch (err) {\n handleErrorAndRedirect(err, 'BEFORE_LOAD')\n break\n }\n }\n } catch (err) {\n if (isRedirect(err)) {\n if (!preload) this.navigate(err as any)\n return matches\n }\n\n throw err\n }\n\n const validResolvedMatches = matches.slice(0, firstBadMatchIndex)\n const matchPromises: Promise<any>[] = []\n\n validResolvedMatches.forEach((match, index) => {\n matchPromises.push(\n new Promise<void>(async (resolve) => {\n const parentMatchPromise = matchPromises[index - 1]\n const route = this.looseRoutesById[match.routeId]!\n\n const handleErrorAndRedirect = (err: any) => {\n if (isRedirect(err)) {\n if (!preload) {\n this.navigate(err as any)\n }\n return true\n }\n\n if (isNotFound(err)) {\n this.updateMatchesWithNotFound(matches, match, err)\n }\n\n return false\n }\n\n let loadPromise: Promise<void> | undefined\n\n matches[index] = match = {\n ...match,\n showPending: false,\n }\n\n let didShowPending = false\n const pendingMs =\n route.options.pendingMs ?? this.options.defaultPendingMs\n const pendingMinMs =\n route.options.pendingMinMs ?? this.options.defaultPendingMinMs\n const shouldPending =\n !preload &&\n typeof pendingMs === 'number' &&\n (route.options.pendingComponent ??\n this.options.defaultPendingComponent)\n\n const loaderContext: LoaderFnContext = {\n params: match.params,\n deps: match.loaderDeps,\n preload: !!preload,\n parentMatchPromise,\n abortController: match.abortController,\n context: match.context,\n location: this.state.location,\n navigate: (opts) =>\n this.navigate({ ...opts, from: match.pathname } as any),\n cause: preload ? 'preload' : match.cause,\n }\n\n const fetch = async () => {\n if (match.isFetching) {\n loadPromise = getRouteMatch(this.state, match.id)?.loadPromise\n } else {\n // If the user doesn't want the route to reload, just\n // resolve with the existing loader data\n\n if (match.fetchCount && match.status === 'success') {\n resolve()\n }\n\n // Otherwise, load the route\n matches[index] = match = {\n ...match,\n isFetching: true,\n fetchCount: match.fetchCount + 1,\n }\n\n const lazyPromise =\n route.lazyFn?.().then((lazyRoute) => {\n Object.assign(route.options, lazyRoute.options)\n }) || Promise.resolve()\n\n // If for some reason lazy resolves more lazy components...\n // We'll wait for that before pre attempt to preload any\n // components themselves.\n const componentsPromise = lazyPromise.then(() =>\n Promise.all(\n componentTypes.map(async (type) => {\n const component = route.options[type]\n\n if ((component as any)?.preload) {\n await (component as any).preload()\n }\n }),\n ),\n )\n\n // Kick off the loader!\n const loaderPromise = route.options.loader?.(loaderContext)\n\n loadPromise = Promise.all([\n componentsPromise,\n loaderPromise,\n lazyPromise,\n ]).then((d) => d[1])\n }\n\n matches[index] = match = {\n ...match,\n loadPromise,\n }\n\n updateMatch(match)\n\n try {\n const loaderData = await loadPromise\n if ((latestPromise = checkLatest())) return await latestPromise\n\n if (isRedirect(loaderData)) {\n if (handleErrorAndRedirect(loaderData)) return\n }\n\n if (didShowPending && pendingMinMs) {\n await new Promise((r) => setTimeout(r, pendingMinMs))\n }\n\n if ((latestPromise = checkLatest())) return await latestPromise\n\n const meta = route.options.meta?.({\n loaderData,\n })\n\n matches[index] = match = {\n ...match,\n error: undefined,\n status: 'success',\n isFetching: false,\n updatedAt: Date.now(),\n loaderData,\n loadPromise: undefined,\n meta,\n }\n } catch (error) {\n if ((latestPromise = checkLatest())) return await latestPromise\n if (handleErrorAndRedirect(error)) return\n\n try {\n route.options.onError?.(error)\n } catch (onErrorError) {\n error = onErrorError\n if (handleErrorAndRedirect(onErrorError)) return\n }\n\n matches[index] = match = {\n ...match,\n error,\n status: 'error',\n isFetching: false,\n }\n }\n\n updateMatch(match)\n }\n\n // This is where all of the stale-while-revalidate magic happens\n const age = Date.now() - match.updatedAt\n\n let staleAge = preload\n ? route.options.preloadStaleTime ??\n this.options.defaultPreloadStaleTime ??\n 30_000 // 30 seconds for preloads by default\n : route.options.staleTime ?? this.options.defaultStaleTime ?? 0\n\n // Default to reloading the route all the time\n let shouldReload\n\n const shouldReloadOption = route.options.shouldReload\n\n // Allow shouldReload to get the last say,\n // if provided.\n shouldReload =\n typeof shouldReloadOption === 'function'\n ? shouldReloadOption(loaderContext)\n : shouldReloadOption\n\n matches[index] = match = {\n ...match,\n preload:\n !!preload && !this.state.matches.find((d) => d.id === match.id),\n }\n\n if (match.status !== 'success') {\n // If we need to potentially show the pending component,\n // start a timer to show it after the pendingMs\n if (shouldPending) {\n match.pendingPromise?.then(async () => {\n if ((latestPromise = checkLatest())) return latestPromise\n\n didShowPending = true\n matches[index] = match = {\n ...match,\n showPending: true,\n }\n\n updateMatch(match)\n resolve()\n })\n }\n\n // Critical Fetching, we need to await\n await fetch()\n } else if (match.invalid || (shouldReload ?? age > staleAge)) {\n // Background Fetching, no need to wait\n fetch()\n }\n\n resolve()\n }),\n )\n })\n\n await Promise.all(matchPromises)\n return matches\n }\n\n invalidate = () => {\n const invalidate = (d: any) => ({\n ...d,\n invalid: true,\n })\n\n this.__store.setState((s) => ({\n ...s,\n matches: s.matches.map(invalidate),\n cachedMatches: s.cachedMatches.map(invalidate),\n pendingMatches: s.pendingMatches?.map(invalidate),\n }))\n\n this.load()\n }\n\n load = async (): Promise<void> => {\n const promise = new Promise<void>(async (resolve, reject) => {\n const next = this.latestLocation\n const prevLocation = this.state.resolvedLocation\n const pathDidChange = prevLocation!.href !== next.href\n let latestPromise: Promise<void> | undefined | null\n\n // Cancel any pending matches\n this.cancelMatches()\n\n this.emit({\n type: 'onBeforeLoad',\n fromLocation: prevLocation,\n toLocation: next,\n pathChanged: pathDidChange,\n })\n\n let pendingMatches!: RouteMatch<any, any>[]\n const previousMatches = this.state.matches\n\n this.__store.batch(() => {\n this.cleanCache()\n\n // Match the routes\n pendingMatches = this.matchRoutes(next.pathname, next.search, {\n debug: true,\n })\n\n // Ingest the new matches\n // If a cached moved to pendingMatches, remove it from cachedMatches\n this.__store.setState((s) => ({\n ...s,\n isLoading: true,\n location: next,\n pendingMatches,\n cachedMatches: s.cachedMatches.filter((d) => {\n return !pendingMatches.find((e) => e.id === d.id)\n }),\n }))\n })\n\n try {\n try {\n // Load the matches\n await this.loadMatches({\n matches: pendingMatches,\n checkLatest: () => this.checkLatest(promise),\n })\n } catch (err) {\n // swallow this error, since we'll display the\n // errors on the route components\n }\n\n // Only apply the latest transition\n if ((latestPromise = this.checkLatest(promise))) {\n return latestPromise\n }\n\n const exitingMatches = previousMatches.filter(\n (match) => !pendingMatches.find((d) => d.id === match.id),\n )\n const enteringMatches = pendingMatches.filter(\n (match) => !previousMatches.find((d) => d.id === match.id),\n )\n const stayingMatches = previousMatches.filter((match) =>\n pendingMatches.find((d) => d.id === match.id),\n )\n\n // Commit the pending matches. If a previous match was\n // removed, place it in the cachedMatches\n this.__store.batch(() => {\n this.__store.setState((s) => ({\n ...s,\n isLoading: false,\n matches: s.pendingMatches!,\n pendingMatches: undefined,\n cachedMatches: [\n ...s.cachedMatches,\n ...exitingMatches.filter((d) => d.status !== 'error'),\n ],\n }))\n this.cleanCache()\n })\n\n //\n ;(\n [\n [exitingMatches, 'onLeave'],\n [enteringMatches, 'onEnter'],\n [stayingMatches, 'onStay'],\n ] as const\n ).forEach(([matches, hook]) => {\n matches.forEach((match) => {\n this.looseRoutesById[match.routeId]!.options[hook]?.(match)\n })\n })\n\n this.emit({\n type: 'onLoad',\n fromLocation: prevLocation,\n toLocation: next,\n pathChanged: pathDidChange,\n })\n\n resolve()\n } catch (err) {\n // Only apply the latest transition\n if ((latestPromise = this.checkLatest(promise))) {\n return latestPromise\n }\n\n reject(err)\n }\n })\n\n this.latestLoadPromise = promise\n\n return this.latestLoadPromise\n }\n\n cleanCache = () => {\n // This is where all of the garbage collection magic happens\n this.__store.setState((s) => {\n return {\n ...s,\n cachedMatches: s.cachedMatches.filter((d) => {\n const route = this.looseRoutesById[d.routeId]!\n\n if (!route.options.loader) {\n return false\n }\n\n // If the route was preloaded, use the preloadGcTime\n // otherwise, use the gcTime\n const gcTime =\n (d.preload\n ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime\n : route.options.gcTime ?? this.options.defaultGcTime) ??\n 5 * 60 * 1000\n\n return d.status !== 'error' && Date.now() - d.updatedAt < gcTime\n }),\n }\n })\n }\n\n preloadRoute = async (\n navigateOpts: ToOptions<TRouteTree> = this.state.location as any,\n ) => {\n let next = this.buildLocation(navigateOpts as any)\n\n let matches = this.matchRoutes(next.pathname, next.search, {\n throwOnError: true,\n })\n\n const loadedMatchIds = Object.fromEntries(\n [\n ...this.state.matches,\n ...(this.state.pendingMatches ?? []),\n ...this.state.cachedMatches,\n ]?.map((d) => [d.id, true]),\n )\n\n this.__store.batch(() => {\n matches.forEach((match) => {\n if (!loadedMatchIds[match.id]) {\n this.__store.setState((s) => ({\n ...s,\n cachedMatches: [...(s.cachedMatches as any), match],\n }))\n }\n })\n })\n\n matches = await this.loadMatches({\n matches,\n preload: true,\n checkLatest: () => undefined,\n })\n\n return matches\n }\n\n matchRoute = <\n TFrom extends RoutePaths<TRouteTree> = '/',\n TTo extends string = '',\n TResolved = ResolveRelativePath<TFrom, NoInfer<TTo>>,\n >(\n location: ToOptions<TRouteTree, TFrom, TTo>,\n opts?: MatchRouteOptions,\n ): false | RouteById<TRouteTree, TResolved>['types']['allParams'] => {\n const matchLocation = {\n ...location,\n to: location.to\n ? this.resolvePathWithBase((location.from || '') as string, location.to)\n : undefined,\n params: location.params || {},\n leaveParams: true,\n }\n const next = this.buildLocation(matchLocation as any)\n\n if (opts?.pending && this.state.status !== 'pending') {\n return false\n }\n\n const baseLocation = opts?.pending\n ? this.latestLocation\n : this.state.resolvedLocation\n\n if (!baseLocation) {\n return false\n }\n const match = matchPathname(this.basepath, baseLocation.pathname, {\n ...opts,\n to: next.pathname,\n }) as any\n\n if (!match) {\n return false\n }\n if (location.params) {\n if (!deepEqual(match, location.params, true)) {\n return false\n }\n }\n\n if (match && (opts?.includeSearch ?? true)) {\n return deepEqual(baseLocation.search, next.search, true) ? match : false\n }\n\n return match\n }\n\n injectHtml = async (html: string | (() => Promise<string> | string)) => {\n this.injectedHtml.push(html)\n }\n\n dehydrateData = <T>(key: any, getData: T | (() => Promise<T> | T)) => {\n if (typeof document === 'undefined') {\n const strKey = typeof key === 'string' ? key : JSON.stringify(key)\n\n this.injectHtml(async () => {\n const id = `__TSR_DEHYDRATED__${strKey}`\n const data =\n typeof getData === 'function' ? await (getData as any)() : getData\n return `<script id='${id}' suppressHydrationWarning>window[\"__TSR_DEHYDRATED__${escapeJSON(\n strKey,\n )}\"] = ${JSON.stringify(this.options.transformer.stringify(data))}\n ;(() => {\n var el = document.getElementById('${id}')\n el.parentElement.removeChild(el)\n })()\n </script>`\n })\n\n return () => this.hydrateData<T>(key)\n }\n\n return () => undefined\n }\n\n hydrateData = <T extends any = unknown>(key: any) => {\n if (typeof document !== 'undefined') {\n const strKey = typeof key === 'string' ? key : JSON.stringify(key)\n\n return this.options.transformer.parse(\n window[`__TSR_DEHYDRATED__${strKey}` as any] as unknown as string,\n ) as T\n }\n\n return undefined\n }\n\n dehydrate = (): DehydratedRouter => {\n const pickError =\n this.options.errorSerializer?.serialize ?? defaultSerializeError\n\n return {\n state: {\n dehydratedMatches: this.state.matches.map((d) => ({\n ...pick(d, [\n 'id',\n 'status',\n 'updatedAt',\n 'loaderData',\n // Not-founds that occur during SSR don't require the client to load data before\n // triggering in order to prevent the flicker of the loading component\n 'notFoundError',\n ]),\n // If an error occurs server-side during SSRing,\n // send a small subset of the error to the client\n error: d.error\n ? {\n data: pickError(d.error),\n __isServerError: true,\n }\n : undefined,\n })),\n },\n }\n }\n\n hydrate = async (__do_not_use_server_ctx?: string) => {\n let _ctx = __do_not_use_server_ctx\n // Client hydrates from window\n if (typeof document !== 'undefined') {\n _ctx = window.__TSR_DEHYDRATED__?.data\n }\n\n invariant(\n _ctx,\n 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?',\n )\n\n const ctx = this.options.transformer.parse(_ctx) as HydrationCtx\n this.dehydratedData = ctx.payload as any\n this.options.hydrate?.(ctx.payload as any)\n const dehydratedState = ctx.router.state\n\n let matches = this.matchRoutes(\n this.state.location.pathname,\n this.state.location.search,\n ).map((match) => {\n const dehydratedMatch = dehydratedState.dehydratedMatches.find(\n (d) => d.id === match.id,\n )\n\n invariant(\n dehydratedMatch,\n `Could not find a client-side match for dehydrated match with id: ${match.id}!`,\n )\n\n if (dehydratedMatch) {\n const route = this.looseRoutesById[match.routeId]!\n\n return {\n ...match,\n ...dehydratedMatch,\n meta: route.options.meta?.({\n loaderData: dehydratedMatch.loaderData,\n }),\n links: route.options.links?.(),\n scripts: route.options.scripts?.(),\n }\n }\n return match\n })\n\n this.__store.setState((s) => {\n return {\n ...s,\n matches: matches as any,\n lastUpdated: Date.now(),\n }\n })\n }\n\n // Finds a match that has a notFoundComponent\n updateMatchesWithNotFound = (\n matches: AnyRouteMatch[],\n currentMatch: AnyRouteMatch,\n err: NotFoundError,\n ) => {\n const matchesByRouteId = Object.fromEntries(\n matches.map((match) => [match.routeId, match]),\n ) as Record<string, AnyRouteMatch>\n\n if (err.global) {\n matchesByRouteId[rootRouteId]!.notFoundError = err\n } else {\n // If the err contains a routeId, start searching up from that route\n let currentRoute = (this.routesById as any)[\n err.route ?? currentMatch.routeId\n ] as AnyRoute\n\n // Go up the tree until we find a route with a notFoundComponent\n while (!currentRoute.options.notFoundComponent) {\n currentRoute = currentRoute?.parentRoute\n\n invariant(\n currentRoute,\n 'Found invalid route tree while trying to find not-found handler.',\n )\n\n if (currentRoute.id === rootRouteId) break\n }\n\n const match = matchesByRouteId[currentRoute.id]\n invariant(match, 'Could not find match for route: ' + currentRoute.id)\n match.notFoundError = err\n }\n }\n\n hasNotFoundMatch = () => {\n return this.__store.state.matches.some((d) => d.notFoundError)\n }\n\n // resolveMatchPromise = (matchId: string, key: string, value: any) => {\n // state.matches\n // .find((d) => d.id === matchId)\n // ?.__promisesByKey[key]?.resolve(value)\n // }\n}\n\n// A function that takes an import() argument which is a function and returns a new function that will\n// proxy arguments from the caller to the imported function, retaining all type\n// information along the way\nexport function lazyFn<\n T extends Record<string, (...args: any[]) => any>,\n TKey extends keyof T = 'default',\n>(fn: () => Promise<T>, key?: TKey) {\n return async (\n ...args: Parameters<T[TKey]>\n ): Promise<Awaited<ReturnType<T[TKey]>>> => {\n const imported = await fn()\n return imported[key || 'default'](...args)\n }\n}\n\nexport class SearchParamError extends Error {}\n\nexport class PathParamError extends Error {}\n\nexport function getInitialRouterState(\n location: ParsedLocation,\n): RouterState<any> {\n return {\n isLoading: false,\n isTransitioning: false,\n status: 'idle',\n resolvedLocation: { ...location },\n location,\n matches: [],\n pendingMatches: [],\n cachedMatches: [],\n lastUpdated: 0,\n }\n}\n\nexport function defaultSerializeError(err: unknown) {\n if (err instanceof Error)\n return {\n name: err.name,\n message: err.message,\n }\n\n return {\n data: err,\n }\n}\n"],"names":["trimPath","createBrowserHistory","createMemoryHistory","Store","trimPathRight","trimPathLeft","parsePathname","d","replaceEqualDeep","path","resolvePath","cleanPath","route","matchPathname","searchError","interpolatePath","getRouteMatch","rootRouteId","joinPaths","last","functionalUpdate","pick","_a","isRedirect","isNotFound","_b","deepEqual","escapeJSON","_c","defaultStringifySearch","defaultParseSearch"],"mappings":";;;;;;;;;;;;AA8MO,MAAM,iBAAiB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA8BO,SAAS,aAKd,SACA;AACO,SAAA,IAAI,OAAkD,OAAO;AACtE;AAEO,MAAM,OAIX;AAAA;AAAA;AAAA;AAAA,EAkCA,YACE,SAKA;AAtCF,SAAA,kBAAsC,GAAG,KAAK;AAAA,MAC5C,KAAK,WAAW;AAAA,IACjB,CAAA;AAC0B,SAAA,kBAAA;AACO,SAAA,kBAAA;AAClC,SAAA,oBAAmC,QAAQ;AAC3C,SAAA,kCAAkB;AAClB,SAAA,eAAoC;AA+Ca,SAAA,uBAAA,CAAC,OAAO,GAAG;AAE5D,SAAA,SAAS,CACP,eAKG;AACH,UAAI,WAAW,eAAe;AACpB,gBAAA;AAAA,UACN;AAAA,QAAA;AAAA,MAEJ;AAEA,YAAM,kBAAkB,KAAK;AAC7B,WAAK,UAAU;AAAA,QACb,GAAG,KAAK;AAAA,QACR,GAAG;AAAA,MAAA;AAIH,UAAA,CAAC,KAAK,YACL,WAAW,YAAY,WAAW,aAAa,gBAAgB,UAChE;AAEE,YAAA,WAAW,aAAa,UACxB,WAAW,aAAa,MACxB,WAAW,aAAa,KACxB;AACA,eAAK,WAAW;AAAA,QAAA,OACX;AACL,eAAK,WAAW,IAAIA,KAAS,SAAA,WAAW,QAAQ,CAAC;AAAA,QACnD;AAAA,MACF;AAGE,UAAA,CAAC,KAAK,WACL,KAAK,QAAQ,WAAW,KAAK,QAAQ,YAAY,KAAK,SACvD;AACK,aAAA,UACH,KAAK,QAAQ,YACZ,OAAO,aAAa,cACjBC,6BAAqB,IACrBC,4BAAoB;AAAA,UAClB,gBAAgB,CAAC,KAAK,QAAQ,YAAY,GAAG;AAAA,QAC9C,CAAA;AACF,aAAA,iBAAiB,KAAK;MA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,IAAA;AA1hD7D,SAAK,OAAO;AAAA,MACV,qBAAqB;AAAA,MACrB,kBAAkB;AAAA,MAClB,qBAAqB;AAAA,MACrB,SAAS;AAAA,MACT,GAAG;AAAA,MACH,kBAAiB,mCAAS,oBAAmBY,aAAA;AAAA,MAC7C,cAAa,mCAAS,gBAAeC,aAAA;AAAA,MACrC,cAAa,mCAAS,gBAAe;AAAA,IAAA,CACtC;AAAA,EACH;AAAA,EA2EA,IAAI,QAAQ;AACV,WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EA+LA,IAAI,kBAAkB;AACpB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AA0wCF;AAKgB,SAAA,OAGd,IAAsB,KAAY;AAClC,SAAO,UACF,SACuC;AACpC,UAAA,WAAW,MAAM;AACvB,WAAO,SAAS,OAAO,SAAS,EAAE,GAAG,IAAI;AAAA,EAAA;AAE7C;AAEO,MAAM,yBAAyB,MAAM;AAAC;AAEtC,MAAM,uBAAuB,MAAM;AAAC;AAEpC,SAAS,sBACd,UACkB;AACX,SAAA;AAAA,IACL,WAAW;AAAA,IACX,iBAAiB;AAAA,IACjB,QAAQ;AAAA,IACR,kBAAkB,EAAE,GAAG,SAAS;AAAA,IAChC;AAAA,IACA,SAAS,CAAC;AAAA,IACV,gBAAgB,CAAC;AAAA,IACjB,eAAe,CAAC;AAAA,IAChB,aAAa;AAAA,EAAA;AAEjB;AAEO,SAAS,sBAAsB,KAAc;AAClD,MAAI,eAAe;AACV,WAAA;AAAA,MACL,MAAM,IAAI;AAAA,MACV,SAAS,IAAI;AAAA,IAAA;AAGV,SAAA;AAAA,IACL,MAAM;AAAA,EAAA;AAEV;;;;;;;;;"}
1
+ {"version":3,"file":"router.cjs","sources":["../../src/router.ts"],"sourcesContent":["import {\n HistoryLocation,\n HistoryState,\n RouterHistory,\n createBrowserHistory,\n createMemoryHistory,\n} from '@tanstack/history'\nimport { Store } from '@tanstack/react-store'\n\n//\n\nimport {\n AnySearchSchema,\n AnyRoute,\n AnyContext,\n AnyPathParams,\n RouteMask,\n Route,\n LoaderFnContext,\n rootRouteId,\n} from './route'\nimport {\n FullSearchSchema,\n RouteById,\n RoutePaths,\n RoutesById,\n RoutesByPath,\n} from './routeInfo'\nimport { defaultParseSearch, defaultStringifySearch } from './searchParams'\nimport {\n PickAsRequired,\n Updater,\n NonNullableUpdater,\n replaceEqualDeep,\n deepEqual,\n escapeJSON,\n functionalUpdate,\n last,\n pick,\n Timeout,\n} from './utils'\nimport { RouteComponent } from './route'\nimport { AnyRouteMatch, MatchRouteOptions, RouteMatch } from './Matches'\nimport { ParsedLocation } from './location'\nimport { SearchSerializer, SearchParser } from './searchParams'\nimport {\n BuildLocationFn,\n CommitLocationOptions,\n InjectedHtmlEntry,\n NavigateFn,\n getRouteMatch,\n} from './RouterProvider'\n\nimport {\n cleanPath,\n interpolatePath,\n joinPaths,\n matchPathname,\n parsePathname,\n resolvePath,\n trimPath,\n trimPathLeft,\n trimPathRight,\n} from './path'\nimport invariant from 'tiny-invariant'\nimport { isRedirect } from './redirects'\nimport { NotFoundError, isNotFound } from './not-found'\nimport { ResolveRelativePath, ToOptions } from './link'\nimport { NoInfer } from '@tanstack/react-store'\n// import warning from 'tiny-warning'\n\n//\n\ndeclare global {\n interface Window {\n __TSR_DEHYDRATED__?: { data: string }\n __TSR_ROUTER_CONTEXT__?: React.Context<Router<any>>\n }\n}\n\nexport interface Register {\n // router: Router\n}\n\nexport type AnyRouter = Router<AnyRoute, any>\n\nexport type RegisteredRouter = Register extends {\n router: infer TRouter extends AnyRouter\n}\n ? TRouter\n : AnyRouter\n\nexport type HydrationCtx = {\n router: DehydratedRouter\n payload: Record<string, any>\n}\n\nexport type RouterContextOptions<TRouteTree extends AnyRoute> =\n AnyContext extends TRouteTree['types']['routerContext']\n ? {\n context?: TRouteTree['types']['routerContext']\n }\n : {\n context: TRouteTree['types']['routerContext']\n }\n\nexport interface RouterOptions<\n TRouteTree extends AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n> {\n history?: RouterHistory\n stringifySearch?: SearchSerializer\n parseSearch?: SearchParser\n defaultPreload?: false | 'intent'\n defaultPreloadDelay?: number\n defaultComponent?: RouteComponent\n defaultErrorComponent?: RouteComponent\n defaultPendingComponent?: RouteComponent\n defaultPendingMs?: number\n defaultPendingMinMs?: number\n defaultStaleTime?: number\n defaultPreloadStaleTime?: number\n defaultPreloadGcTime?: number\n defaultGcTime?: number\n caseSensitive?: boolean\n routeTree?: TRouteTree\n basepath?: string\n context?: TRouteTree['types']['routerContext']\n dehydrate?: () => TDehydrated\n hydrate?: (dehydrated: TDehydrated) => void\n routeMasks?: RouteMask<TRouteTree>[]\n unmaskOnReload?: boolean\n Wrap?: (props: { children: any }) => JSX.Element\n InnerWrap?: (props: { children: any }) => JSX.Element\n /**\n * @deprecated\n * Use `notFoundComponent` instead.\n * See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.\n */\n notFoundRoute?: AnyRoute\n transformer?: RouterTransformer\n errorSerializer?: RouterErrorSerializer<TSerializedError>\n globalNotFound?: RouteComponent\n}\n\nexport interface RouterTransformer {\n stringify: (obj: unknown) => string\n parse: (str: string) => unknown\n}\nexport interface RouterErrorSerializer<TSerializedError> {\n serialize: (err: unknown) => TSerializedError\n deserialize: (err: TSerializedError) => unknown\n}\n\nexport interface RouterState<TRouteTree extends AnyRoute = AnyRoute> {\n status: 'pending' | 'idle'\n isLoading: boolean\n isTransitioning: boolean\n matches: RouteMatch<TRouteTree>[]\n pendingMatches?: RouteMatch<TRouteTree>[]\n cachedMatches: RouteMatch<TRouteTree>[]\n location: ParsedLocation<FullSearchSchema<TRouteTree>>\n resolvedLocation: ParsedLocation<FullSearchSchema<TRouteTree>>\n lastUpdated: number\n}\n\nexport type ListenerFn<TEvent extends RouterEvent> = (event: TEvent) => void\n\nexport interface BuildNextOptions {\n to?: string | number | null\n params?: true | Updater<unknown>\n search?: true | Updater<unknown>\n hash?: true | Updater<string>\n state?: true | NonNullableUpdater<HistoryState>\n mask?: {\n to?: string | number | null\n params?: true | Updater<unknown>\n search?: true | Updater<unknown>\n hash?: true | Updater<string>\n state?: true | NonNullableUpdater<HistoryState>\n unmaskOnReload?: boolean\n }\n from?: string\n}\n\nexport interface DehydratedRouterState {\n dehydratedMatches: DehydratedRouteMatch[]\n}\n\nexport type DehydratedRouteMatch = Pick<\n RouteMatch,\n 'id' | 'status' | 'updatedAt' | 'notFoundError' | 'loaderData'\n>\n\nexport interface DehydratedRouter {\n state: DehydratedRouterState\n}\n\nexport type RouterConstructorOptions<\n TRouteTree extends AnyRoute,\n TDehydrated extends Record<string, any>,\n TSerializedError extends Record<string, any>,\n> = Omit<RouterOptions<TRouteTree, TDehydrated, TSerializedError>, 'context'> &\n RouterContextOptions<TRouteTree>\n\nexport const componentTypes = [\n 'component',\n 'errorComponent',\n 'pendingComponent',\n 'notFoundComponent',\n] as const\n\nexport type RouterEvents = {\n onBeforeLoad: {\n type: 'onBeforeLoad'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n onLoad: {\n type: 'onLoad'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n onResolved: {\n type: 'onResolved'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n}\n\nexport type RouterEvent = RouterEvents[keyof RouterEvents]\n\nexport type RouterListener<TRouterEvent extends RouterEvent> = {\n eventType: TRouterEvent['type']\n fn: ListenerFn<TRouterEvent>\n}\n\nexport function createRouter<\n TRouteTree extends AnyRoute = AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n>(\n options: RouterConstructorOptions<TRouteTree, TDehydrated, TSerializedError>,\n) {\n return new Router<TRouteTree, TDehydrated, TSerializedError>(options)\n}\n\nexport class Router<\n TRouteTree extends AnyRoute = AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n> {\n // Option-independent properties\n tempLocationKey: string | undefined = `${Math.round(\n Math.random() * 10000000,\n )}`\n resetNextScroll: boolean = true\n navigateTimeout: Timeout | null = null\n latestLoadPromise: Promise<void> = Promise.resolve()\n subscribers = new Set<RouterListener<RouterEvent>>()\n injectedHtml: InjectedHtmlEntry[] = []\n dehydratedData?: TDehydrated\n\n // Must build in constructor\n __store!: Store<RouterState<TRouteTree>>\n options!: PickAsRequired<\n Omit<\n RouterOptions<TRouteTree, TDehydrated, TSerializedError>,\n 'transformer'\n > & {\n transformer: RouterTransformer\n },\n 'stringifySearch' | 'parseSearch' | 'context'\n >\n history!: RouterHistory\n latestLocation!: ParsedLocation\n basepath!: string\n routeTree!: TRouteTree\n routesById!: RoutesById<TRouteTree>\n routesByPath!: RoutesByPath<TRouteTree>\n flatRoutes!: AnyRoute[]\n\n /**\n * @deprecated Use the `createRouter` function instead\n */\n constructor(\n options: RouterConstructorOptions<\n TRouteTree,\n TDehydrated,\n TSerializedError\n >,\n ) {\n this.update({\n defaultPreloadDelay: 50,\n defaultPendingMs: 1000,\n defaultPendingMinMs: 500,\n context: undefined!,\n ...options,\n stringifySearch: options?.stringifySearch ?? defaultStringifySearch,\n parseSearch: options?.parseSearch ?? defaultParseSearch,\n transformer: options?.transformer ?? JSON,\n })\n }\n\n // These are default implementations that can optionally be overridden\n // by the router provider once rendered. We provide these so that the\n // router can be used in a non-react environment if necessary\n startReactTransition: (fn: () => void) => void = (fn) => fn()\n\n update = (\n newOptions: RouterConstructorOptions<\n TRouteTree,\n TDehydrated,\n TSerializedError\n >,\n ) => {\n if (newOptions.notFoundRoute) {\n console.warn(\n 'The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.',\n )\n }\n\n const previousOptions = this.options\n this.options = {\n ...this.options,\n ...newOptions,\n }\n\n if (\n !this.basepath ||\n (newOptions.basepath && newOptions.basepath !== previousOptions.basepath)\n ) {\n if (\n newOptions.basepath === undefined ||\n newOptions.basepath === '' ||\n newOptions.basepath === '/'\n ) {\n this.basepath = '/'\n } else {\n this.basepath = `/${trimPath(newOptions.basepath)}`\n }\n }\n\n if (\n !this.history ||\n (this.options.history && this.options.history !== this.history)\n ) {\n this.history =\n this.options.history ??\n (typeof document !== 'undefined'\n ? createBrowserHistory()\n : createMemoryHistory({\n initialEntries: [this.options.basepath || '/'],\n }))\n this.latestLocation = this.parseLocation()\n }\n\n if (this.options.routeTree !== this.routeTree) {\n this.routeTree = this.options.routeTree as TRouteTree\n this.buildRouteTree()\n }\n\n if (!this.__store) {\n this.__store = new Store(getInitialRouterState(this.latestLocation), {\n onUpdate: () => {\n this.__store.state = {\n ...this.state,\n status:\n this.state.isTransitioning || this.state.isLoading\n ? 'pending'\n : 'idle',\n }\n },\n })\n }\n }\n\n get state() {\n return this.__store.state\n }\n\n buildRouteTree = () => {\n this.routesById = {} as RoutesById<TRouteTree>\n this.routesByPath = {} as RoutesByPath<TRouteTree>\n\n const notFoundRoute = this.options.notFoundRoute\n if (notFoundRoute) {\n notFoundRoute.init({ originalIndex: 99999999999 })\n ;(this.routesById as any)[notFoundRoute.id] = notFoundRoute\n }\n\n const recurseRoutes = (childRoutes: AnyRoute[]) => {\n childRoutes.forEach((childRoute, i) => {\n childRoute.init({ originalIndex: i })\n\n const existingRoute = (this.routesById as any)[childRoute.id]\n\n invariant(\n !existingRoute,\n `Duplicate routes found with id: ${String(childRoute.id)}`,\n )\n ;(this.routesById as any)[childRoute.id] = childRoute\n\n if (!childRoute.isRoot && childRoute.path) {\n const trimmedFullPath = trimPathRight(childRoute.fullPath)\n if (\n !(this.routesByPath as any)[trimmedFullPath] ||\n childRoute.fullPath.endsWith('/')\n ) {\n ;(this.routesByPath as any)[trimmedFullPath] = childRoute\n }\n }\n\n const children = childRoute.children as Route[]\n\n if (children?.length) {\n recurseRoutes(children)\n }\n })\n }\n\n recurseRoutes([this.routeTree])\n\n const scoredRoutes: {\n child: AnyRoute\n trimmed: string\n parsed: ReturnType<typeof parsePathname>\n index: number\n scores: number[]\n }[] = []\n\n ;(Object.values(this.routesById) as AnyRoute[]).forEach((d, i) => {\n if (d.isRoot || !d.path) {\n return\n }\n\n const trimmed = trimPathLeft(d.fullPath)\n const parsed = parsePathname(trimmed)\n\n while (parsed.length > 1 && parsed[0]?.value === '/') {\n parsed.shift()\n }\n\n const scores = parsed.map((d) => {\n if (d.value === '/') {\n return 0.75\n }\n\n if (d.type === 'param') {\n return 0.5\n }\n\n if (d.type === 'wildcard') {\n return 0.25\n }\n\n return 1\n })\n\n scoredRoutes.push({ child: d, trimmed, parsed, index: i, scores })\n })\n\n this.flatRoutes = scoredRoutes\n .sort((a, b) => {\n const minLength = Math.min(a.scores.length, b.scores.length)\n\n // Sort by min available score\n for (let i = 0; i < minLength; i++) {\n if (a.scores[i] !== b.scores[i]) {\n return b.scores[i]! - a.scores[i]!\n }\n }\n\n // Sort by length of score\n if (a.scores.length !== b.scores.length) {\n return b.scores.length - a.scores.length\n }\n\n // Sort by min available parsed value\n for (let i = 0; i < minLength; i++) {\n if (a.parsed[i]!.value !== b.parsed[i]!.value) {\n return a.parsed[i]!.value! > b.parsed[i]!.value! ? 1 : -1\n }\n }\n\n // Sort by original index\n return a.index - b.index\n })\n .map((d, i) => {\n d.child.rank = i\n return d.child\n })\n }\n\n subscribe = <TType extends keyof RouterEvents>(\n eventType: TType,\n fn: ListenerFn<RouterEvents[TType]>,\n ) => {\n const listener: RouterListener<any> = {\n eventType,\n fn,\n }\n\n this.subscribers.add(listener)\n\n return () => {\n this.subscribers.delete(listener)\n }\n }\n\n emit = (routerEvent: RouterEvent) => {\n this.subscribers.forEach((listener) => {\n if (listener.eventType === routerEvent.type) {\n listener.fn(routerEvent)\n }\n })\n }\n\n checkLatest = (promise: Promise<void>): undefined | Promise<void> => {\n return this.latestLoadPromise !== promise\n ? this.latestLoadPromise\n : undefined\n }\n\n parseLocation = (\n previousLocation?: ParsedLocation,\n ): ParsedLocation<FullSearchSchema<TRouteTree>> => {\n const parse = ({\n pathname,\n search,\n hash,\n state,\n }: HistoryLocation): ParsedLocation<FullSearchSchema<TRouteTree>> => {\n const parsedSearch = this.options.parseSearch(search)\n const searchStr = this.options.stringifySearch(parsedSearch)\n\n return {\n pathname: pathname,\n searchStr,\n search: replaceEqualDeep(previousLocation?.search, parsedSearch) as any,\n hash: hash.split('#').reverse()[0] ?? '',\n href: `${pathname}${searchStr}${hash}`,\n state: replaceEqualDeep(previousLocation?.state, state) as HistoryState,\n }\n }\n\n const location = parse(this.history.location)\n\n let { __tempLocation, __tempKey } = location.state\n\n if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {\n // Sync up the location keys\n const parsedTempLocation = parse(__tempLocation) as any\n parsedTempLocation.state.key = location.state.key\n\n delete parsedTempLocation.state.__tempLocation\n\n return {\n ...parsedTempLocation,\n maskedLocation: location,\n }\n }\n\n return location\n }\n\n resolvePathWithBase = (from: string, path: string) => {\n return resolvePath(this.basepath!, from, cleanPath(path))\n }\n\n get looseRoutesById() {\n return this.routesById as Record<string, AnyRoute>\n }\n\n matchRoutes = <TRouteTree extends AnyRoute>(\n pathname: string,\n locationSearch: AnySearchSchema,\n opts?: { throwOnError?: boolean; debug?: boolean },\n ): RouteMatch<TRouteTree>[] => {\n let routeParams: Record<string, string> = {}\n\n let foundRoute = this.flatRoutes.find((route) => {\n const matchedParams = matchPathname(\n this.basepath,\n trimPathRight(pathname),\n {\n to: route.fullPath,\n caseSensitive:\n route.options.caseSensitive ?? this.options.caseSensitive,\n fuzzy: true,\n },\n )\n\n if (matchedParams) {\n routeParams = matchedParams\n return true\n }\n\n return false\n })\n\n let routeCursor: AnyRoute =\n foundRoute || (this.routesById as any)['__root__']\n\n let matchedRoutes: AnyRoute[] = [routeCursor]\n\n let isGlobalNotFound = false\n\n // Check to see if the route needs a 404 entry\n if (\n // If we found a route, and it's not an index route and we have left over path\n foundRoute\n ? foundRoute.path !== '/' && routeParams['**']\n : // Or if we didn't find a route and we have left over path\n trimPathRight(pathname)\n ) {\n // If the user has defined an (old) 404 route, use it\n if (this.options.notFoundRoute) {\n matchedRoutes.push(this.options.notFoundRoute)\n } else {\n // If there is no routes found during path matching\n isGlobalNotFound = true\n }\n }\n\n while (routeCursor?.parentRoute) {\n routeCursor = routeCursor.parentRoute\n if (routeCursor) matchedRoutes.unshift(routeCursor)\n }\n\n // Existing matches are matches that are already loaded along with\n // pending matches that are still loading\n\n const parseErrors = matchedRoutes.map((route) => {\n let parsedParamsError\n\n if (route.options.parseParams) {\n try {\n const parsedParams = route.options.parseParams(routeParams)\n // Add the parsed params to the accumulated params bag\n Object.assign(routeParams, parsedParams)\n } catch (err: any) {\n parsedParamsError = new PathParamError(err.message, {\n cause: err,\n })\n\n if (opts?.throwOnError) {\n throw parsedParamsError\n }\n\n return parsedParamsError\n }\n }\n\n return\n })\n\n const matches: AnyRouteMatch[] = []\n\n matchedRoutes.forEach((route, index) => {\n // Take each matched route and resolve + validate its search params\n // This has to happen serially because each route's search params\n // can depend on the parent route's search params\n // It must also happen before we create the match so that we can\n // pass the search params to the route's potential key function\n // which is used to uniquely identify the route match in state\n\n const parentMatch = matches[index - 1]\n\n const [preMatchSearch, searchError]: [Record<string, any>, any] = (() => {\n // Validate the search params and stabilize them\n const parentSearch = parentMatch?.search ?? locationSearch\n\n try {\n const validator =\n typeof route.options.validateSearch === 'object'\n ? route.options.validateSearch.parse\n : route.options.validateSearch\n\n let search = validator?.(parentSearch) ?? {}\n\n return [\n {\n ...parentSearch,\n ...search,\n },\n undefined,\n ]\n } catch (err: any) {\n const searchError = new SearchParamError(err.message, {\n cause: err,\n })\n\n if (opts?.throwOnError) {\n throw searchError\n }\n\n return [parentSearch, searchError]\n }\n })()\n\n // This is where we need to call route.options.loaderDeps() to get any additional\n // deps that the route's loader function might need to run. We need to do this\n // before we create the match so that we can pass the deps to the route's\n // potential key function which is used to uniquely identify the route match in state\n\n const loaderDeps =\n route.options.loaderDeps?.({\n search: preMatchSearch,\n }) ?? ''\n\n const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : ''\n\n const interpolatedPath = interpolatePath({\n path: route.fullPath,\n params: routeParams,\n })\n const matchId =\n interpolatePath({\n path: route.id,\n params: routeParams,\n leaveWildcards: true,\n }) + loaderDepsHash\n\n // Waste not, want not. If we already have a match for this route,\n // reuse it. This is important for layout routes, which might stick\n // around between navigation actions that only change leaf routes.\n const existingMatch = getRouteMatch(this.state, matchId)\n\n const cause = this.state.matches.find((d) => d.id === matchId)\n ? 'stay'\n : 'enter'\n\n const match: AnyRouteMatch = existingMatch\n ? {\n ...existingMatch,\n cause,\n notFoundError:\n isGlobalNotFound && route.id === rootRouteId\n ? { global: true }\n : undefined,\n }\n : {\n id: matchId,\n routeId: route.id,\n params: routeParams,\n pathname: joinPaths([this.basepath, interpolatedPath]),\n updatedAt: Date.now(),\n search: {} as any,\n searchError: undefined,\n status: 'pending',\n showPending: false,\n isFetching: false,\n error: undefined,\n paramsError: parseErrors[index],\n loadPromise: Promise.resolve(),\n routeContext: undefined!,\n context: undefined!,\n abortController: new AbortController(),\n fetchCount: 0,\n cause,\n loaderDeps,\n invalid: false,\n preload: false,\n notFoundError:\n isGlobalNotFound && route.id === rootRouteId\n ? { global: true }\n : undefined,\n links: route.options.links?.(),\n scripts: route.options.scripts?.(),\n staticData: route.options.staticData || {},\n }\n\n // Regardless of whether we're reusing an existing match or creating\n // a new one, we need to update the match's search params\n match.search = replaceEqualDeep(match.search, preMatchSearch)\n // And also update the searchError if there is one\n match.searchError = searchError\n\n matches.push(match)\n })\n\n return matches as any\n }\n\n cancelMatch = (id: string) => {\n getRouteMatch(this.state, id)?.abortController?.abort()\n }\n\n cancelMatches = () => {\n this.state.pendingMatches?.forEach((match) => {\n this.cancelMatch(match.id)\n })\n }\n\n buildLocation: BuildLocationFn<TRouteTree> = (opts) => {\n const build = (\n dest: BuildNextOptions & {\n unmaskOnReload?: boolean\n } = {},\n matches?: AnyRouteMatch[],\n ): ParsedLocation => {\n const relevantMatches = this.state.pendingMatches || this.state.matches\n const fromSearch =\n relevantMatches[relevantMatches.length - 1]?.search ||\n this.latestLocation.search\n\n let pathname = this.resolvePathWithBase(\n dest.from ?? this.latestLocation.pathname,\n `${dest.to ?? ''}`,\n )\n\n const fromMatches = this.matchRoutes(\n this.latestLocation.pathname,\n fromSearch,\n )\n const stayingMatches = matches?.filter((d) =>\n fromMatches?.find((e) => e.routeId === d.routeId),\n )\n\n const prevParams = { ...last(fromMatches)?.params }\n\n let nextParams =\n (dest.params ?? true) === true\n ? prevParams\n : functionalUpdate(dest.params!, prevParams)\n\n if (nextParams) {\n matches\n ?.map((d) => this.looseRoutesById[d.routeId]!.options.stringifyParams)\n .filter(Boolean)\n .forEach((fn) => {\n nextParams = { ...nextParams!, ...fn!(nextParams!) }\n })\n }\n\n pathname = interpolatePath({\n path: pathname,\n params: nextParams ?? {},\n leaveWildcards: false,\n leaveParams: opts.leaveParams,\n })\n\n const preSearchFilters =\n stayingMatches\n ?.map(\n (match) =>\n this.looseRoutesById[match.routeId]!.options.preSearchFilters ??\n [],\n )\n .flat()\n .filter(Boolean) ?? []\n\n const postSearchFilters =\n stayingMatches\n ?.map(\n (match) =>\n this.looseRoutesById[match.routeId]!.options.postSearchFilters ??\n [],\n )\n .flat()\n .filter(Boolean) ?? []\n\n // Pre filters first\n const preFilteredSearch = preSearchFilters?.length\n ? preSearchFilters?.reduce(\n (prev, next) => next(prev) as any,\n fromSearch,\n )\n : fromSearch\n\n // Then the link/navigate function\n const destSearch =\n dest.search === true\n ? preFilteredSearch // Preserve resolvedFrom true\n : dest.search\n ? functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater\n : preSearchFilters?.length\n ? preFilteredSearch // Preserve resolvedFrom filters\n : {}\n\n // Then post filters\n const postFilteredSearch = postSearchFilters?.length\n ? postSearchFilters.reduce((prev, next) => next(prev), destSearch)\n : destSearch\n\n const search = replaceEqualDeep(fromSearch, postFilteredSearch)\n\n const searchStr = this.options.stringifySearch(search)\n\n const hash =\n dest.hash === true\n ? this.latestLocation.hash\n : dest.hash\n ? functionalUpdate(dest.hash!, this.latestLocation.hash)\n : undefined\n\n const hashStr = hash ? `#${hash}` : ''\n\n let nextState =\n dest.state === true\n ? this.latestLocation.state\n : dest.state\n ? functionalUpdate(dest.state, this.latestLocation.state)\n : {}\n\n nextState = replaceEqualDeep(this.latestLocation.state, nextState)\n\n return {\n pathname,\n search,\n searchStr,\n state: nextState as any,\n hash: hash ?? '',\n href: `${pathname}${searchStr}${hashStr}`,\n unmaskOnReload: dest.unmaskOnReload,\n }\n }\n\n const buildWithMatches = (\n dest: BuildNextOptions = {},\n maskedDest?: BuildNextOptions,\n ) => {\n let next = build(dest)\n let maskedNext = maskedDest ? build(maskedDest) : undefined\n\n if (!maskedNext) {\n let params = {}\n\n let foundMask = this.options.routeMasks?.find((d) => {\n const match = matchPathname(this.basepath, next.pathname, {\n to: d.from,\n caseSensitive: false,\n fuzzy: false,\n })\n\n if (match) {\n params = match\n return true\n }\n\n return false\n })\n\n if (foundMask) {\n maskedDest = {\n ...pick(opts, ['from']),\n ...foundMask,\n params,\n }\n maskedNext = build(maskedDest)\n }\n }\n\n const nextMatches = this.matchRoutes(next.pathname, next.search)\n const maskedMatches = maskedNext\n ? this.matchRoutes(maskedNext.pathname, maskedNext.search)\n : undefined\n const maskedFinal = maskedNext\n ? build(maskedDest, maskedMatches)\n : undefined\n\n const final = build(dest, nextMatches)\n\n if (maskedFinal) {\n final.maskedLocation = maskedFinal\n }\n\n return final\n }\n\n if (opts.mask) {\n return buildWithMatches(opts, {\n ...pick(opts, ['from']),\n ...opts.mask,\n })\n }\n\n return buildWithMatches(opts)\n }\n\n commitLocation = async ({\n startTransition,\n ...next\n }: ParsedLocation & CommitLocationOptions) => {\n if (this.navigateTimeout) clearTimeout(this.navigateTimeout)\n\n const isSameUrl = this.latestLocation.href === next.href\n\n // If the next urls are the same and we're not replacing,\n // do nothing\n if (!isSameUrl || !next.replace) {\n let { maskedLocation, ...nextHistory } = next\n\n if (maskedLocation) {\n nextHistory = {\n ...maskedLocation,\n state: {\n ...maskedLocation.state,\n __tempKey: undefined,\n __tempLocation: {\n ...nextHistory,\n search: nextHistory.searchStr,\n state: {\n ...nextHistory.state,\n __tempKey: undefined!,\n __tempLocation: undefined!,\n key: undefined!,\n },\n },\n },\n }\n\n if (\n nextHistory.unmaskOnReload ??\n this.options.unmaskOnReload ??\n false\n ) {\n nextHistory.state.__tempKey = this.tempLocationKey\n }\n }\n\n const apply = () => {\n this.history[next.replace ? 'replace' : 'push'](\n nextHistory.href,\n nextHistory.state,\n )\n }\n\n if (startTransition ?? true) {\n this.startReactTransition(apply)\n } else {\n apply()\n }\n }\n\n this.resetNextScroll = next.resetScroll ?? true\n\n return this.latestLoadPromise\n }\n\n buildAndCommitLocation = ({\n replace,\n resetScroll,\n startTransition,\n ...rest\n }: BuildNextOptions & CommitLocationOptions = {}) => {\n const location = this.buildLocation(rest as any)\n return this.commitLocation({\n ...location,\n startTransition,\n replace,\n resetScroll,\n })\n }\n\n navigate: NavigateFn<TRouteTree> = ({ from, to, ...rest }) => {\n // If this link simply reloads the current route,\n // make sure it has a new key so it will trigger a data refresh\n\n // If this `to` is a valid external URL, return\n // null for LinkUtils\n const toString = String(to)\n // const fromString = from !== undefined ? String(from) : from\n let isExternal\n\n try {\n new URL(`${toString}`)\n isExternal = true\n } catch (e) {}\n\n invariant(\n !isExternal,\n 'Attempting to navigate to external url with this.navigate!',\n )\n\n return this.buildAndCommitLocation({\n ...rest,\n from,\n to,\n // to: toString,\n })\n }\n\n loadMatches = async ({\n checkLatest,\n matches,\n preload,\n }: {\n checkLatest: () => Promise<void> | undefined\n matches: AnyRouteMatch[]\n preload?: boolean\n }): Promise<RouteMatch[]> => {\n let latestPromise\n let firstBadMatchIndex: number | undefined\n\n const updateMatch = (match: AnyRouteMatch) => {\n // const isPreload = this.state.cachedMatches.find((d) => d.id === match.id)\n const isPending = this.state.pendingMatches?.find(\n (d) => d.id === match.id,\n )\n\n const isMatched = this.state.matches.find((d) => d.id === match.id)\n\n const matchesKey = isPending\n ? 'pendingMatches'\n : isMatched\n ? 'matches'\n : 'cachedMatches'\n\n this.__store.setState((s) => ({\n ...s,\n [matchesKey]: s[matchesKey]?.map((d) =>\n d.id === match.id ? match : d,\n ),\n }))\n }\n\n // Check each match middleware to see if the route can be accessed\n try {\n for (let [index, match] of matches.entries()) {\n const parentMatch = matches[index - 1]\n const route = this.looseRoutesById[match.routeId]!\n const abortController = new AbortController()\n\n const handleErrorAndRedirect = (err: any, code: string) => {\n err.routerCode = code\n firstBadMatchIndex = firstBadMatchIndex ?? index\n\n if (isRedirect(err)) {\n throw err\n }\n\n if (isNotFound(err)) {\n this.updateMatchesWithNotFound(matches, match, err)\n }\n\n try {\n route.options.onError?.(err)\n } catch (errorHandlerErr) {\n err = errorHandlerErr\n\n if (isRedirect(errorHandlerErr)) {\n throw errorHandlerErr\n }\n }\n\n matches[index] = match = {\n ...match,\n error: err,\n status: 'error',\n updatedAt: Date.now(),\n abortController: new AbortController(),\n }\n }\n\n try {\n if (match.paramsError) {\n handleErrorAndRedirect(match.paramsError, 'PARSE_PARAMS')\n }\n\n if (match.searchError) {\n handleErrorAndRedirect(match.searchError, 'VALIDATE_SEARCH')\n }\n\n const parentContext =\n parentMatch?.context ?? this.options.context ?? {}\n\n const pendingMs =\n route.options.pendingMs ?? this.options.defaultPendingMs\n const pendingPromise =\n typeof pendingMs === 'number' && pendingMs <= 0\n ? Promise.resolve()\n : new Promise<void>((r) => setTimeout(r, pendingMs))\n\n const beforeLoadContext =\n (await route.options.beforeLoad?.({\n search: match.search,\n abortController,\n params: match.params,\n preload: !!preload,\n context: parentContext,\n location: this.state.location,\n // TOOD: just expose state and router, etc\n navigate: (opts) =>\n this.navigate({ ...opts, from: match.pathname } as any),\n buildLocation: this.buildLocation,\n cause: preload ? 'preload' : match.cause,\n })) ?? ({} as any)\n\n if (isRedirect(beforeLoadContext)) {\n throw beforeLoadContext\n }\n\n const context = {\n ...parentContext,\n ...beforeLoadContext,\n }\n\n matches[index] = match = {\n ...match,\n routeContext: replaceEqualDeep(\n match.routeContext,\n beforeLoadContext,\n ),\n context: replaceEqualDeep(match.context, context),\n abortController,\n pendingPromise,\n }\n } catch (err) {\n handleErrorAndRedirect(err, 'BEFORE_LOAD')\n break\n }\n }\n } catch (err) {\n if (isRedirect(err)) {\n if (!preload) this.navigate(err as any)\n return matches\n }\n\n throw err\n }\n\n const validResolvedMatches = matches.slice(0, firstBadMatchIndex)\n const matchPromises: Promise<any>[] = []\n\n validResolvedMatches.forEach((match, index) => {\n matchPromises.push(\n new Promise<void>(async (resolve) => {\n const parentMatchPromise = matchPromises[index - 1]\n const route = this.looseRoutesById[match.routeId]!\n\n const handleErrorAndRedirect = (err: any) => {\n if (isRedirect(err)) {\n if (!preload) {\n this.navigate(err as any)\n }\n return true\n }\n\n if (isNotFound(err)) {\n if (!preload) {\n this.updateMatchesWithNotFound(matches, match, err)\n }\n return true\n }\n\n return false\n }\n\n let loadPromise: Promise<void> | undefined\n\n matches[index] = match = {\n ...match,\n showPending: false,\n }\n\n let didShowPending = false\n const pendingMs =\n route.options.pendingMs ?? this.options.defaultPendingMs\n const pendingMinMs =\n route.options.pendingMinMs ?? this.options.defaultPendingMinMs\n const shouldPending =\n !preload &&\n typeof pendingMs === 'number' &&\n (route.options.pendingComponent ??\n this.options.defaultPendingComponent)\n\n const loaderContext: LoaderFnContext = {\n params: match.params,\n deps: match.loaderDeps,\n preload: !!preload,\n parentMatchPromise,\n abortController: match.abortController,\n context: match.context,\n location: this.state.location,\n navigate: (opts) =>\n this.navigate({ ...opts, from: match.pathname } as any),\n cause: preload ? 'preload' : match.cause,\n }\n\n const fetch = async () => {\n if (match.isFetching) {\n loadPromise = getRouteMatch(this.state, match.id)?.loadPromise\n } else {\n // If the user doesn't want the route to reload, just\n // resolve with the existing loader data\n\n if (match.fetchCount && match.status === 'success') {\n resolve()\n }\n\n // Otherwise, load the route\n matches[index] = match = {\n ...match,\n isFetching: true,\n fetchCount: match.fetchCount + 1,\n }\n\n const lazyPromise =\n route.lazyFn?.().then((lazyRoute) => {\n Object.assign(route.options, lazyRoute.options)\n }) || Promise.resolve()\n\n // If for some reason lazy resolves more lazy components...\n // We'll wait for that before pre attempt to preload any\n // components themselves.\n const componentsPromise = lazyPromise.then(() =>\n Promise.all(\n componentTypes.map(async (type) => {\n const component = route.options[type]\n\n if ((component as any)?.preload) {\n await (component as any).preload()\n }\n }),\n ),\n )\n\n // Kick off the loader!\n const loaderPromise = route.options.loader?.(loaderContext)\n\n loadPromise = Promise.all([\n componentsPromise,\n loaderPromise,\n lazyPromise,\n ]).then((d) => d[1])\n }\n\n matches[index] = match = {\n ...match,\n loadPromise,\n }\n\n updateMatch(match)\n\n try {\n const loaderData = await loadPromise\n if ((latestPromise = checkLatest())) return await latestPromise\n\n if (isRedirect(loaderData) || isNotFound(loaderData)) {\n if (handleErrorAndRedirect(loaderData)) return\n }\n\n if (didShowPending && pendingMinMs) {\n await new Promise((r) => setTimeout(r, pendingMinMs))\n }\n\n if ((latestPromise = checkLatest())) return await latestPromise\n\n const meta = route.options.meta?.({\n loaderData,\n })\n\n matches[index] = match = {\n ...match,\n error: undefined,\n status: 'success',\n isFetching: false,\n updatedAt: Date.now(),\n loaderData,\n loadPromise: undefined,\n meta,\n }\n } catch (error) {\n if ((latestPromise = checkLatest())) return await latestPromise\n if (handleErrorAndRedirect(error)) return\n\n try {\n route.options.onError?.(error)\n } catch (onErrorError) {\n error = onErrorError\n if (handleErrorAndRedirect(onErrorError)) return\n }\n\n matches[index] = match = {\n ...match,\n error,\n status: 'error',\n isFetching: false,\n }\n }\n\n updateMatch(match)\n }\n\n // This is where all of the stale-while-revalidate magic happens\n const age = Date.now() - match.updatedAt\n\n let staleAge = preload\n ? route.options.preloadStaleTime ??\n this.options.defaultPreloadStaleTime ??\n 30_000 // 30 seconds for preloads by default\n : route.options.staleTime ?? this.options.defaultStaleTime ?? 0\n\n // Default to reloading the route all the time\n let shouldReload\n\n const shouldReloadOption = route.options.shouldReload\n\n // Allow shouldReload to get the last say,\n // if provided.\n shouldReload =\n typeof shouldReloadOption === 'function'\n ? shouldReloadOption(loaderContext)\n : shouldReloadOption\n\n matches[index] = match = {\n ...match,\n preload:\n !!preload && !this.state.matches.find((d) => d.id === match.id),\n }\n\n if (match.status !== 'success') {\n // If we need to potentially show the pending component,\n // start a timer to show it after the pendingMs\n if (shouldPending) {\n match.pendingPromise?.then(async () => {\n if ((latestPromise = checkLatest())) return latestPromise\n\n didShowPending = true\n matches[index] = match = {\n ...match,\n showPending: true,\n }\n\n updateMatch(match)\n resolve()\n })\n }\n\n // Critical Fetching, we need to await\n await fetch()\n } else if (match.invalid || (shouldReload ?? age > staleAge)) {\n // Background Fetching, no need to wait\n fetch()\n }\n\n resolve()\n }),\n )\n })\n\n await Promise.all(matchPromises)\n return matches\n }\n\n invalidate = () => {\n const invalidate = (d: any) => ({\n ...d,\n invalid: true,\n })\n\n this.__store.setState((s) => ({\n ...s,\n matches: s.matches.map(invalidate),\n cachedMatches: s.cachedMatches.map(invalidate),\n pendingMatches: s.pendingMatches?.map(invalidate),\n }))\n\n this.load()\n }\n\n load = async (): Promise<void> => {\n const promise = new Promise<void>(async (resolve, reject) => {\n const next = this.latestLocation\n const prevLocation = this.state.resolvedLocation\n const pathDidChange = prevLocation!.href !== next.href\n let latestPromise: Promise<void> | undefined | null\n\n // Cancel any pending matches\n this.cancelMatches()\n\n this.emit({\n type: 'onBeforeLoad',\n fromLocation: prevLocation,\n toLocation: next,\n pathChanged: pathDidChange,\n })\n\n let pendingMatches!: RouteMatch<any, any>[]\n const previousMatches = this.state.matches\n\n this.__store.batch(() => {\n this.cleanCache()\n\n // Match the routes\n pendingMatches = this.matchRoutes(next.pathname, next.search, {\n debug: true,\n })\n\n // Ingest the new matches\n // If a cached moved to pendingMatches, remove it from cachedMatches\n this.__store.setState((s) => ({\n ...s,\n isLoading: true,\n location: next,\n pendingMatches,\n cachedMatches: s.cachedMatches.filter((d) => {\n return !pendingMatches.find((e) => e.id === d.id)\n }),\n }))\n })\n\n try {\n try {\n // Load the matches\n await this.loadMatches({\n matches: pendingMatches,\n checkLatest: () => this.checkLatest(promise),\n })\n } catch (err) {\n // swallow this error, since we'll display the\n // errors on the route components\n }\n\n // Only apply the latest transition\n if ((latestPromise = this.checkLatest(promise))) {\n return latestPromise\n }\n\n const exitingMatches = previousMatches.filter(\n (match) => !pendingMatches.find((d) => d.id === match.id),\n )\n const enteringMatches = pendingMatches.filter(\n (match) => !previousMatches.find((d) => d.id === match.id),\n )\n const stayingMatches = previousMatches.filter((match) =>\n pendingMatches.find((d) => d.id === match.id),\n )\n\n // Commit the pending matches. If a previous match was\n // removed, place it in the cachedMatches\n this.__store.batch(() => {\n this.__store.setState((s) => ({\n ...s,\n isLoading: false,\n matches: s.pendingMatches!,\n pendingMatches: undefined,\n cachedMatches: [\n ...s.cachedMatches,\n ...exitingMatches.filter((d) => d.status !== 'error'),\n ],\n }))\n this.cleanCache()\n })\n\n //\n ;(\n [\n [exitingMatches, 'onLeave'],\n [enteringMatches, 'onEnter'],\n [stayingMatches, 'onStay'],\n ] as const\n ).forEach(([matches, hook]) => {\n matches.forEach((match) => {\n this.looseRoutesById[match.routeId]!.options[hook]?.(match)\n })\n })\n\n this.emit({\n type: 'onLoad',\n fromLocation: prevLocation,\n toLocation: next,\n pathChanged: pathDidChange,\n })\n\n resolve()\n } catch (err) {\n // Only apply the latest transition\n if ((latestPromise = this.checkLatest(promise))) {\n return latestPromise\n }\n\n reject(err)\n }\n })\n\n this.latestLoadPromise = promise\n\n return this.latestLoadPromise\n }\n\n cleanCache = () => {\n // This is where all of the garbage collection magic happens\n this.__store.setState((s) => {\n return {\n ...s,\n cachedMatches: s.cachedMatches.filter((d) => {\n const route = this.looseRoutesById[d.routeId]!\n\n if (!route.options.loader) {\n return false\n }\n\n // If the route was preloaded, use the preloadGcTime\n // otherwise, use the gcTime\n const gcTime =\n (d.preload\n ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime\n : route.options.gcTime ?? this.options.defaultGcTime) ??\n 5 * 60 * 1000\n\n return d.status !== 'error' && Date.now() - d.updatedAt < gcTime\n }),\n }\n })\n }\n\n preloadRoute = async (\n navigateOpts: ToOptions<TRouteTree> = this.state.location as any,\n ) => {\n let next = this.buildLocation(navigateOpts as any)\n\n let matches = this.matchRoutes(next.pathname, next.search, {\n throwOnError: true,\n })\n\n const loadedMatchIds = Object.fromEntries(\n [\n ...this.state.matches,\n ...(this.state.pendingMatches ?? []),\n ...this.state.cachedMatches,\n ]?.map((d) => [d.id, true]),\n )\n\n this.__store.batch(() => {\n matches.forEach((match) => {\n if (!loadedMatchIds[match.id]) {\n this.__store.setState((s) => ({\n ...s,\n cachedMatches: [...(s.cachedMatches as any), match],\n }))\n }\n })\n })\n\n matches = await this.loadMatches({\n matches,\n preload: true,\n checkLatest: () => undefined,\n })\n\n return matches\n }\n\n matchRoute = <\n TFrom extends RoutePaths<TRouteTree> = '/',\n TTo extends string = '',\n TResolved = ResolveRelativePath<TFrom, NoInfer<TTo>>,\n >(\n location: ToOptions<TRouteTree, TFrom, TTo>,\n opts?: MatchRouteOptions,\n ): false | RouteById<TRouteTree, TResolved>['types']['allParams'] => {\n const matchLocation = {\n ...location,\n to: location.to\n ? this.resolvePathWithBase((location.from || '') as string, location.to)\n : undefined,\n params: location.params || {},\n leaveParams: true,\n }\n const next = this.buildLocation(matchLocation as any)\n\n if (opts?.pending && this.state.status !== 'pending') {\n return false\n }\n\n const baseLocation = opts?.pending\n ? this.latestLocation\n : this.state.resolvedLocation\n\n if (!baseLocation) {\n return false\n }\n const match = matchPathname(this.basepath, baseLocation.pathname, {\n ...opts,\n to: next.pathname,\n }) as any\n\n if (!match) {\n return false\n }\n if (location.params) {\n if (!deepEqual(match, location.params, true)) {\n return false\n }\n }\n\n if (match && (opts?.includeSearch ?? true)) {\n return deepEqual(baseLocation.search, next.search, true) ? match : false\n }\n\n return match\n }\n\n injectHtml = async (html: string | (() => Promise<string> | string)) => {\n this.injectedHtml.push(html)\n }\n\n dehydrateData = <T>(key: any, getData: T | (() => Promise<T> | T)) => {\n if (typeof document === 'undefined') {\n const strKey = typeof key === 'string' ? key : JSON.stringify(key)\n\n this.injectHtml(async () => {\n const id = `__TSR_DEHYDRATED__${strKey}`\n const data =\n typeof getData === 'function' ? await (getData as any)() : getData\n return `<script id='${id}' suppressHydrationWarning>window[\"__TSR_DEHYDRATED__${escapeJSON(\n strKey,\n )}\"] = ${JSON.stringify(this.options.transformer.stringify(data))}\n ;(() => {\n var el = document.getElementById('${id}')\n el.parentElement.removeChild(el)\n })()\n </script>`\n })\n\n return () => this.hydrateData<T>(key)\n }\n\n return () => undefined\n }\n\n hydrateData = <T extends any = unknown>(key: any) => {\n if (typeof document !== 'undefined') {\n const strKey = typeof key === 'string' ? key : JSON.stringify(key)\n\n return this.options.transformer.parse(\n window[`__TSR_DEHYDRATED__${strKey}` as any] as unknown as string,\n ) as T\n }\n\n return undefined\n }\n\n dehydrate = (): DehydratedRouter => {\n const pickError =\n this.options.errorSerializer?.serialize ?? defaultSerializeError\n\n return {\n state: {\n dehydratedMatches: this.state.matches.map((d) => ({\n ...pick(d, [\n 'id',\n 'status',\n 'updatedAt',\n 'loaderData',\n // Not-founds that occur during SSR don't require the client to load data before\n // triggering in order to prevent the flicker of the loading component\n 'notFoundError',\n ]),\n // If an error occurs server-side during SSRing,\n // send a small subset of the error to the client\n error: d.error\n ? {\n data: pickError(d.error),\n __isServerError: true,\n }\n : undefined,\n })),\n },\n }\n }\n\n hydrate = async (__do_not_use_server_ctx?: string) => {\n let _ctx = __do_not_use_server_ctx\n // Client hydrates from window\n if (typeof document !== 'undefined') {\n _ctx = window.__TSR_DEHYDRATED__?.data\n }\n\n invariant(\n _ctx,\n 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?',\n )\n\n const ctx = this.options.transformer.parse(_ctx) as HydrationCtx\n this.dehydratedData = ctx.payload as any\n this.options.hydrate?.(ctx.payload as any)\n const dehydratedState = ctx.router.state\n\n let matches = this.matchRoutes(\n this.state.location.pathname,\n this.state.location.search,\n ).map((match) => {\n const dehydratedMatch = dehydratedState.dehydratedMatches.find(\n (d) => d.id === match.id,\n )\n\n invariant(\n dehydratedMatch,\n `Could not find a client-side match for dehydrated match with id: ${match.id}!`,\n )\n\n if (dehydratedMatch) {\n const route = this.looseRoutesById[match.routeId]!\n\n return {\n ...match,\n ...dehydratedMatch,\n meta: route.options.meta?.({\n loaderData: dehydratedMatch.loaderData,\n }),\n links: route.options.links?.(),\n scripts: route.options.scripts?.(),\n }\n }\n return match\n })\n\n this.__store.setState((s) => {\n return {\n ...s,\n matches: matches as any,\n lastUpdated: Date.now(),\n }\n })\n }\n\n // Finds a match that has a notFoundComponent\n updateMatchesWithNotFound = (\n matches: AnyRouteMatch[],\n currentMatch: AnyRouteMatch,\n err: NotFoundError,\n ) => {\n const matchesByRouteId = Object.fromEntries(\n matches.map((match) => [match.routeId, match]),\n ) as Record<string, AnyRouteMatch>\n\n if (err.global) {\n matchesByRouteId[rootRouteId]!.notFoundError = err\n } else {\n // If the err contains a routeId, start searching up from that route\n let currentRoute = (this.routesById as any)[\n err.route ?? currentMatch.routeId\n ] as AnyRoute\n\n // Go up the tree until we find a route with a notFoundComponent\n while (!currentRoute.options.notFoundComponent) {\n currentRoute = currentRoute?.parentRoute\n\n invariant(\n currentRoute,\n 'Found invalid route tree while trying to find not-found handler.',\n )\n\n if (currentRoute.id === rootRouteId) break\n }\n\n const match = matchesByRouteId[currentRoute.id]\n invariant(match, 'Could not find match for route: ' + currentRoute.id)\n match.notFoundError = err\n }\n }\n\n hasNotFoundMatch = () => {\n return this.__store.state.matches.some((d) => d.notFoundError)\n }\n\n // resolveMatchPromise = (matchId: string, key: string, value: any) => {\n // state.matches\n // .find((d) => d.id === matchId)\n // ?.__promisesByKey[key]?.resolve(value)\n // }\n}\n\n// A function that takes an import() argument which is a function and returns a new function that will\n// proxy arguments from the caller to the imported function, retaining all type\n// information along the way\nexport function lazyFn<\n T extends Record<string, (...args: any[]) => any>,\n TKey extends keyof T = 'default',\n>(fn: () => Promise<T>, key?: TKey) {\n return async (\n ...args: Parameters<T[TKey]>\n ): Promise<Awaited<ReturnType<T[TKey]>>> => {\n const imported = await fn()\n return imported[key || 'default'](...args)\n }\n}\n\nexport class SearchParamError extends Error {}\n\nexport class PathParamError extends Error {}\n\nexport function getInitialRouterState(\n location: ParsedLocation,\n): RouterState<any> {\n return {\n isLoading: false,\n isTransitioning: false,\n status: 'idle',\n resolvedLocation: { ...location },\n location,\n matches: [],\n pendingMatches: [],\n cachedMatches: [],\n lastUpdated: 0,\n }\n}\n\nexport function defaultSerializeError(err: unknown) {\n if (err instanceof Error)\n return {\n name: err.name,\n message: err.message,\n }\n\n return {\n data: err,\n }\n}\n"],"names":["trimPath","createBrowserHistory","createMemoryHistory","Store","trimPathRight","trimPathLeft","parsePathname","d","replaceEqualDeep","path","resolvePath","cleanPath","route","matchPathname","searchError","interpolatePath","getRouteMatch","rootRouteId","joinPaths","last","functionalUpdate","pick","_a","isRedirect","isNotFound","_b","deepEqual","escapeJSON","_c","defaultStringifySearch","defaultParseSearch"],"mappings":";;;;;;;;;;;;AA8MO,MAAM,iBAAiB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA8BO,SAAS,aAKd,SACA;AACO,SAAA,IAAI,OAAkD,OAAO;AACtE;AAEO,MAAM,OAIX;AAAA;AAAA;AAAA;AAAA,EAkCA,YACE,SAKA;AAtCF,SAAA,kBAAsC,GAAG,KAAK;AAAA,MAC5C,KAAK,WAAW;AAAA,IACjB,CAAA;AAC0B,SAAA,kBAAA;AACO,SAAA,kBAAA;AAClC,SAAA,oBAAmC,QAAQ;AAC3C,SAAA,kCAAkB;AAClB,SAAA,eAAoC;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A6wCF;AAKgB,SAAA,OAGd,IAAsB,KAAY;AAClC,SAAO,UACF,SACuC;AACpC,UAAA,WAAW,MAAM;AACvB,WAAO,SAAS,OAAO,SAAS,EAAE,GAAG,IAAI;AAAA,EAAA;AAE7C;AAEO,MAAM,yBAAyB,MAAM;AAAC;AAEtC,MAAM,uBAAuB,MAAM;AAAC;AAEpC,SAAS,sBACd,UACkB;AACX,SAAA;AAAA,IACL,WAAW;AAAA,IACX,iBAAiB;AAAA,IACjB,QAAQ;AAAA,IACR,kBAAkB,EAAE,GAAG,SAAS;AAAA,IAChC;AAAA,IACA,SAAS,CAAC;AAAA,IACV,gBAAgB,CAAC;AAAA,IACjB,eAAe,CAAC;AAAA,IAChB,aAAa;AAAA,EAAA;AAEjB;AAEO,SAAS,sBAAsB,KAAc;AAClD,MAAI,eAAe;AACV,WAAA;AAAA,MACL,MAAM,IAAI;AAAA,MACV,SAAS,IAAI;AAAA,IAAA;AAGV,SAAA;AAAA,IACL,MAAM;AAAA,EAAA;AAEV;;;;;;;;;"}
@@ -0,0 +1,36 @@
1
+ export declare const XTSROrigin = "x-tsr-origin";
2
+ export interface JsonResponse<TData> extends Response {
3
+ json(): Promise<TData>;
4
+ }
5
+ export type FetcherOptionsBase = {
6
+ method?: 'GET' | 'POST';
7
+ };
8
+ export type FetcherOptions = FetcherOptionsBase & {
9
+ requestInit?: RequestInit;
10
+ };
11
+ export type FetchFnCtx = {
12
+ method: 'GET' | 'POST';
13
+ request: Request;
14
+ };
15
+ export type FetchFn<TPayload, TResponse> = {
16
+ (payload: TPayload, ctx: FetchFnCtx): TResponse;
17
+ url?: string;
18
+ };
19
+ export type CompiledFetcherFnOptions<TPayload> = {
20
+ method: 'GET' | 'POST';
21
+ type: 'request' | 'payload';
22
+ payload: TPayload;
23
+ requestInit?: RequestInit;
24
+ };
25
+ export type CompiledFetcherFn<TPayload, TResponse> = {
26
+ (opts: CompiledFetcherFnOptions<TPayload>): Promise<TResponse>;
27
+ url: string;
28
+ };
29
+ export type Fetcher<TPayload, TResponse> = (TPayload extends undefined ? {
30
+ (payload?: TPayload, opts?: FetcherOptions): Promise<TResponse>;
31
+ } : {
32
+ (payload: TPayload, opts?: FetcherOptions): Promise<TResponse>;
33
+ }) & {
34
+ url: string;
35
+ };
36
+ export declare function createServerFn<TPayload, TResponse>(method: 'GET' | 'POST', fn: FetchFn<TPayload, TResponse>): Fetcher<TPayload, TResponse>;
@@ -0,0 +1,32 @@
1
+ import invariant from "tiny-invariant";
2
+ const XTSROrigin = "x-tsr-origin";
3
+ function createServerFn(method, fn) {
4
+ const compiledFn = fn;
5
+ console.log(
6
+ compiledFn,
7
+ compiledFn.toString(),
8
+ JSON.stringify(compiledFn, null, 2)
9
+ );
10
+ invariant(
11
+ compiledFn.url,
12
+ `createServerFn must be called with a function that is marked with the 'use server' pragma.`
13
+ );
14
+ return Object.assign(
15
+ async (payload, opts) => {
16
+ return compiledFn({
17
+ method,
18
+ type: payload instanceof Request ? "request" : "payload",
19
+ payload,
20
+ requestInit: opts == null ? void 0 : opts.requestInit
21
+ });
22
+ },
23
+ {
24
+ url: fn.url
25
+ }
26
+ );
27
+ }
28
+ export {
29
+ XTSROrigin,
30
+ createServerFn
31
+ };
32
+ //# sourceMappingURL=createServerFn.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createServerFn.js","sources":["../../src/createServerFn.ts"],"sourcesContent":["import invariant from 'tiny-invariant'\n\nexport const XTSROrigin = 'x-tsr-origin'\n\nexport interface JsonResponse<TData> extends Response {\n json(): Promise<TData>\n}\n\nexport type FetcherOptionsBase = {\n method?: 'GET' | 'POST'\n}\n\nexport type FetcherOptions = FetcherOptionsBase & {\n requestInit?: RequestInit\n}\n\nexport type FetchFnCtx = {\n method: 'GET' | 'POST'\n request: Request\n}\n\nexport type FetchFn<TPayload, TResponse> = {\n (payload: TPayload, ctx: FetchFnCtx): TResponse\n url?: string\n}\n\n// export type AnyFetchFn = FetchFn<any, any>\n\n// export type FetchFnReturn<T extends AnyFetchFn> =\n// Awaited<ReturnType<T>> extends JsonResponse<infer R> ? R : ReturnType<T>\n\n// export type FetcherFn<T extends AnyFetchFn> = Parameters<T>[0] extends undefined\n// ? (\n// payload?: Parameters<T>['0'],\n// opts?: FetchFnCtx,\n// ) => Promise<Awaited<FetchFnReturn<T>>>\n// : (\n// payload: Parameters<T>['0'],\n// opts?: FetchFnCtx,\n// ) => Promise<Awaited<FetchFnReturn<T>>>\n\n// export type FetcherMethods<T extends AnyFetchFn> = {\n// url: string\n// fetch: (\n// init: RequestInit,\n// opts?: FetcherOptions,\n// ) => Promise<Awaited<FetchFnReturn<T>>>\n// }\n\n// export type Fetcher<T extends AnyFetchFn> = FetcherFn<T> & FetcherMethods<T>\n\nexport type CompiledFetcherFnOptions<TPayload> = {\n method: 'GET' | 'POST'\n type: 'request' | 'payload'\n payload: TPayload\n requestInit?: RequestInit\n}\n\nexport type CompiledFetcherFn<TPayload, TResponse> = {\n (opts: CompiledFetcherFnOptions<TPayload>): Promise<TResponse>\n url: string\n}\n\nexport type Fetcher<TPayload, TResponse> = (TPayload extends undefined\n ? {\n (payload?: TPayload, opts?: FetcherOptions): Promise<TResponse>\n }\n : {\n (payload: TPayload, opts?: FetcherOptions): Promise<TResponse>\n }) & {\n url: string\n}\n\nexport function createServerFn<TPayload, TResponse>(\n method: 'GET' | 'POST',\n fn: FetchFn<TPayload, TResponse>,\n): Fetcher<TPayload, TResponse> {\n // Cast the compiled function that will be injected by vinxi\n const compiledFn = fn as unknown as CompiledFetcherFn<TPayload, TResponse>\n\n console.log(\n compiledFn,\n compiledFn.toString(),\n JSON.stringify(compiledFn, null, 2),\n )\n\n invariant(\n compiledFn.url,\n `createServerFn must be called with a function that is marked with the 'use server' pragma.`,\n )\n\n return Object.assign(\n async (payload: TPayload, opts?: FetcherOptions) => {\n return compiledFn({\n method,\n type: payload instanceof Request ? 'request' : 'payload',\n payload,\n requestInit: opts?.requestInit,\n })\n },\n {\n url: fn.url!,\n },\n ) as Fetcher<TPayload, TResponse>\n}\n"],"names":[],"mappings":";AAEO,MAAM,aAAa;AAuEV,SAAA,eACd,QACA,IAC8B;AAE9B,QAAM,aAAa;AAEX,UAAA;AAAA,IACN;AAAA,IACA,WAAW,SAAS;AAAA,IACpB,KAAK,UAAU,YAAY,MAAM,CAAC;AAAA,EAAA;AAGpC;AAAA,IACE,WAAW;AAAA,IACX;AAAA,EAAA;AAGF,SAAO,OAAO;AAAA,IACZ,OAAO,SAAmB,SAA0B;AAClD,aAAO,WAAW;AAAA,QAChB;AAAA,QACA,MAAM,mBAAmB,UAAU,YAAY;AAAA,QAC/C;AAAA,QACA,aAAa,6BAAM;AAAA,MAAA,CACpB;AAAA,IACH;AAAA,IACA;AAAA,MACE,KAAK,GAAG;AAAA,IACV;AAAA,EAAA;AAEJ;"}
@@ -29,3 +29,4 @@ export * from './useRouter.js';
29
29
  export * from './useRouterState.js';
30
30
  export * from './utils.js';
31
31
  export * from './not-found.js';
32
+ export * from './createServerFn.js';
package/dist/esm/index.js CHANGED
@@ -26,6 +26,7 @@ import { useRouter } from "./useRouter.js";
26
26
  import { useRouterState } from "./useRouterState.js";
27
27
  import { deepEqual, escapeJSON, functionalUpdate, isPlainArray, isPlainObject, isServer, last, pick, replaceEqualDeep, shallow, useLayoutEffect, useStableCallback } from "./utils.js";
28
28
  import { CatchNotFound, DefaultGlobalNotFound, isNotFound, notFound } from "./not-found.js";
29
+ import { XTSROrigin, createServerFn } from "./createServerFn.js";
29
30
  export {
30
31
  Await,
31
32
  Block,
@@ -52,6 +53,7 @@ export {
52
53
  RouterProvider,
53
54
  ScrollRestoration,
54
55
  SearchParamError,
56
+ XTSROrigin,
55
57
  cleanPath,
56
58
  componentTypes,
57
59
  createFileRoute,
@@ -62,6 +64,7 @@ export {
62
64
  createRoute,
63
65
  createRouteMask,
64
66
  createRouter,
67
+ createServerFn,
65
68
  decode,
66
69
  deepEqual,
67
70
  defaultDeserializeError,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -649,7 +649,10 @@ class Router {
649
649
  return true;
650
650
  }
651
651
  if (isNotFound(err)) {
652
- this.updateMatchesWithNotFound(matches, match, err);
652
+ if (!preload) {
653
+ this.updateMatchesWithNotFound(matches, match, err);
654
+ }
655
+ return true;
653
656
  }
654
657
  return false;
655
658
  };
@@ -715,7 +718,7 @@ class Router {
715
718
  const loaderData = await loadPromise;
716
719
  if (latestPromise = checkLatest())
717
720
  return await latestPromise;
718
- if (isRedirect(loaderData)) {
721
+ if (isRedirect(loaderData) || isNotFound(loaderData)) {
719
722
  if (handleErrorAndRedirect(loaderData))
720
723
  return;
721
724
  }
@@ -1 +1 @@
1
- {"version":3,"file":"router.js","sources":["../../src/router.ts"],"sourcesContent":["import {\n HistoryLocation,\n HistoryState,\n RouterHistory,\n createBrowserHistory,\n createMemoryHistory,\n} from '@tanstack/history'\nimport { Store } from '@tanstack/react-store'\n\n//\n\nimport {\n AnySearchSchema,\n AnyRoute,\n AnyContext,\n AnyPathParams,\n RouteMask,\n Route,\n LoaderFnContext,\n rootRouteId,\n} from './route'\nimport {\n FullSearchSchema,\n RouteById,\n RoutePaths,\n RoutesById,\n RoutesByPath,\n} from './routeInfo'\nimport { defaultParseSearch, defaultStringifySearch } from './searchParams'\nimport {\n PickAsRequired,\n Updater,\n NonNullableUpdater,\n replaceEqualDeep,\n deepEqual,\n escapeJSON,\n functionalUpdate,\n last,\n pick,\n Timeout,\n} from './utils'\nimport { RouteComponent } from './route'\nimport { AnyRouteMatch, MatchRouteOptions, RouteMatch } from './Matches'\nimport { ParsedLocation } from './location'\nimport { SearchSerializer, SearchParser } from './searchParams'\nimport {\n BuildLocationFn,\n CommitLocationOptions,\n InjectedHtmlEntry,\n NavigateFn,\n getRouteMatch,\n} from './RouterProvider'\n\nimport {\n cleanPath,\n interpolatePath,\n joinPaths,\n matchPathname,\n parsePathname,\n resolvePath,\n trimPath,\n trimPathLeft,\n trimPathRight,\n} from './path'\nimport invariant from 'tiny-invariant'\nimport { isRedirect } from './redirects'\nimport { NotFoundError, isNotFound } from './not-found'\nimport { ResolveRelativePath, ToOptions } from './link'\nimport { NoInfer } from '@tanstack/react-store'\n// import warning from 'tiny-warning'\n\n//\n\ndeclare global {\n interface Window {\n __TSR_DEHYDRATED__?: { data: string }\n __TSR_ROUTER_CONTEXT__?: React.Context<Router<any>>\n }\n}\n\nexport interface Register {\n // router: Router\n}\n\nexport type AnyRouter = Router<AnyRoute, any>\n\nexport type RegisteredRouter = Register extends {\n router: infer TRouter extends AnyRouter\n}\n ? TRouter\n : AnyRouter\n\nexport type HydrationCtx = {\n router: DehydratedRouter\n payload: Record<string, any>\n}\n\nexport type RouterContextOptions<TRouteTree extends AnyRoute> =\n AnyContext extends TRouteTree['types']['routerContext']\n ? {\n context?: TRouteTree['types']['routerContext']\n }\n : {\n context: TRouteTree['types']['routerContext']\n }\n\nexport interface RouterOptions<\n TRouteTree extends AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n> {\n history?: RouterHistory\n stringifySearch?: SearchSerializer\n parseSearch?: SearchParser\n defaultPreload?: false | 'intent'\n defaultPreloadDelay?: number\n defaultComponent?: RouteComponent\n defaultErrorComponent?: RouteComponent\n defaultPendingComponent?: RouteComponent\n defaultPendingMs?: number\n defaultPendingMinMs?: number\n defaultStaleTime?: number\n defaultPreloadStaleTime?: number\n defaultPreloadGcTime?: number\n defaultGcTime?: number\n caseSensitive?: boolean\n routeTree?: TRouteTree\n basepath?: string\n context?: TRouteTree['types']['routerContext']\n dehydrate?: () => TDehydrated\n hydrate?: (dehydrated: TDehydrated) => void\n routeMasks?: RouteMask<TRouteTree>[]\n unmaskOnReload?: boolean\n Wrap?: (props: { children: any }) => JSX.Element\n InnerWrap?: (props: { children: any }) => JSX.Element\n /**\n * @deprecated\n * Use `notFoundComponent` instead.\n * See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.\n */\n notFoundRoute?: AnyRoute\n transformer?: RouterTransformer\n errorSerializer?: RouterErrorSerializer<TSerializedError>\n globalNotFound?: RouteComponent\n}\n\nexport interface RouterTransformer {\n stringify: (obj: unknown) => string\n parse: (str: string) => unknown\n}\nexport interface RouterErrorSerializer<TSerializedError> {\n serialize: (err: unknown) => TSerializedError\n deserialize: (err: TSerializedError) => unknown\n}\n\nexport interface RouterState<TRouteTree extends AnyRoute = AnyRoute> {\n status: 'pending' | 'idle'\n isLoading: boolean\n isTransitioning: boolean\n matches: RouteMatch<TRouteTree>[]\n pendingMatches?: RouteMatch<TRouteTree>[]\n cachedMatches: RouteMatch<TRouteTree>[]\n location: ParsedLocation<FullSearchSchema<TRouteTree>>\n resolvedLocation: ParsedLocation<FullSearchSchema<TRouteTree>>\n lastUpdated: number\n}\n\nexport type ListenerFn<TEvent extends RouterEvent> = (event: TEvent) => void\n\nexport interface BuildNextOptions {\n to?: string | number | null\n params?: true | Updater<unknown>\n search?: true | Updater<unknown>\n hash?: true | Updater<string>\n state?: true | NonNullableUpdater<HistoryState>\n mask?: {\n to?: string | number | null\n params?: true | Updater<unknown>\n search?: true | Updater<unknown>\n hash?: true | Updater<string>\n state?: true | NonNullableUpdater<HistoryState>\n unmaskOnReload?: boolean\n }\n from?: string\n}\n\nexport interface DehydratedRouterState {\n dehydratedMatches: DehydratedRouteMatch[]\n}\n\nexport type DehydratedRouteMatch = Pick<\n RouteMatch,\n 'id' | 'status' | 'updatedAt' | 'notFoundError' | 'loaderData'\n>\n\nexport interface DehydratedRouter {\n state: DehydratedRouterState\n}\n\nexport type RouterConstructorOptions<\n TRouteTree extends AnyRoute,\n TDehydrated extends Record<string, any>,\n TSerializedError extends Record<string, any>,\n> = Omit<RouterOptions<TRouteTree, TDehydrated, TSerializedError>, 'context'> &\n RouterContextOptions<TRouteTree>\n\nexport const componentTypes = [\n 'component',\n 'errorComponent',\n 'pendingComponent',\n 'notFoundComponent',\n] as const\n\nexport type RouterEvents = {\n onBeforeLoad: {\n type: 'onBeforeLoad'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n onLoad: {\n type: 'onLoad'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n onResolved: {\n type: 'onResolved'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n}\n\nexport type RouterEvent = RouterEvents[keyof RouterEvents]\n\nexport type RouterListener<TRouterEvent extends RouterEvent> = {\n eventType: TRouterEvent['type']\n fn: ListenerFn<TRouterEvent>\n}\n\nexport function createRouter<\n TRouteTree extends AnyRoute = AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n>(\n options: RouterConstructorOptions<TRouteTree, TDehydrated, TSerializedError>,\n) {\n return new Router<TRouteTree, TDehydrated, TSerializedError>(options)\n}\n\nexport class Router<\n TRouteTree extends AnyRoute = AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n> {\n // Option-independent properties\n tempLocationKey: string | undefined = `${Math.round(\n Math.random() * 10000000,\n )}`\n resetNextScroll: boolean = true\n navigateTimeout: Timeout | null = null\n latestLoadPromise: Promise<void> = Promise.resolve()\n subscribers = new Set<RouterListener<RouterEvent>>()\n injectedHtml: InjectedHtmlEntry[] = []\n dehydratedData?: TDehydrated\n\n // Must build in constructor\n __store!: Store<RouterState<TRouteTree>>\n options!: PickAsRequired<\n Omit<\n RouterOptions<TRouteTree, TDehydrated, TSerializedError>,\n 'transformer'\n > & {\n transformer: RouterTransformer\n },\n 'stringifySearch' | 'parseSearch' | 'context'\n >\n history!: RouterHistory\n latestLocation!: ParsedLocation\n basepath!: string\n routeTree!: TRouteTree\n routesById!: RoutesById<TRouteTree>\n routesByPath!: RoutesByPath<TRouteTree>\n flatRoutes!: AnyRoute[]\n\n /**\n * @deprecated Use the `createRouter` function instead\n */\n constructor(\n options: RouterConstructorOptions<\n TRouteTree,\n TDehydrated,\n TSerializedError\n >,\n ) {\n this.update({\n defaultPreloadDelay: 50,\n defaultPendingMs: 1000,\n defaultPendingMinMs: 500,\n context: undefined!,\n ...options,\n stringifySearch: options?.stringifySearch ?? defaultStringifySearch,\n parseSearch: options?.parseSearch ?? defaultParseSearch,\n transformer: options?.transformer ?? JSON,\n })\n }\n\n // These are default implementations that can optionally be overridden\n // by the router provider once rendered. We provide these so that the\n // router can be used in a non-react environment if necessary\n startReactTransition: (fn: () => void) => void = (fn) => fn()\n\n update = (\n newOptions: RouterConstructorOptions<\n TRouteTree,\n TDehydrated,\n TSerializedError\n >,\n ) => {\n if (newOptions.notFoundRoute) {\n console.warn(\n 'The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.',\n )\n }\n\n const previousOptions = this.options\n this.options = {\n ...this.options,\n ...newOptions,\n }\n\n if (\n !this.basepath ||\n (newOptions.basepath && newOptions.basepath !== previousOptions.basepath)\n ) {\n if (\n newOptions.basepath === undefined ||\n newOptions.basepath === '' ||\n newOptions.basepath === '/'\n ) {\n this.basepath = '/'\n } else {\n this.basepath = `/${trimPath(newOptions.basepath)}`\n }\n }\n\n if (\n !this.history ||\n (this.options.history && this.options.history !== this.history)\n ) {\n this.history =\n this.options.history ??\n (typeof document !== 'undefined'\n ? createBrowserHistory()\n : createMemoryHistory({\n initialEntries: [this.options.basepath || '/'],\n }))\n this.latestLocation = this.parseLocation()\n }\n\n if (this.options.routeTree !== this.routeTree) {\n this.routeTree = this.options.routeTree as TRouteTree\n this.buildRouteTree()\n }\n\n if (!this.__store) {\n this.__store = new Store(getInitialRouterState(this.latestLocation), {\n onUpdate: () => {\n this.__store.state = {\n ...this.state,\n status:\n this.state.isTransitioning || this.state.isLoading\n ? 'pending'\n : 'idle',\n }\n },\n })\n }\n }\n\n get state() {\n return this.__store.state\n }\n\n buildRouteTree = () => {\n this.routesById = {} as RoutesById<TRouteTree>\n this.routesByPath = {} as RoutesByPath<TRouteTree>\n\n const notFoundRoute = this.options.notFoundRoute\n if (notFoundRoute) {\n notFoundRoute.init({ originalIndex: 99999999999 })\n ;(this.routesById as any)[notFoundRoute.id] = notFoundRoute\n }\n\n const recurseRoutes = (childRoutes: AnyRoute[]) => {\n childRoutes.forEach((childRoute, i) => {\n childRoute.init({ originalIndex: i })\n\n const existingRoute = (this.routesById as any)[childRoute.id]\n\n invariant(\n !existingRoute,\n `Duplicate routes found with id: ${String(childRoute.id)}`,\n )\n ;(this.routesById as any)[childRoute.id] = childRoute\n\n if (!childRoute.isRoot && childRoute.path) {\n const trimmedFullPath = trimPathRight(childRoute.fullPath)\n if (\n !(this.routesByPath as any)[trimmedFullPath] ||\n childRoute.fullPath.endsWith('/')\n ) {\n ;(this.routesByPath as any)[trimmedFullPath] = childRoute\n }\n }\n\n const children = childRoute.children as Route[]\n\n if (children?.length) {\n recurseRoutes(children)\n }\n })\n }\n\n recurseRoutes([this.routeTree])\n\n const scoredRoutes: {\n child: AnyRoute\n trimmed: string\n parsed: ReturnType<typeof parsePathname>\n index: number\n scores: number[]\n }[] = []\n\n ;(Object.values(this.routesById) as AnyRoute[]).forEach((d, i) => {\n if (d.isRoot || !d.path) {\n return\n }\n\n const trimmed = trimPathLeft(d.fullPath)\n const parsed = parsePathname(trimmed)\n\n while (parsed.length > 1 && parsed[0]?.value === '/') {\n parsed.shift()\n }\n\n const scores = parsed.map((d) => {\n if (d.value === '/') {\n return 0.75\n }\n\n if (d.type === 'param') {\n return 0.5\n }\n\n if (d.type === 'wildcard') {\n return 0.25\n }\n\n return 1\n })\n\n scoredRoutes.push({ child: d, trimmed, parsed, index: i, scores })\n })\n\n this.flatRoutes = scoredRoutes\n .sort((a, b) => {\n const minLength = Math.min(a.scores.length, b.scores.length)\n\n // Sort by min available score\n for (let i = 0; i < minLength; i++) {\n if (a.scores[i] !== b.scores[i]) {\n return b.scores[i]! - a.scores[i]!\n }\n }\n\n // Sort by length of score\n if (a.scores.length !== b.scores.length) {\n return b.scores.length - a.scores.length\n }\n\n // Sort by min available parsed value\n for (let i = 0; i < minLength; i++) {\n if (a.parsed[i]!.value !== b.parsed[i]!.value) {\n return a.parsed[i]!.value! > b.parsed[i]!.value! ? 1 : -1\n }\n }\n\n // Sort by original index\n return a.index - b.index\n })\n .map((d, i) => {\n d.child.rank = i\n return d.child\n })\n }\n\n subscribe = <TType extends keyof RouterEvents>(\n eventType: TType,\n fn: ListenerFn<RouterEvents[TType]>,\n ) => {\n const listener: RouterListener<any> = {\n eventType,\n fn,\n }\n\n this.subscribers.add(listener)\n\n return () => {\n this.subscribers.delete(listener)\n }\n }\n\n emit = (routerEvent: RouterEvent) => {\n this.subscribers.forEach((listener) => {\n if (listener.eventType === routerEvent.type) {\n listener.fn(routerEvent)\n }\n })\n }\n\n checkLatest = (promise: Promise<void>): undefined | Promise<void> => {\n return this.latestLoadPromise !== promise\n ? this.latestLoadPromise\n : undefined\n }\n\n parseLocation = (\n previousLocation?: ParsedLocation,\n ): ParsedLocation<FullSearchSchema<TRouteTree>> => {\n const parse = ({\n pathname,\n search,\n hash,\n state,\n }: HistoryLocation): ParsedLocation<FullSearchSchema<TRouteTree>> => {\n const parsedSearch = this.options.parseSearch(search)\n const searchStr = this.options.stringifySearch(parsedSearch)\n\n return {\n pathname: pathname,\n searchStr,\n search: replaceEqualDeep(previousLocation?.search, parsedSearch) as any,\n hash: hash.split('#').reverse()[0] ?? '',\n href: `${pathname}${searchStr}${hash}`,\n state: replaceEqualDeep(previousLocation?.state, state) as HistoryState,\n }\n }\n\n const location = parse(this.history.location)\n\n let { __tempLocation, __tempKey } = location.state\n\n if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {\n // Sync up the location keys\n const parsedTempLocation = parse(__tempLocation) as any\n parsedTempLocation.state.key = location.state.key\n\n delete parsedTempLocation.state.__tempLocation\n\n return {\n ...parsedTempLocation,\n maskedLocation: location,\n }\n }\n\n return location\n }\n\n resolvePathWithBase = (from: string, path: string) => {\n return resolvePath(this.basepath!, from, cleanPath(path))\n }\n\n get looseRoutesById() {\n return this.routesById as Record<string, AnyRoute>\n }\n\n matchRoutes = <TRouteTree extends AnyRoute>(\n pathname: string,\n locationSearch: AnySearchSchema,\n opts?: { throwOnError?: boolean; debug?: boolean },\n ): RouteMatch<TRouteTree>[] => {\n let routeParams: Record<string, string> = {}\n\n let foundRoute = this.flatRoutes.find((route) => {\n const matchedParams = matchPathname(\n this.basepath,\n trimPathRight(pathname),\n {\n to: route.fullPath,\n caseSensitive:\n route.options.caseSensitive ?? this.options.caseSensitive,\n fuzzy: true,\n },\n )\n\n if (matchedParams) {\n routeParams = matchedParams\n return true\n }\n\n return false\n })\n\n let routeCursor: AnyRoute =\n foundRoute || (this.routesById as any)['__root__']\n\n let matchedRoutes: AnyRoute[] = [routeCursor]\n\n let isGlobalNotFound = false\n\n // Check to see if the route needs a 404 entry\n if (\n // If we found a route, and it's not an index route and we have left over path\n foundRoute\n ? foundRoute.path !== '/' && routeParams['**']\n : // Or if we didn't find a route and we have left over path\n trimPathRight(pathname)\n ) {\n // If the user has defined an (old) 404 route, use it\n if (this.options.notFoundRoute) {\n matchedRoutes.push(this.options.notFoundRoute)\n } else {\n // If there is no routes found during path matching\n isGlobalNotFound = true\n }\n }\n\n while (routeCursor?.parentRoute) {\n routeCursor = routeCursor.parentRoute\n if (routeCursor) matchedRoutes.unshift(routeCursor)\n }\n\n // Existing matches are matches that are already loaded along with\n // pending matches that are still loading\n\n const parseErrors = matchedRoutes.map((route) => {\n let parsedParamsError\n\n if (route.options.parseParams) {\n try {\n const parsedParams = route.options.parseParams(routeParams)\n // Add the parsed params to the accumulated params bag\n Object.assign(routeParams, parsedParams)\n } catch (err: any) {\n parsedParamsError = new PathParamError(err.message, {\n cause: err,\n })\n\n if (opts?.throwOnError) {\n throw parsedParamsError\n }\n\n return parsedParamsError\n }\n }\n\n return\n })\n\n const matches: AnyRouteMatch[] = []\n\n matchedRoutes.forEach((route, index) => {\n // Take each matched route and resolve + validate its search params\n // This has to happen serially because each route's search params\n // can depend on the parent route's search params\n // It must also happen before we create the match so that we can\n // pass the search params to the route's potential key function\n // which is used to uniquely identify the route match in state\n\n const parentMatch = matches[index - 1]\n\n const [preMatchSearch, searchError]: [Record<string, any>, any] = (() => {\n // Validate the search params and stabilize them\n const parentSearch = parentMatch?.search ?? locationSearch\n\n try {\n const validator =\n typeof route.options.validateSearch === 'object'\n ? route.options.validateSearch.parse\n : route.options.validateSearch\n\n let search = validator?.(parentSearch) ?? {}\n\n return [\n {\n ...parentSearch,\n ...search,\n },\n undefined,\n ]\n } catch (err: any) {\n const searchError = new SearchParamError(err.message, {\n cause: err,\n })\n\n if (opts?.throwOnError) {\n throw searchError\n }\n\n return [parentSearch, searchError]\n }\n })()\n\n // This is where we need to call route.options.loaderDeps() to get any additional\n // deps that the route's loader function might need to run. We need to do this\n // before we create the match so that we can pass the deps to the route's\n // potential key function which is used to uniquely identify the route match in state\n\n const loaderDeps =\n route.options.loaderDeps?.({\n search: preMatchSearch,\n }) ?? ''\n\n const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : ''\n\n const interpolatedPath = interpolatePath({\n path: route.fullPath,\n params: routeParams,\n })\n const matchId =\n interpolatePath({\n path: route.id,\n params: routeParams,\n leaveWildcards: true,\n }) + loaderDepsHash\n\n // Waste not, want not. If we already have a match for this route,\n // reuse it. This is important for layout routes, which might stick\n // around between navigation actions that only change leaf routes.\n const existingMatch = getRouteMatch(this.state, matchId)\n\n const cause = this.state.matches.find((d) => d.id === matchId)\n ? 'stay'\n : 'enter'\n\n const match: AnyRouteMatch = existingMatch\n ? {\n ...existingMatch,\n cause,\n notFoundError:\n isGlobalNotFound && route.id === rootRouteId\n ? { global: true }\n : undefined,\n }\n : {\n id: matchId,\n routeId: route.id,\n params: routeParams,\n pathname: joinPaths([this.basepath, interpolatedPath]),\n updatedAt: Date.now(),\n search: {} as any,\n searchError: undefined,\n status: 'pending',\n showPending: false,\n isFetching: false,\n error: undefined,\n paramsError: parseErrors[index],\n loadPromise: Promise.resolve(),\n routeContext: undefined!,\n context: undefined!,\n abortController: new AbortController(),\n fetchCount: 0,\n cause,\n loaderDeps,\n invalid: false,\n preload: false,\n notFoundError:\n isGlobalNotFound && route.id === rootRouteId\n ? { global: true }\n : undefined,\n links: route.options.links?.(),\n scripts: route.options.scripts?.(),\n staticData: route.options.staticData || {},\n }\n\n // Regardless of whether we're reusing an existing match or creating\n // a new one, we need to update the match's search params\n match.search = replaceEqualDeep(match.search, preMatchSearch)\n // And also update the searchError if there is one\n match.searchError = searchError\n\n matches.push(match)\n })\n\n return matches as any\n }\n\n cancelMatch = (id: string) => {\n getRouteMatch(this.state, id)?.abortController?.abort()\n }\n\n cancelMatches = () => {\n this.state.pendingMatches?.forEach((match) => {\n this.cancelMatch(match.id)\n })\n }\n\n buildLocation: BuildLocationFn<TRouteTree> = (opts) => {\n const build = (\n dest: BuildNextOptions & {\n unmaskOnReload?: boolean\n } = {},\n matches?: AnyRouteMatch[],\n ): ParsedLocation => {\n const relevantMatches = this.state.pendingMatches || this.state.matches\n const fromSearch =\n relevantMatches[relevantMatches.length - 1]?.search ||\n this.latestLocation.search\n\n let pathname = this.resolvePathWithBase(\n dest.from ?? this.latestLocation.pathname,\n `${dest.to ?? ''}`,\n )\n\n const fromMatches = this.matchRoutes(\n this.latestLocation.pathname,\n fromSearch,\n )\n const stayingMatches = matches?.filter((d) =>\n fromMatches?.find((e) => e.routeId === d.routeId),\n )\n\n const prevParams = { ...last(fromMatches)?.params }\n\n let nextParams =\n (dest.params ?? true) === true\n ? prevParams\n : functionalUpdate(dest.params!, prevParams)\n\n if (nextParams) {\n matches\n ?.map((d) => this.looseRoutesById[d.routeId]!.options.stringifyParams)\n .filter(Boolean)\n .forEach((fn) => {\n nextParams = { ...nextParams!, ...fn!(nextParams!) }\n })\n }\n\n pathname = interpolatePath({\n path: pathname,\n params: nextParams ?? {},\n leaveWildcards: false,\n leaveParams: opts.leaveParams,\n })\n\n const preSearchFilters =\n stayingMatches\n ?.map(\n (match) =>\n this.looseRoutesById[match.routeId]!.options.preSearchFilters ??\n [],\n )\n .flat()\n .filter(Boolean) ?? []\n\n const postSearchFilters =\n stayingMatches\n ?.map(\n (match) =>\n this.looseRoutesById[match.routeId]!.options.postSearchFilters ??\n [],\n )\n .flat()\n .filter(Boolean) ?? []\n\n // Pre filters first\n const preFilteredSearch = preSearchFilters?.length\n ? preSearchFilters?.reduce(\n (prev, next) => next(prev) as any,\n fromSearch,\n )\n : fromSearch\n\n // Then the link/navigate function\n const destSearch =\n dest.search === true\n ? preFilteredSearch // Preserve resolvedFrom true\n : dest.search\n ? functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater\n : preSearchFilters?.length\n ? preFilteredSearch // Preserve resolvedFrom filters\n : {}\n\n // Then post filters\n const postFilteredSearch = postSearchFilters?.length\n ? postSearchFilters.reduce((prev, next) => next(prev), destSearch)\n : destSearch\n\n const search = replaceEqualDeep(fromSearch, postFilteredSearch)\n\n const searchStr = this.options.stringifySearch(search)\n\n const hash =\n dest.hash === true\n ? this.latestLocation.hash\n : dest.hash\n ? functionalUpdate(dest.hash!, this.latestLocation.hash)\n : undefined\n\n const hashStr = hash ? `#${hash}` : ''\n\n let nextState =\n dest.state === true\n ? this.latestLocation.state\n : dest.state\n ? functionalUpdate(dest.state, this.latestLocation.state)\n : {}\n\n nextState = replaceEqualDeep(this.latestLocation.state, nextState)\n\n return {\n pathname,\n search,\n searchStr,\n state: nextState as any,\n hash: hash ?? '',\n href: `${pathname}${searchStr}${hashStr}`,\n unmaskOnReload: dest.unmaskOnReload,\n }\n }\n\n const buildWithMatches = (\n dest: BuildNextOptions = {},\n maskedDest?: BuildNextOptions,\n ) => {\n let next = build(dest)\n let maskedNext = maskedDest ? build(maskedDest) : undefined\n\n if (!maskedNext) {\n let params = {}\n\n let foundMask = this.options.routeMasks?.find((d) => {\n const match = matchPathname(this.basepath, next.pathname, {\n to: d.from,\n caseSensitive: false,\n fuzzy: false,\n })\n\n if (match) {\n params = match\n return true\n }\n\n return false\n })\n\n if (foundMask) {\n maskedDest = {\n ...pick(opts, ['from']),\n ...foundMask,\n params,\n }\n maskedNext = build(maskedDest)\n }\n }\n\n const nextMatches = this.matchRoutes(next.pathname, next.search)\n const maskedMatches = maskedNext\n ? this.matchRoutes(maskedNext.pathname, maskedNext.search)\n : undefined\n const maskedFinal = maskedNext\n ? build(maskedDest, maskedMatches)\n : undefined\n\n const final = build(dest, nextMatches)\n\n if (maskedFinal) {\n final.maskedLocation = maskedFinal\n }\n\n return final\n }\n\n if (opts.mask) {\n return buildWithMatches(opts, {\n ...pick(opts, ['from']),\n ...opts.mask,\n })\n }\n\n return buildWithMatches(opts)\n }\n\n commitLocation = async ({\n startTransition,\n ...next\n }: ParsedLocation & CommitLocationOptions) => {\n if (this.navigateTimeout) clearTimeout(this.navigateTimeout)\n\n const isSameUrl = this.latestLocation.href === next.href\n\n // If the next urls are the same and we're not replacing,\n // do nothing\n if (!isSameUrl || !next.replace) {\n let { maskedLocation, ...nextHistory } = next\n\n if (maskedLocation) {\n nextHistory = {\n ...maskedLocation,\n state: {\n ...maskedLocation.state,\n __tempKey: undefined,\n __tempLocation: {\n ...nextHistory,\n search: nextHistory.searchStr,\n state: {\n ...nextHistory.state,\n __tempKey: undefined!,\n __tempLocation: undefined!,\n key: undefined!,\n },\n },\n },\n }\n\n if (\n nextHistory.unmaskOnReload ??\n this.options.unmaskOnReload ??\n false\n ) {\n nextHistory.state.__tempKey = this.tempLocationKey\n }\n }\n\n const apply = () => {\n this.history[next.replace ? 'replace' : 'push'](\n nextHistory.href,\n nextHistory.state,\n )\n }\n\n if (startTransition ?? true) {\n this.startReactTransition(apply)\n } else {\n apply()\n }\n }\n\n this.resetNextScroll = next.resetScroll ?? true\n\n return this.latestLoadPromise\n }\n\n buildAndCommitLocation = ({\n replace,\n resetScroll,\n startTransition,\n ...rest\n }: BuildNextOptions & CommitLocationOptions = {}) => {\n const location = this.buildLocation(rest as any)\n return this.commitLocation({\n ...location,\n startTransition,\n replace,\n resetScroll,\n })\n }\n\n navigate: NavigateFn<TRouteTree> = ({ from, to, ...rest }) => {\n // If this link simply reloads the current route,\n // make sure it has a new key so it will trigger a data refresh\n\n // If this `to` is a valid external URL, return\n // null for LinkUtils\n const toString = String(to)\n // const fromString = from !== undefined ? String(from) : from\n let isExternal\n\n try {\n new URL(`${toString}`)\n isExternal = true\n } catch (e) {}\n\n invariant(\n !isExternal,\n 'Attempting to navigate to external url with this.navigate!',\n )\n\n return this.buildAndCommitLocation({\n ...rest,\n from,\n to,\n // to: toString,\n })\n }\n\n loadMatches = async ({\n checkLatest,\n matches,\n preload,\n }: {\n checkLatest: () => Promise<void> | undefined\n matches: AnyRouteMatch[]\n preload?: boolean\n }): Promise<RouteMatch[]> => {\n let latestPromise\n let firstBadMatchIndex: number | undefined\n\n const updateMatch = (match: AnyRouteMatch) => {\n // const isPreload = this.state.cachedMatches.find((d) => d.id === match.id)\n const isPending = this.state.pendingMatches?.find(\n (d) => d.id === match.id,\n )\n\n const isMatched = this.state.matches.find((d) => d.id === match.id)\n\n const matchesKey = isPending\n ? 'pendingMatches'\n : isMatched\n ? 'matches'\n : 'cachedMatches'\n\n this.__store.setState((s) => ({\n ...s,\n [matchesKey]: s[matchesKey]?.map((d) =>\n d.id === match.id ? match : d,\n ),\n }))\n }\n\n // Check each match middleware to see if the route can be accessed\n try {\n for (let [index, match] of matches.entries()) {\n const parentMatch = matches[index - 1]\n const route = this.looseRoutesById[match.routeId]!\n const abortController = new AbortController()\n\n const handleErrorAndRedirect = (err: any, code: string) => {\n err.routerCode = code\n firstBadMatchIndex = firstBadMatchIndex ?? index\n\n if (isRedirect(err)) {\n throw err\n }\n\n if (isNotFound(err)) {\n this.updateMatchesWithNotFound(matches, match, err)\n }\n\n try {\n route.options.onError?.(err)\n } catch (errorHandlerErr) {\n err = errorHandlerErr\n\n if (isRedirect(errorHandlerErr)) {\n throw errorHandlerErr\n }\n }\n\n matches[index] = match = {\n ...match,\n error: err,\n status: 'error',\n updatedAt: Date.now(),\n abortController: new AbortController(),\n }\n }\n\n try {\n if (match.paramsError) {\n handleErrorAndRedirect(match.paramsError, 'PARSE_PARAMS')\n }\n\n if (match.searchError) {\n handleErrorAndRedirect(match.searchError, 'VALIDATE_SEARCH')\n }\n\n const parentContext =\n parentMatch?.context ?? this.options.context ?? {}\n\n const pendingMs =\n route.options.pendingMs ?? this.options.defaultPendingMs\n const pendingPromise =\n typeof pendingMs === 'number' && pendingMs <= 0\n ? Promise.resolve()\n : new Promise<void>((r) => setTimeout(r, pendingMs))\n\n const beforeLoadContext =\n (await route.options.beforeLoad?.({\n search: match.search,\n abortController,\n params: match.params,\n preload: !!preload,\n context: parentContext,\n location: this.state.location,\n // TOOD: just expose state and router, etc\n navigate: (opts) =>\n this.navigate({ ...opts, from: match.pathname } as any),\n buildLocation: this.buildLocation,\n cause: preload ? 'preload' : match.cause,\n })) ?? ({} as any)\n\n if (isRedirect(beforeLoadContext)) {\n throw beforeLoadContext\n }\n\n const context = {\n ...parentContext,\n ...beforeLoadContext,\n }\n\n matches[index] = match = {\n ...match,\n routeContext: replaceEqualDeep(\n match.routeContext,\n beforeLoadContext,\n ),\n context: replaceEqualDeep(match.context, context),\n abortController,\n pendingPromise,\n }\n } catch (err) {\n handleErrorAndRedirect(err, 'BEFORE_LOAD')\n break\n }\n }\n } catch (err) {\n if (isRedirect(err)) {\n if (!preload) this.navigate(err as any)\n return matches\n }\n\n throw err\n }\n\n const validResolvedMatches = matches.slice(0, firstBadMatchIndex)\n const matchPromises: Promise<any>[] = []\n\n validResolvedMatches.forEach((match, index) => {\n matchPromises.push(\n new Promise<void>(async (resolve) => {\n const parentMatchPromise = matchPromises[index - 1]\n const route = this.looseRoutesById[match.routeId]!\n\n const handleErrorAndRedirect = (err: any) => {\n if (isRedirect(err)) {\n if (!preload) {\n this.navigate(err as any)\n }\n return true\n }\n\n if (isNotFound(err)) {\n this.updateMatchesWithNotFound(matches, match, err)\n }\n\n return false\n }\n\n let loadPromise: Promise<void> | undefined\n\n matches[index] = match = {\n ...match,\n showPending: false,\n }\n\n let didShowPending = false\n const pendingMs =\n route.options.pendingMs ?? this.options.defaultPendingMs\n const pendingMinMs =\n route.options.pendingMinMs ?? this.options.defaultPendingMinMs\n const shouldPending =\n !preload &&\n typeof pendingMs === 'number' &&\n (route.options.pendingComponent ??\n this.options.defaultPendingComponent)\n\n const loaderContext: LoaderFnContext = {\n params: match.params,\n deps: match.loaderDeps,\n preload: !!preload,\n parentMatchPromise,\n abortController: match.abortController,\n context: match.context,\n location: this.state.location,\n navigate: (opts) =>\n this.navigate({ ...opts, from: match.pathname } as any),\n cause: preload ? 'preload' : match.cause,\n }\n\n const fetch = async () => {\n if (match.isFetching) {\n loadPromise = getRouteMatch(this.state, match.id)?.loadPromise\n } else {\n // If the user doesn't want the route to reload, just\n // resolve with the existing loader data\n\n if (match.fetchCount && match.status === 'success') {\n resolve()\n }\n\n // Otherwise, load the route\n matches[index] = match = {\n ...match,\n isFetching: true,\n fetchCount: match.fetchCount + 1,\n }\n\n const lazyPromise =\n route.lazyFn?.().then((lazyRoute) => {\n Object.assign(route.options, lazyRoute.options)\n }) || Promise.resolve()\n\n // If for some reason lazy resolves more lazy components...\n // We'll wait for that before pre attempt to preload any\n // components themselves.\n const componentsPromise = lazyPromise.then(() =>\n Promise.all(\n componentTypes.map(async (type) => {\n const component = route.options[type]\n\n if ((component as any)?.preload) {\n await (component as any).preload()\n }\n }),\n ),\n )\n\n // Kick off the loader!\n const loaderPromise = route.options.loader?.(loaderContext)\n\n loadPromise = Promise.all([\n componentsPromise,\n loaderPromise,\n lazyPromise,\n ]).then((d) => d[1])\n }\n\n matches[index] = match = {\n ...match,\n loadPromise,\n }\n\n updateMatch(match)\n\n try {\n const loaderData = await loadPromise\n if ((latestPromise = checkLatest())) return await latestPromise\n\n if (isRedirect(loaderData)) {\n if (handleErrorAndRedirect(loaderData)) return\n }\n\n if (didShowPending && pendingMinMs) {\n await new Promise((r) => setTimeout(r, pendingMinMs))\n }\n\n if ((latestPromise = checkLatest())) return await latestPromise\n\n const meta = route.options.meta?.({\n loaderData,\n })\n\n matches[index] = match = {\n ...match,\n error: undefined,\n status: 'success',\n isFetching: false,\n updatedAt: Date.now(),\n loaderData,\n loadPromise: undefined,\n meta,\n }\n } catch (error) {\n if ((latestPromise = checkLatest())) return await latestPromise\n if (handleErrorAndRedirect(error)) return\n\n try {\n route.options.onError?.(error)\n } catch (onErrorError) {\n error = onErrorError\n if (handleErrorAndRedirect(onErrorError)) return\n }\n\n matches[index] = match = {\n ...match,\n error,\n status: 'error',\n isFetching: false,\n }\n }\n\n updateMatch(match)\n }\n\n // This is where all of the stale-while-revalidate magic happens\n const age = Date.now() - match.updatedAt\n\n let staleAge = preload\n ? route.options.preloadStaleTime ??\n this.options.defaultPreloadStaleTime ??\n 30_000 // 30 seconds for preloads by default\n : route.options.staleTime ?? this.options.defaultStaleTime ?? 0\n\n // Default to reloading the route all the time\n let shouldReload\n\n const shouldReloadOption = route.options.shouldReload\n\n // Allow shouldReload to get the last say,\n // if provided.\n shouldReload =\n typeof shouldReloadOption === 'function'\n ? shouldReloadOption(loaderContext)\n : shouldReloadOption\n\n matches[index] = match = {\n ...match,\n preload:\n !!preload && !this.state.matches.find((d) => d.id === match.id),\n }\n\n if (match.status !== 'success') {\n // If we need to potentially show the pending component,\n // start a timer to show it after the pendingMs\n if (shouldPending) {\n match.pendingPromise?.then(async () => {\n if ((latestPromise = checkLatest())) return latestPromise\n\n didShowPending = true\n matches[index] = match = {\n ...match,\n showPending: true,\n }\n\n updateMatch(match)\n resolve()\n })\n }\n\n // Critical Fetching, we need to await\n await fetch()\n } else if (match.invalid || (shouldReload ?? age > staleAge)) {\n // Background Fetching, no need to wait\n fetch()\n }\n\n resolve()\n }),\n )\n })\n\n await Promise.all(matchPromises)\n return matches\n }\n\n invalidate = () => {\n const invalidate = (d: any) => ({\n ...d,\n invalid: true,\n })\n\n this.__store.setState((s) => ({\n ...s,\n matches: s.matches.map(invalidate),\n cachedMatches: s.cachedMatches.map(invalidate),\n pendingMatches: s.pendingMatches?.map(invalidate),\n }))\n\n this.load()\n }\n\n load = async (): Promise<void> => {\n const promise = new Promise<void>(async (resolve, reject) => {\n const next = this.latestLocation\n const prevLocation = this.state.resolvedLocation\n const pathDidChange = prevLocation!.href !== next.href\n let latestPromise: Promise<void> | undefined | null\n\n // Cancel any pending matches\n this.cancelMatches()\n\n this.emit({\n type: 'onBeforeLoad',\n fromLocation: prevLocation,\n toLocation: next,\n pathChanged: pathDidChange,\n })\n\n let pendingMatches!: RouteMatch<any, any>[]\n const previousMatches = this.state.matches\n\n this.__store.batch(() => {\n this.cleanCache()\n\n // Match the routes\n pendingMatches = this.matchRoutes(next.pathname, next.search, {\n debug: true,\n })\n\n // Ingest the new matches\n // If a cached moved to pendingMatches, remove it from cachedMatches\n this.__store.setState((s) => ({\n ...s,\n isLoading: true,\n location: next,\n pendingMatches,\n cachedMatches: s.cachedMatches.filter((d) => {\n return !pendingMatches.find((e) => e.id === d.id)\n }),\n }))\n })\n\n try {\n try {\n // Load the matches\n await this.loadMatches({\n matches: pendingMatches,\n checkLatest: () => this.checkLatest(promise),\n })\n } catch (err) {\n // swallow this error, since we'll display the\n // errors on the route components\n }\n\n // Only apply the latest transition\n if ((latestPromise = this.checkLatest(promise))) {\n return latestPromise\n }\n\n const exitingMatches = previousMatches.filter(\n (match) => !pendingMatches.find((d) => d.id === match.id),\n )\n const enteringMatches = pendingMatches.filter(\n (match) => !previousMatches.find((d) => d.id === match.id),\n )\n const stayingMatches = previousMatches.filter((match) =>\n pendingMatches.find((d) => d.id === match.id),\n )\n\n // Commit the pending matches. If a previous match was\n // removed, place it in the cachedMatches\n this.__store.batch(() => {\n this.__store.setState((s) => ({\n ...s,\n isLoading: false,\n matches: s.pendingMatches!,\n pendingMatches: undefined,\n cachedMatches: [\n ...s.cachedMatches,\n ...exitingMatches.filter((d) => d.status !== 'error'),\n ],\n }))\n this.cleanCache()\n })\n\n //\n ;(\n [\n [exitingMatches, 'onLeave'],\n [enteringMatches, 'onEnter'],\n [stayingMatches, 'onStay'],\n ] as const\n ).forEach(([matches, hook]) => {\n matches.forEach((match) => {\n this.looseRoutesById[match.routeId]!.options[hook]?.(match)\n })\n })\n\n this.emit({\n type: 'onLoad',\n fromLocation: prevLocation,\n toLocation: next,\n pathChanged: pathDidChange,\n })\n\n resolve()\n } catch (err) {\n // Only apply the latest transition\n if ((latestPromise = this.checkLatest(promise))) {\n return latestPromise\n }\n\n reject(err)\n }\n })\n\n this.latestLoadPromise = promise\n\n return this.latestLoadPromise\n }\n\n cleanCache = () => {\n // This is where all of the garbage collection magic happens\n this.__store.setState((s) => {\n return {\n ...s,\n cachedMatches: s.cachedMatches.filter((d) => {\n const route = this.looseRoutesById[d.routeId]!\n\n if (!route.options.loader) {\n return false\n }\n\n // If the route was preloaded, use the preloadGcTime\n // otherwise, use the gcTime\n const gcTime =\n (d.preload\n ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime\n : route.options.gcTime ?? this.options.defaultGcTime) ??\n 5 * 60 * 1000\n\n return d.status !== 'error' && Date.now() - d.updatedAt < gcTime\n }),\n }\n })\n }\n\n preloadRoute = async (\n navigateOpts: ToOptions<TRouteTree> = this.state.location as any,\n ) => {\n let next = this.buildLocation(navigateOpts as any)\n\n let matches = this.matchRoutes(next.pathname, next.search, {\n throwOnError: true,\n })\n\n const loadedMatchIds = Object.fromEntries(\n [\n ...this.state.matches,\n ...(this.state.pendingMatches ?? []),\n ...this.state.cachedMatches,\n ]?.map((d) => [d.id, true]),\n )\n\n this.__store.batch(() => {\n matches.forEach((match) => {\n if (!loadedMatchIds[match.id]) {\n this.__store.setState((s) => ({\n ...s,\n cachedMatches: [...(s.cachedMatches as any), match],\n }))\n }\n })\n })\n\n matches = await this.loadMatches({\n matches,\n preload: true,\n checkLatest: () => undefined,\n })\n\n return matches\n }\n\n matchRoute = <\n TFrom extends RoutePaths<TRouteTree> = '/',\n TTo extends string = '',\n TResolved = ResolveRelativePath<TFrom, NoInfer<TTo>>,\n >(\n location: ToOptions<TRouteTree, TFrom, TTo>,\n opts?: MatchRouteOptions,\n ): false | RouteById<TRouteTree, TResolved>['types']['allParams'] => {\n const matchLocation = {\n ...location,\n to: location.to\n ? this.resolvePathWithBase((location.from || '') as string, location.to)\n : undefined,\n params: location.params || {},\n leaveParams: true,\n }\n const next = this.buildLocation(matchLocation as any)\n\n if (opts?.pending && this.state.status !== 'pending') {\n return false\n }\n\n const baseLocation = opts?.pending\n ? this.latestLocation\n : this.state.resolvedLocation\n\n if (!baseLocation) {\n return false\n }\n const match = matchPathname(this.basepath, baseLocation.pathname, {\n ...opts,\n to: next.pathname,\n }) as any\n\n if (!match) {\n return false\n }\n if (location.params) {\n if (!deepEqual(match, location.params, true)) {\n return false\n }\n }\n\n if (match && (opts?.includeSearch ?? true)) {\n return deepEqual(baseLocation.search, next.search, true) ? match : false\n }\n\n return match\n }\n\n injectHtml = async (html: string | (() => Promise<string> | string)) => {\n this.injectedHtml.push(html)\n }\n\n dehydrateData = <T>(key: any, getData: T | (() => Promise<T> | T)) => {\n if (typeof document === 'undefined') {\n const strKey = typeof key === 'string' ? key : JSON.stringify(key)\n\n this.injectHtml(async () => {\n const id = `__TSR_DEHYDRATED__${strKey}`\n const data =\n typeof getData === 'function' ? await (getData as any)() : getData\n return `<script id='${id}' suppressHydrationWarning>window[\"__TSR_DEHYDRATED__${escapeJSON(\n strKey,\n )}\"] = ${JSON.stringify(this.options.transformer.stringify(data))}\n ;(() => {\n var el = document.getElementById('${id}')\n el.parentElement.removeChild(el)\n })()\n </script>`\n })\n\n return () => this.hydrateData<T>(key)\n }\n\n return () => undefined\n }\n\n hydrateData = <T extends any = unknown>(key: any) => {\n if (typeof document !== 'undefined') {\n const strKey = typeof key === 'string' ? key : JSON.stringify(key)\n\n return this.options.transformer.parse(\n window[`__TSR_DEHYDRATED__${strKey}` as any] as unknown as string,\n ) as T\n }\n\n return undefined\n }\n\n dehydrate = (): DehydratedRouter => {\n const pickError =\n this.options.errorSerializer?.serialize ?? defaultSerializeError\n\n return {\n state: {\n dehydratedMatches: this.state.matches.map((d) => ({\n ...pick(d, [\n 'id',\n 'status',\n 'updatedAt',\n 'loaderData',\n // Not-founds that occur during SSR don't require the client to load data before\n // triggering in order to prevent the flicker of the loading component\n 'notFoundError',\n ]),\n // If an error occurs server-side during SSRing,\n // send a small subset of the error to the client\n error: d.error\n ? {\n data: pickError(d.error),\n __isServerError: true,\n }\n : undefined,\n })),\n },\n }\n }\n\n hydrate = async (__do_not_use_server_ctx?: string) => {\n let _ctx = __do_not_use_server_ctx\n // Client hydrates from window\n if (typeof document !== 'undefined') {\n _ctx = window.__TSR_DEHYDRATED__?.data\n }\n\n invariant(\n _ctx,\n 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?',\n )\n\n const ctx = this.options.transformer.parse(_ctx) as HydrationCtx\n this.dehydratedData = ctx.payload as any\n this.options.hydrate?.(ctx.payload as any)\n const dehydratedState = ctx.router.state\n\n let matches = this.matchRoutes(\n this.state.location.pathname,\n this.state.location.search,\n ).map((match) => {\n const dehydratedMatch = dehydratedState.dehydratedMatches.find(\n (d) => d.id === match.id,\n )\n\n invariant(\n dehydratedMatch,\n `Could not find a client-side match for dehydrated match with id: ${match.id}!`,\n )\n\n if (dehydratedMatch) {\n const route = this.looseRoutesById[match.routeId]!\n\n return {\n ...match,\n ...dehydratedMatch,\n meta: route.options.meta?.({\n loaderData: dehydratedMatch.loaderData,\n }),\n links: route.options.links?.(),\n scripts: route.options.scripts?.(),\n }\n }\n return match\n })\n\n this.__store.setState((s) => {\n return {\n ...s,\n matches: matches as any,\n lastUpdated: Date.now(),\n }\n })\n }\n\n // Finds a match that has a notFoundComponent\n updateMatchesWithNotFound = (\n matches: AnyRouteMatch[],\n currentMatch: AnyRouteMatch,\n err: NotFoundError,\n ) => {\n const matchesByRouteId = Object.fromEntries(\n matches.map((match) => [match.routeId, match]),\n ) as Record<string, AnyRouteMatch>\n\n if (err.global) {\n matchesByRouteId[rootRouteId]!.notFoundError = err\n } else {\n // If the err contains a routeId, start searching up from that route\n let currentRoute = (this.routesById as any)[\n err.route ?? currentMatch.routeId\n ] as AnyRoute\n\n // Go up the tree until we find a route with a notFoundComponent\n while (!currentRoute.options.notFoundComponent) {\n currentRoute = currentRoute?.parentRoute\n\n invariant(\n currentRoute,\n 'Found invalid route tree while trying to find not-found handler.',\n )\n\n if (currentRoute.id === rootRouteId) break\n }\n\n const match = matchesByRouteId[currentRoute.id]\n invariant(match, 'Could not find match for route: ' + currentRoute.id)\n match.notFoundError = err\n }\n }\n\n hasNotFoundMatch = () => {\n return this.__store.state.matches.some((d) => d.notFoundError)\n }\n\n // resolveMatchPromise = (matchId: string, key: string, value: any) => {\n // state.matches\n // .find((d) => d.id === matchId)\n // ?.__promisesByKey[key]?.resolve(value)\n // }\n}\n\n// A function that takes an import() argument which is a function and returns a new function that will\n// proxy arguments from the caller to the imported function, retaining all type\n// information along the way\nexport function lazyFn<\n T extends Record<string, (...args: any[]) => any>,\n TKey extends keyof T = 'default',\n>(fn: () => Promise<T>, key?: TKey) {\n return async (\n ...args: Parameters<T[TKey]>\n ): Promise<Awaited<ReturnType<T[TKey]>>> => {\n const imported = await fn()\n return imported[key || 'default'](...args)\n }\n}\n\nexport class SearchParamError extends Error {}\n\nexport class PathParamError extends Error {}\n\nexport function getInitialRouterState(\n location: ParsedLocation,\n): RouterState<any> {\n return {\n isLoading: false,\n isTransitioning: false,\n status: 'idle',\n resolvedLocation: { ...location },\n location,\n matches: [],\n pendingMatches: [],\n cachedMatches: [],\n lastUpdated: 0,\n }\n}\n\nexport function defaultSerializeError(err: unknown) {\n if (err instanceof Error)\n return {\n name: err.name,\n message: err.message,\n }\n\n return {\n data: err,\n }\n}\n"],"names":["d","searchError","_a","_b","_c"],"mappings":";;;;;;;;;;AA8MO,MAAM,iBAAiB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA8BO,SAAS,aAKd,SACA;AACO,SAAA,IAAI,OAAkD,OAAO;AACtE;AAEO,MAAM,OAIX;AAAA;AAAA;AAAA;AAAA,EAkCA,YACE,SAKA;AAtCF,SAAA,kBAAsC,GAAG,KAAK;AAAA,MAC5C,KAAK,WAAW;AAAA,IACjB,CAAA;AAC0B,SAAA,kBAAA;AACO,SAAA,kBAAA;AAClC,SAAA,oBAAmC,QAAQ;AAC3C,SAAA,kCAAkB;AAClB,SAAA,eAAoC;AA+Ca,SAAA,uBAAA,CAAC,OAAO,GAAG;AAE5D,SAAA,SAAS,CACP,eAKG;AACH,UAAI,WAAW,eAAe;AACpB,gBAAA;AAAA,UACN;AAAA,QAAA;AAAA,MAEJ;AAEA,YAAM,kBAAkB,KAAK;AAC7B,WAAK,UAAU;AAAA,QACb,GAAG,KAAK;AAAA,QACR,GAAG;AAAA,MAAA;AAIH,UAAA,CAAC,KAAK,YACL,WAAW,YAAY,WAAW,aAAa,gBAAgB,UAChE;AAEE,YAAA,WAAW,aAAa,UACxB,WAAW,aAAa,MACxB,WAAW,aAAa,KACxB;AACA,eAAK,WAAW;AAAA,QAAA,OACX;AACL,eAAK,WAAW,IAAI,SAAS,WAAW,QAAQ,CAAC;AAAA,QACnD;AAAA,MACF;AAGE,UAAA,CAAC,KAAK,WACL,KAAK,QAAQ,WAAW,KAAK,QAAQ,YAAY,KAAK,SACvD;AACK,aAAA,UACH,KAAK,QAAQ,YACZ,OAAO,aAAa,cACjB,qBAAqB,IACrB,oBAAoB;AAAA,UAClB,gBAAgB,CAAC,KAAK,QAAQ,YAAY,GAAG;AAAA,QAC9C,CAAA;AACF,aAAA,iBAAiB,KAAK;MAC7B;AAEA,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AsB,KAAY;AAClC,SAAO,UACF,SACuC;AACpC,UAAA,WAAW,MAAM;AACvB,WAAO,SAAS,OAAO,SAAS,EAAE,GAAG,IAAI;AAAA,EAAA;AAE7C;AAEO,MAAM,yBAAyB,MAAM;AAAC;AAEtC,MAAM,uBAAuB,MAAM;AAAC;AAEpC,SAAS,sBACd,UACkB;AACX,SAAA;AAAA,IACL,WAAW;AAAA,IACX,iBAAiB;AAAA,IACjB,QAAQ;AAAA,IACR,kBAAkB,EAAE,GAAG,SAAS;AAAA,IAChC;AAAA,IACA,SAAS,CAAC;AAAA,IACV,gBAAgB,CAAC;AAAA,IACjB,eAAe,CAAC;AAAA,IAChB,aAAa;AAAA,EAAA;AAEjB;AAEO,SAAS,sBAAsB,KAAc;AAClD,MAAI,eAAe;AACV,WAAA;AAAA,MACL,MAAM,IAAI;AAAA,MACV,SAAS,IAAI;AAAA,IAAA;AAGV,SAAA;AAAA,IACL,MAAM;AAAA,EAAA;AAEV;"}
1
+ {"version":3,"file":"router.js","sources":["../../src/router.ts"],"sourcesContent":["import {\n HistoryLocation,\n HistoryState,\n RouterHistory,\n createBrowserHistory,\n createMemoryHistory,\n} from '@tanstack/history'\nimport { Store } from '@tanstack/react-store'\n\n//\n\nimport {\n AnySearchSchema,\n AnyRoute,\n AnyContext,\n AnyPathParams,\n RouteMask,\n Route,\n LoaderFnContext,\n rootRouteId,\n} from './route'\nimport {\n FullSearchSchema,\n RouteById,\n RoutePaths,\n RoutesById,\n RoutesByPath,\n} from './routeInfo'\nimport { defaultParseSearch, defaultStringifySearch } from './searchParams'\nimport {\n PickAsRequired,\n Updater,\n NonNullableUpdater,\n replaceEqualDeep,\n deepEqual,\n escapeJSON,\n functionalUpdate,\n last,\n pick,\n Timeout,\n} from './utils'\nimport { RouteComponent } from './route'\nimport { AnyRouteMatch, MatchRouteOptions, RouteMatch } from './Matches'\nimport { ParsedLocation } from './location'\nimport { SearchSerializer, SearchParser } from './searchParams'\nimport {\n BuildLocationFn,\n CommitLocationOptions,\n InjectedHtmlEntry,\n NavigateFn,\n getRouteMatch,\n} from './RouterProvider'\n\nimport {\n cleanPath,\n interpolatePath,\n joinPaths,\n matchPathname,\n parsePathname,\n resolvePath,\n trimPath,\n trimPathLeft,\n trimPathRight,\n} from './path'\nimport invariant from 'tiny-invariant'\nimport { isRedirect } from './redirects'\nimport { NotFoundError, isNotFound } from './not-found'\nimport { ResolveRelativePath, ToOptions } from './link'\nimport { NoInfer } from '@tanstack/react-store'\n// import warning from 'tiny-warning'\n\n//\n\ndeclare global {\n interface Window {\n __TSR_DEHYDRATED__?: { data: string }\n __TSR_ROUTER_CONTEXT__?: React.Context<Router<any>>\n }\n}\n\nexport interface Register {\n // router: Router\n}\n\nexport type AnyRouter = Router<AnyRoute, any>\n\nexport type RegisteredRouter = Register extends {\n router: infer TRouter extends AnyRouter\n}\n ? TRouter\n : AnyRouter\n\nexport type HydrationCtx = {\n router: DehydratedRouter\n payload: Record<string, any>\n}\n\nexport type RouterContextOptions<TRouteTree extends AnyRoute> =\n AnyContext extends TRouteTree['types']['routerContext']\n ? {\n context?: TRouteTree['types']['routerContext']\n }\n : {\n context: TRouteTree['types']['routerContext']\n }\n\nexport interface RouterOptions<\n TRouteTree extends AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n> {\n history?: RouterHistory\n stringifySearch?: SearchSerializer\n parseSearch?: SearchParser\n defaultPreload?: false | 'intent'\n defaultPreloadDelay?: number\n defaultComponent?: RouteComponent\n defaultErrorComponent?: RouteComponent\n defaultPendingComponent?: RouteComponent\n defaultPendingMs?: number\n defaultPendingMinMs?: number\n defaultStaleTime?: number\n defaultPreloadStaleTime?: number\n defaultPreloadGcTime?: number\n defaultGcTime?: number\n caseSensitive?: boolean\n routeTree?: TRouteTree\n basepath?: string\n context?: TRouteTree['types']['routerContext']\n dehydrate?: () => TDehydrated\n hydrate?: (dehydrated: TDehydrated) => void\n routeMasks?: RouteMask<TRouteTree>[]\n unmaskOnReload?: boolean\n Wrap?: (props: { children: any }) => JSX.Element\n InnerWrap?: (props: { children: any }) => JSX.Element\n /**\n * @deprecated\n * Use `notFoundComponent` instead.\n * See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.\n */\n notFoundRoute?: AnyRoute\n transformer?: RouterTransformer\n errorSerializer?: RouterErrorSerializer<TSerializedError>\n globalNotFound?: RouteComponent\n}\n\nexport interface RouterTransformer {\n stringify: (obj: unknown) => string\n parse: (str: string) => unknown\n}\nexport interface RouterErrorSerializer<TSerializedError> {\n serialize: (err: unknown) => TSerializedError\n deserialize: (err: TSerializedError) => unknown\n}\n\nexport interface RouterState<TRouteTree extends AnyRoute = AnyRoute> {\n status: 'pending' | 'idle'\n isLoading: boolean\n isTransitioning: boolean\n matches: RouteMatch<TRouteTree>[]\n pendingMatches?: RouteMatch<TRouteTree>[]\n cachedMatches: RouteMatch<TRouteTree>[]\n location: ParsedLocation<FullSearchSchema<TRouteTree>>\n resolvedLocation: ParsedLocation<FullSearchSchema<TRouteTree>>\n lastUpdated: number\n}\n\nexport type ListenerFn<TEvent extends RouterEvent> = (event: TEvent) => void\n\nexport interface BuildNextOptions {\n to?: string | number | null\n params?: true | Updater<unknown>\n search?: true | Updater<unknown>\n hash?: true | Updater<string>\n state?: true | NonNullableUpdater<HistoryState>\n mask?: {\n to?: string | number | null\n params?: true | Updater<unknown>\n search?: true | Updater<unknown>\n hash?: true | Updater<string>\n state?: true | NonNullableUpdater<HistoryState>\n unmaskOnReload?: boolean\n }\n from?: string\n}\n\nexport interface DehydratedRouterState {\n dehydratedMatches: DehydratedRouteMatch[]\n}\n\nexport type DehydratedRouteMatch = Pick<\n RouteMatch,\n 'id' | 'status' | 'updatedAt' | 'notFoundError' | 'loaderData'\n>\n\nexport interface DehydratedRouter {\n state: DehydratedRouterState\n}\n\nexport type RouterConstructorOptions<\n TRouteTree extends AnyRoute,\n TDehydrated extends Record<string, any>,\n TSerializedError extends Record<string, any>,\n> = Omit<RouterOptions<TRouteTree, TDehydrated, TSerializedError>, 'context'> &\n RouterContextOptions<TRouteTree>\n\nexport const componentTypes = [\n 'component',\n 'errorComponent',\n 'pendingComponent',\n 'notFoundComponent',\n] as const\n\nexport type RouterEvents = {\n onBeforeLoad: {\n type: 'onBeforeLoad'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n onLoad: {\n type: 'onLoad'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n onResolved: {\n type: 'onResolved'\n fromLocation: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n }\n}\n\nexport type RouterEvent = RouterEvents[keyof RouterEvents]\n\nexport type RouterListener<TRouterEvent extends RouterEvent> = {\n eventType: TRouterEvent['type']\n fn: ListenerFn<TRouterEvent>\n}\n\nexport function createRouter<\n TRouteTree extends AnyRoute = AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n>(\n options: RouterConstructorOptions<TRouteTree, TDehydrated, TSerializedError>,\n) {\n return new Router<TRouteTree, TDehydrated, TSerializedError>(options)\n}\n\nexport class Router<\n TRouteTree extends AnyRoute = AnyRoute,\n TDehydrated extends Record<string, any> = Record<string, any>,\n TSerializedError extends Record<string, any> = Record<string, any>,\n> {\n // Option-independent properties\n tempLocationKey: string | undefined = `${Math.round(\n Math.random() * 10000000,\n )}`\n resetNextScroll: boolean = true\n navigateTimeout: Timeout | null = null\n latestLoadPromise: Promise<void> = Promise.resolve()\n subscribers = new Set<RouterListener<RouterEvent>>()\n injectedHtml: InjectedHtmlEntry[] = []\n dehydratedData?: TDehydrated\n\n // Must build in constructor\n __store!: Store<RouterState<TRouteTree>>\n options!: PickAsRequired<\n Omit<\n RouterOptions<TRouteTree, TDehydrated, TSerializedError>,\n 'transformer'\n > & {\n transformer: RouterTransformer\n },\n 'stringifySearch' | 'parseSearch' | 'context'\n >\n history!: RouterHistory\n latestLocation!: ParsedLocation\n basepath!: string\n routeTree!: TRouteTree\n routesById!: RoutesById<TRouteTree>\n routesByPath!: RoutesByPath<TRouteTree>\n flatRoutes!: AnyRoute[]\n\n /**\n * @deprecated Use the `createRouter` function instead\n */\n constructor(\n options: RouterConstructorOptions<\n TRouteTree,\n TDehydrated,\n TSerializedError\n >,\n ) {\n this.update({\n defaultPreloadDelay: 50,\n defaultPendingMs: 1000,\n defaultPendingMinMs: 500,\n context: undefined!,\n ...options,\n stringifySearch: options?.stringifySearch ?? defaultStringifySearch,\n parseSearch: options?.parseSearch ?? defaultParseSearch,\n transformer: options?.transformer ?? JSON,\n })\n }\n\n // These are default implementations that can optionally be overridden\n // by the router provider once rendered. We provide these so that the\n // router can be used in a non-react environment if necessary\n startReactTransition: (fn: () => void) => void = (fn) => fn()\n\n update = (\n newOptions: RouterConstructorOptions<\n TRouteTree,\n TDehydrated,\n TSerializedError\n >,\n ) => {\n if (newOptions.notFoundRoute) {\n console.warn(\n 'The notFoundRoute API is deprecated and will be removed in the next major version. See https://tanstack.com/router/v1/docs/guide/not-found-errors#migrating-from-notfoundroute for more info.',\n )\n }\n\n const previousOptions = this.options\n this.options = {\n ...this.options,\n ...newOptions,\n }\n\n if (\n !this.basepath ||\n (newOptions.basepath && newOptions.basepath !== previousOptions.basepath)\n ) {\n if (\n newOptions.basepath === undefined ||\n newOptions.basepath === '' ||\n newOptions.basepath === '/'\n ) {\n this.basepath = '/'\n } else {\n this.basepath = `/${trimPath(newOptions.basepath)}`\n }\n }\n\n if (\n !this.history ||\n (this.options.history && this.options.history !== this.history)\n ) {\n this.history =\n this.options.history ??\n (typeof document !== 'undefined'\n ? createBrowserHistory()\n : createMemoryHistory({\n initialEntries: [this.options.basepath || '/'],\n }))\n this.latestLocation = this.parseLocation()\n }\n\n if (this.options.routeTree !== this.routeTree) {\n this.routeTree = this.options.routeTree as TRouteTree\n this.buildRouteTree()\n }\n\n if (!this.__store) {\n this.__store = new Store(getInitialRouterState(this.latestLocation), {\n onUpdate: () => {\n this.__store.state = {\n ...this.state,\n status:\n this.state.isTransitioning || this.state.isLoading\n ? 'pending'\n : 'idle',\n }\n },\n })\n }\n }\n\n get state() {\n return this.__store.state\n }\n\n buildRouteTree = () => {\n this.routesById = {} as RoutesById<TRouteTree>\n this.routesByPath = {} as RoutesByPath<TRouteTree>\n\n const notFoundRoute = this.options.notFoundRoute\n if (notFoundRoute) {\n notFoundRoute.init({ originalIndex: 99999999999 })\n ;(this.routesById as any)[notFoundRoute.id] = notFoundRoute\n }\n\n const recurseRoutes = (childRoutes: AnyRoute[]) => {\n childRoutes.forEach((childRoute, i) => {\n childRoute.init({ originalIndex: i })\n\n const existingRoute = (this.routesById as any)[childRoute.id]\n\n invariant(\n !existingRoute,\n `Duplicate routes found with id: ${String(childRoute.id)}`,\n )\n ;(this.routesById as any)[childRoute.id] = childRoute\n\n if (!childRoute.isRoot && childRoute.path) {\n const trimmedFullPath = trimPathRight(childRoute.fullPath)\n if (\n !(this.routesByPath as any)[trimmedFullPath] ||\n childRoute.fullPath.endsWith('/')\n ) {\n ;(this.routesByPath as any)[trimmedFullPath] = childRoute\n }\n }\n\n const children = childRoute.children as Route[]\n\n if (children?.length) {\n recurseRoutes(children)\n }\n })\n }\n\n recurseRoutes([this.routeTree])\n\n const scoredRoutes: {\n child: AnyRoute\n trimmed: string\n parsed: ReturnType<typeof parsePathname>\n index: number\n scores: number[]\n }[] = []\n\n ;(Object.values(this.routesById) as AnyRoute[]).forEach((d, i) => {\n if (d.isRoot || !d.path) {\n return\n }\n\n const trimmed = trimPathLeft(d.fullPath)\n const parsed = parsePathname(trimmed)\n\n while (parsed.length > 1 && parsed[0]?.value === '/') {\n parsed.shift()\n }\n\n const scores = parsed.map((d) => {\n if (d.value === '/') {\n return 0.75\n }\n\n if (d.type === 'param') {\n return 0.5\n }\n\n if (d.type === 'wildcard') {\n return 0.25\n }\n\n return 1\n })\n\n scoredRoutes.push({ child: d, trimmed, parsed, index: i, scores })\n })\n\n this.flatRoutes = scoredRoutes\n .sort((a, b) => {\n const minLength = Math.min(a.scores.length, b.scores.length)\n\n // Sort by min available score\n for (let i = 0; i < minLength; i++) {\n if (a.scores[i] !== b.scores[i]) {\n return b.scores[i]! - a.scores[i]!\n }\n }\n\n // Sort by length of score\n if (a.scores.length !== b.scores.length) {\n return b.scores.length - a.scores.length\n }\n\n // Sort by min available parsed value\n for (let i = 0; i < minLength; i++) {\n if (a.parsed[i]!.value !== b.parsed[i]!.value) {\n return a.parsed[i]!.value! > b.parsed[i]!.value! ? 1 : -1\n }\n }\n\n // Sort by original index\n return a.index - b.index\n })\n .map((d, i) => {\n d.child.rank = i\n return d.child\n })\n }\n\n subscribe = <TType extends keyof RouterEvents>(\n eventType: TType,\n fn: ListenerFn<RouterEvents[TType]>,\n ) => {\n const listener: RouterListener<any> = {\n eventType,\n fn,\n }\n\n this.subscribers.add(listener)\n\n return () => {\n this.subscribers.delete(listener)\n }\n }\n\n emit = (routerEvent: RouterEvent) => {\n this.subscribers.forEach((listener) => {\n if (listener.eventType === routerEvent.type) {\n listener.fn(routerEvent)\n }\n })\n }\n\n checkLatest = (promise: Promise<void>): undefined | Promise<void> => {\n return this.latestLoadPromise !== promise\n ? this.latestLoadPromise\n : undefined\n }\n\n parseLocation = (\n previousLocation?: ParsedLocation,\n ): ParsedLocation<FullSearchSchema<TRouteTree>> => {\n const parse = ({\n pathname,\n search,\n hash,\n state,\n }: HistoryLocation): ParsedLocation<FullSearchSchema<TRouteTree>> => {\n const parsedSearch = this.options.parseSearch(search)\n const searchStr = this.options.stringifySearch(parsedSearch)\n\n return {\n pathname: pathname,\n searchStr,\n search: replaceEqualDeep(previousLocation?.search, parsedSearch) as any,\n hash: hash.split('#').reverse()[0] ?? '',\n href: `${pathname}${searchStr}${hash}`,\n state: replaceEqualDeep(previousLocation?.state, state) as HistoryState,\n }\n }\n\n const location = parse(this.history.location)\n\n let { __tempLocation, __tempKey } = location.state\n\n if (__tempLocation && (!__tempKey || __tempKey === this.tempLocationKey)) {\n // Sync up the location keys\n const parsedTempLocation = parse(__tempLocation) as any\n parsedTempLocation.state.key = location.state.key\n\n delete parsedTempLocation.state.__tempLocation\n\n return {\n ...parsedTempLocation,\n maskedLocation: location,\n }\n }\n\n return location\n }\n\n resolvePathWithBase = (from: string, path: string) => {\n return resolvePath(this.basepath!, from, cleanPath(path))\n }\n\n get looseRoutesById() {\n return this.routesById as Record<string, AnyRoute>\n }\n\n matchRoutes = <TRouteTree extends AnyRoute>(\n pathname: string,\n locationSearch: AnySearchSchema,\n opts?: { throwOnError?: boolean; debug?: boolean },\n ): RouteMatch<TRouteTree>[] => {\n let routeParams: Record<string, string> = {}\n\n let foundRoute = this.flatRoutes.find((route) => {\n const matchedParams = matchPathname(\n this.basepath,\n trimPathRight(pathname),\n {\n to: route.fullPath,\n caseSensitive:\n route.options.caseSensitive ?? this.options.caseSensitive,\n fuzzy: true,\n },\n )\n\n if (matchedParams) {\n routeParams = matchedParams\n return true\n }\n\n return false\n })\n\n let routeCursor: AnyRoute =\n foundRoute || (this.routesById as any)['__root__']\n\n let matchedRoutes: AnyRoute[] = [routeCursor]\n\n let isGlobalNotFound = false\n\n // Check to see if the route needs a 404 entry\n if (\n // If we found a route, and it's not an index route and we have left over path\n foundRoute\n ? foundRoute.path !== '/' && routeParams['**']\n : // Or if we didn't find a route and we have left over path\n trimPathRight(pathname)\n ) {\n // If the user has defined an (old) 404 route, use it\n if (this.options.notFoundRoute) {\n matchedRoutes.push(this.options.notFoundRoute)\n } else {\n // If there is no routes found during path matching\n isGlobalNotFound = true\n }\n }\n\n while (routeCursor?.parentRoute) {\n routeCursor = routeCursor.parentRoute\n if (routeCursor) matchedRoutes.unshift(routeCursor)\n }\n\n // Existing matches are matches that are already loaded along with\n // pending matches that are still loading\n\n const parseErrors = matchedRoutes.map((route) => {\n let parsedParamsError\n\n if (route.options.parseParams) {\n try {\n const parsedParams = route.options.parseParams(routeParams)\n // Add the parsed params to the accumulated params bag\n Object.assign(routeParams, parsedParams)\n } catch (err: any) {\n parsedParamsError = new PathParamError(err.message, {\n cause: err,\n })\n\n if (opts?.throwOnError) {\n throw parsedParamsError\n }\n\n return parsedParamsError\n }\n }\n\n return\n })\n\n const matches: AnyRouteMatch[] = []\n\n matchedRoutes.forEach((route, index) => {\n // Take each matched route and resolve + validate its search params\n // This has to happen serially because each route's search params\n // can depend on the parent route's search params\n // It must also happen before we create the match so that we can\n // pass the search params to the route's potential key function\n // which is used to uniquely identify the route match in state\n\n const parentMatch = matches[index - 1]\n\n const [preMatchSearch, searchError]: [Record<string, any>, any] = (() => {\n // Validate the search params and stabilize them\n const parentSearch = parentMatch?.search ?? locationSearch\n\n try {\n const validator =\n typeof route.options.validateSearch === 'object'\n ? route.options.validateSearch.parse\n : route.options.validateSearch\n\n let search = validator?.(parentSearch) ?? {}\n\n return [\n {\n ...parentSearch,\n ...search,\n },\n undefined,\n ]\n } catch (err: any) {\n const searchError = new SearchParamError(err.message, {\n cause: err,\n })\n\n if (opts?.throwOnError) {\n throw searchError\n }\n\n return [parentSearch, searchError]\n }\n })()\n\n // This is where we need to call route.options.loaderDeps() to get any additional\n // deps that the route's loader function might need to run. We need to do this\n // before we create the match so that we can pass the deps to the route's\n // potential key function which is used to uniquely identify the route match in state\n\n const loaderDeps =\n route.options.loaderDeps?.({\n search: preMatchSearch,\n }) ?? ''\n\n const loaderDepsHash = loaderDeps ? JSON.stringify(loaderDeps) : ''\n\n const interpolatedPath = interpolatePath({\n path: route.fullPath,\n params: routeParams,\n })\n const matchId =\n interpolatePath({\n path: route.id,\n params: routeParams,\n leaveWildcards: true,\n }) + loaderDepsHash\n\n // Waste not, want not. If we already have a match for this route,\n // reuse it. This is important for layout routes, which might stick\n // around between navigation actions that only change leaf routes.\n const existingMatch = getRouteMatch(this.state, matchId)\n\n const cause = this.state.matches.find((d) => d.id === matchId)\n ? 'stay'\n : 'enter'\n\n const match: AnyRouteMatch = existingMatch\n ? {\n ...existingMatch,\n cause,\n notFoundError:\n isGlobalNotFound && route.id === rootRouteId\n ? { global: true }\n : undefined,\n }\n : {\n id: matchId,\n routeId: route.id,\n params: routeParams,\n pathname: joinPaths([this.basepath, interpolatedPath]),\n updatedAt: Date.now(),\n search: {} as any,\n searchError: undefined,\n status: 'pending',\n showPending: false,\n isFetching: false,\n error: undefined,\n paramsError: parseErrors[index],\n loadPromise: Promise.resolve(),\n routeContext: undefined!,\n context: undefined!,\n abortController: new AbortController(),\n fetchCount: 0,\n cause,\n loaderDeps,\n invalid: false,\n preload: false,\n notFoundError:\n isGlobalNotFound && route.id === rootRouteId\n ? { global: true }\n : undefined,\n links: route.options.links?.(),\n scripts: route.options.scripts?.(),\n staticData: route.options.staticData || {},\n }\n\n // Regardless of whether we're reusing an existing match or creating\n // a new one, we need to update the match's search params\n match.search = replaceEqualDeep(match.search, preMatchSearch)\n // And also update the searchError if there is one\n match.searchError = searchError\n\n matches.push(match)\n })\n\n return matches as any\n }\n\n cancelMatch = (id: string) => {\n getRouteMatch(this.state, id)?.abortController?.abort()\n }\n\n cancelMatches = () => {\n this.state.pendingMatches?.forEach((match) => {\n this.cancelMatch(match.id)\n })\n }\n\n buildLocation: BuildLocationFn<TRouteTree> = (opts) => {\n const build = (\n dest: BuildNextOptions & {\n unmaskOnReload?: boolean\n } = {},\n matches?: AnyRouteMatch[],\n ): ParsedLocation => {\n const relevantMatches = this.state.pendingMatches || this.state.matches\n const fromSearch =\n relevantMatches[relevantMatches.length - 1]?.search ||\n this.latestLocation.search\n\n let pathname = this.resolvePathWithBase(\n dest.from ?? this.latestLocation.pathname,\n `${dest.to ?? ''}`,\n )\n\n const fromMatches = this.matchRoutes(\n this.latestLocation.pathname,\n fromSearch,\n )\n const stayingMatches = matches?.filter((d) =>\n fromMatches?.find((e) => e.routeId === d.routeId),\n )\n\n const prevParams = { ...last(fromMatches)?.params }\n\n let nextParams =\n (dest.params ?? true) === true\n ? prevParams\n : functionalUpdate(dest.params!, prevParams)\n\n if (nextParams) {\n matches\n ?.map((d) => this.looseRoutesById[d.routeId]!.options.stringifyParams)\n .filter(Boolean)\n .forEach((fn) => {\n nextParams = { ...nextParams!, ...fn!(nextParams!) }\n })\n }\n\n pathname = interpolatePath({\n path: pathname,\n params: nextParams ?? {},\n leaveWildcards: false,\n leaveParams: opts.leaveParams,\n })\n\n const preSearchFilters =\n stayingMatches\n ?.map(\n (match) =>\n this.looseRoutesById[match.routeId]!.options.preSearchFilters ??\n [],\n )\n .flat()\n .filter(Boolean) ?? []\n\n const postSearchFilters =\n stayingMatches\n ?.map(\n (match) =>\n this.looseRoutesById[match.routeId]!.options.postSearchFilters ??\n [],\n )\n .flat()\n .filter(Boolean) ?? []\n\n // Pre filters first\n const preFilteredSearch = preSearchFilters?.length\n ? preSearchFilters?.reduce(\n (prev, next) => next(prev) as any,\n fromSearch,\n )\n : fromSearch\n\n // Then the link/navigate function\n const destSearch =\n dest.search === true\n ? preFilteredSearch // Preserve resolvedFrom true\n : dest.search\n ? functionalUpdate(dest.search, preFilteredSearch) ?? {} // Updater\n : preSearchFilters?.length\n ? preFilteredSearch // Preserve resolvedFrom filters\n : {}\n\n // Then post filters\n const postFilteredSearch = postSearchFilters?.length\n ? postSearchFilters.reduce((prev, next) => next(prev), destSearch)\n : destSearch\n\n const search = replaceEqualDeep(fromSearch, postFilteredSearch)\n\n const searchStr = this.options.stringifySearch(search)\n\n const hash =\n dest.hash === true\n ? this.latestLocation.hash\n : dest.hash\n ? functionalUpdate(dest.hash!, this.latestLocation.hash)\n : undefined\n\n const hashStr = hash ? `#${hash}` : ''\n\n let nextState =\n dest.state === true\n ? this.latestLocation.state\n : dest.state\n ? functionalUpdate(dest.state, this.latestLocation.state)\n : {}\n\n nextState = replaceEqualDeep(this.latestLocation.state, nextState)\n\n return {\n pathname,\n search,\n searchStr,\n state: nextState as any,\n hash: hash ?? '',\n href: `${pathname}${searchStr}${hashStr}`,\n unmaskOnReload: dest.unmaskOnReload,\n }\n }\n\n const buildWithMatches = (\n dest: BuildNextOptions = {},\n maskedDest?: BuildNextOptions,\n ) => {\n let next = build(dest)\n let maskedNext = maskedDest ? build(maskedDest) : undefined\n\n if (!maskedNext) {\n let params = {}\n\n let foundMask = this.options.routeMasks?.find((d) => {\n const match = matchPathname(this.basepath, next.pathname, {\n to: d.from,\n caseSensitive: false,\n fuzzy: false,\n })\n\n if (match) {\n params = match\n return true\n }\n\n return false\n })\n\n if (foundMask) {\n maskedDest = {\n ...pick(opts, ['from']),\n ...foundMask,\n params,\n }\n maskedNext = build(maskedDest)\n }\n }\n\n const nextMatches = this.matchRoutes(next.pathname, next.search)\n const maskedMatches = maskedNext\n ? this.matchRoutes(maskedNext.pathname, maskedNext.search)\n : undefined\n const maskedFinal = maskedNext\n ? build(maskedDest, maskedMatches)\n : undefined\n\n const final = build(dest, nextMatches)\n\n if (maskedFinal) {\n final.maskedLocation = maskedFinal\n }\n\n return final\n }\n\n if (opts.mask) {\n return buildWithMatches(opts, {\n ...pick(opts, ['from']),\n ...opts.mask,\n })\n }\n\n return buildWithMatches(opts)\n }\n\n commitLocation = async ({\n startTransition,\n ...next\n }: ParsedLocation & CommitLocationOptions) => {\n if (this.navigateTimeout) clearTimeout(this.navigateTimeout)\n\n const isSameUrl = this.latestLocation.href === next.href\n\n // If the next urls are the same and we're not replacing,\n // do nothing\n if (!isSameUrl || !next.replace) {\n let { maskedLocation, ...nextHistory } = next\n\n if (maskedLocation) {\n nextHistory = {\n ...maskedLocation,\n state: {\n ...maskedLocation.state,\n __tempKey: undefined,\n __tempLocation: {\n ...nextHistory,\n search: nextHistory.searchStr,\n state: {\n ...nextHistory.state,\n __tempKey: undefined!,\n __tempLocation: undefined!,\n key: undefined!,\n },\n },\n },\n }\n\n if (\n nextHistory.unmaskOnReload ??\n this.options.unmaskOnReload ??\n false\n ) {\n nextHistory.state.__tempKey = this.tempLocationKey\n }\n }\n\n const apply = () => {\n this.history[next.replace ? 'replace' : 'push'](\n nextHistory.href,\n nextHistory.state,\n )\n }\n\n if (startTransition ?? true) {\n this.startReactTransition(apply)\n } else {\n apply()\n }\n }\n\n this.resetNextScroll = next.resetScroll ?? true\n\n return this.latestLoadPromise\n }\n\n buildAndCommitLocation = ({\n replace,\n resetScroll,\n startTransition,\n ...rest\n }: BuildNextOptions & CommitLocationOptions = {}) => {\n const location = this.buildLocation(rest as any)\n return this.commitLocation({\n ...location,\n startTransition,\n replace,\n resetScroll,\n })\n }\n\n navigate: NavigateFn<TRouteTree> = ({ from, to, ...rest }) => {\n // If this link simply reloads the current route,\n // make sure it has a new key so it will trigger a data refresh\n\n // If this `to` is a valid external URL, return\n // null for LinkUtils\n const toString = String(to)\n // const fromString = from !== undefined ? String(from) : from\n let isExternal\n\n try {\n new URL(`${toString}`)\n isExternal = true\n } catch (e) {}\n\n invariant(\n !isExternal,\n 'Attempting to navigate to external url with this.navigate!',\n )\n\n return this.buildAndCommitLocation({\n ...rest,\n from,\n to,\n // to: toString,\n })\n }\n\n loadMatches = async ({\n checkLatest,\n matches,\n preload,\n }: {\n checkLatest: () => Promise<void> | undefined\n matches: AnyRouteMatch[]\n preload?: boolean\n }): Promise<RouteMatch[]> => {\n let latestPromise\n let firstBadMatchIndex: number | undefined\n\n const updateMatch = (match: AnyRouteMatch) => {\n // const isPreload = this.state.cachedMatches.find((d) => d.id === match.id)\n const isPending = this.state.pendingMatches?.find(\n (d) => d.id === match.id,\n )\n\n const isMatched = this.state.matches.find((d) => d.id === match.id)\n\n const matchesKey = isPending\n ? 'pendingMatches'\n : isMatched\n ? 'matches'\n : 'cachedMatches'\n\n this.__store.setState((s) => ({\n ...s,\n [matchesKey]: s[matchesKey]?.map((d) =>\n d.id === match.id ? match : d,\n ),\n }))\n }\n\n // Check each match middleware to see if the route can be accessed\n try {\n for (let [index, match] of matches.entries()) {\n const parentMatch = matches[index - 1]\n const route = this.looseRoutesById[match.routeId]!\n const abortController = new AbortController()\n\n const handleErrorAndRedirect = (err: any, code: string) => {\n err.routerCode = code\n firstBadMatchIndex = firstBadMatchIndex ?? index\n\n if (isRedirect(err)) {\n throw err\n }\n\n if (isNotFound(err)) {\n this.updateMatchesWithNotFound(matches, match, err)\n }\n\n try {\n route.options.onError?.(err)\n } catch (errorHandlerErr) {\n err = errorHandlerErr\n\n if (isRedirect(errorHandlerErr)) {\n throw errorHandlerErr\n }\n }\n\n matches[index] = match = {\n ...match,\n error: err,\n status: 'error',\n updatedAt: Date.now(),\n abortController: new AbortController(),\n }\n }\n\n try {\n if (match.paramsError) {\n handleErrorAndRedirect(match.paramsError, 'PARSE_PARAMS')\n }\n\n if (match.searchError) {\n handleErrorAndRedirect(match.searchError, 'VALIDATE_SEARCH')\n }\n\n const parentContext =\n parentMatch?.context ?? this.options.context ?? {}\n\n const pendingMs =\n route.options.pendingMs ?? this.options.defaultPendingMs\n const pendingPromise =\n typeof pendingMs === 'number' && pendingMs <= 0\n ? Promise.resolve()\n : new Promise<void>((r) => setTimeout(r, pendingMs))\n\n const beforeLoadContext =\n (await route.options.beforeLoad?.({\n search: match.search,\n abortController,\n params: match.params,\n preload: !!preload,\n context: parentContext,\n location: this.state.location,\n // TOOD: just expose state and router, etc\n navigate: (opts) =>\n this.navigate({ ...opts, from: match.pathname } as any),\n buildLocation: this.buildLocation,\n cause: preload ? 'preload' : match.cause,\n })) ?? ({} as any)\n\n if (isRedirect(beforeLoadContext)) {\n throw beforeLoadContext\n }\n\n const context = {\n ...parentContext,\n ...beforeLoadContext,\n }\n\n matches[index] = match = {\n ...match,\n routeContext: replaceEqualDeep(\n match.routeContext,\n beforeLoadContext,\n ),\n context: replaceEqualDeep(match.context, context),\n abortController,\n pendingPromise,\n }\n } catch (err) {\n handleErrorAndRedirect(err, 'BEFORE_LOAD')\n break\n }\n }\n } catch (err) {\n if (isRedirect(err)) {\n if (!preload) this.navigate(err as any)\n return matches\n }\n\n throw err\n }\n\n const validResolvedMatches = matches.slice(0, firstBadMatchIndex)\n const matchPromises: Promise<any>[] = []\n\n validResolvedMatches.forEach((match, index) => {\n matchPromises.push(\n new Promise<void>(async (resolve) => {\n const parentMatchPromise = matchPromises[index - 1]\n const route = this.looseRoutesById[match.routeId]!\n\n const handleErrorAndRedirect = (err: any) => {\n if (isRedirect(err)) {\n if (!preload) {\n this.navigate(err as any)\n }\n return true\n }\n\n if (isNotFound(err)) {\n if (!preload) {\n this.updateMatchesWithNotFound(matches, match, err)\n }\n return true\n }\n\n return false\n }\n\n let loadPromise: Promise<void> | undefined\n\n matches[index] = match = {\n ...match,\n showPending: false,\n }\n\n let didShowPending = false\n const pendingMs =\n route.options.pendingMs ?? this.options.defaultPendingMs\n const pendingMinMs =\n route.options.pendingMinMs ?? this.options.defaultPendingMinMs\n const shouldPending =\n !preload &&\n typeof pendingMs === 'number' &&\n (route.options.pendingComponent ??\n this.options.defaultPendingComponent)\n\n const loaderContext: LoaderFnContext = {\n params: match.params,\n deps: match.loaderDeps,\n preload: !!preload,\n parentMatchPromise,\n abortController: match.abortController,\n context: match.context,\n location: this.state.location,\n navigate: (opts) =>\n this.navigate({ ...opts, from: match.pathname } as any),\n cause: preload ? 'preload' : match.cause,\n }\n\n const fetch = async () => {\n if (match.isFetching) {\n loadPromise = getRouteMatch(this.state, match.id)?.loadPromise\n } else {\n // If the user doesn't want the route to reload, just\n // resolve with the existing loader data\n\n if (match.fetchCount && match.status === 'success') {\n resolve()\n }\n\n // Otherwise, load the route\n matches[index] = match = {\n ...match,\n isFetching: true,\n fetchCount: match.fetchCount + 1,\n }\n\n const lazyPromise =\n route.lazyFn?.().then((lazyRoute) => {\n Object.assign(route.options, lazyRoute.options)\n }) || Promise.resolve()\n\n // If for some reason lazy resolves more lazy components...\n // We'll wait for that before pre attempt to preload any\n // components themselves.\n const componentsPromise = lazyPromise.then(() =>\n Promise.all(\n componentTypes.map(async (type) => {\n const component = route.options[type]\n\n if ((component as any)?.preload) {\n await (component as any).preload()\n }\n }),\n ),\n )\n\n // Kick off the loader!\n const loaderPromise = route.options.loader?.(loaderContext)\n\n loadPromise = Promise.all([\n componentsPromise,\n loaderPromise,\n lazyPromise,\n ]).then((d) => d[1])\n }\n\n matches[index] = match = {\n ...match,\n loadPromise,\n }\n\n updateMatch(match)\n\n try {\n const loaderData = await loadPromise\n if ((latestPromise = checkLatest())) return await latestPromise\n\n if (isRedirect(loaderData) || isNotFound(loaderData)) {\n if (handleErrorAndRedirect(loaderData)) return\n }\n\n if (didShowPending && pendingMinMs) {\n await new Promise((r) => setTimeout(r, pendingMinMs))\n }\n\n if ((latestPromise = checkLatest())) return await latestPromise\n\n const meta = route.options.meta?.({\n loaderData,\n })\n\n matches[index] = match = {\n ...match,\n error: undefined,\n status: 'success',\n isFetching: false,\n updatedAt: Date.now(),\n loaderData,\n loadPromise: undefined,\n meta,\n }\n } catch (error) {\n if ((latestPromise = checkLatest())) return await latestPromise\n if (handleErrorAndRedirect(error)) return\n\n try {\n route.options.onError?.(error)\n } catch (onErrorError) {\n error = onErrorError\n if (handleErrorAndRedirect(onErrorError)) return\n }\n\n matches[index] = match = {\n ...match,\n error,\n status: 'error',\n isFetching: false,\n }\n }\n\n updateMatch(match)\n }\n\n // This is where all of the stale-while-revalidate magic happens\n const age = Date.now() - match.updatedAt\n\n let staleAge = preload\n ? route.options.preloadStaleTime ??\n this.options.defaultPreloadStaleTime ??\n 30_000 // 30 seconds for preloads by default\n : route.options.staleTime ?? this.options.defaultStaleTime ?? 0\n\n // Default to reloading the route all the time\n let shouldReload\n\n const shouldReloadOption = route.options.shouldReload\n\n // Allow shouldReload to get the last say,\n // if provided.\n shouldReload =\n typeof shouldReloadOption === 'function'\n ? shouldReloadOption(loaderContext)\n : shouldReloadOption\n\n matches[index] = match = {\n ...match,\n preload:\n !!preload && !this.state.matches.find((d) => d.id === match.id),\n }\n\n if (match.status !== 'success') {\n // If we need to potentially show the pending component,\n // start a timer to show it after the pendingMs\n if (shouldPending) {\n match.pendingPromise?.then(async () => {\n if ((latestPromise = checkLatest())) return latestPromise\n\n didShowPending = true\n matches[index] = match = {\n ...match,\n showPending: true,\n }\n\n updateMatch(match)\n resolve()\n })\n }\n\n // Critical Fetching, we need to await\n await fetch()\n } else if (match.invalid || (shouldReload ?? age > staleAge)) {\n // Background Fetching, no need to wait\n fetch()\n }\n\n resolve()\n }),\n )\n })\n\n await Promise.all(matchPromises)\n return matches\n }\n\n invalidate = () => {\n const invalidate = (d: any) => ({\n ...d,\n invalid: true,\n })\n\n this.__store.setState((s) => ({\n ...s,\n matches: s.matches.map(invalidate),\n cachedMatches: s.cachedMatches.map(invalidate),\n pendingMatches: s.pendingMatches?.map(invalidate),\n }))\n\n this.load()\n }\n\n load = async (): Promise<void> => {\n const promise = new Promise<void>(async (resolve, reject) => {\n const next = this.latestLocation\n const prevLocation = this.state.resolvedLocation\n const pathDidChange = prevLocation!.href !== next.href\n let latestPromise: Promise<void> | undefined | null\n\n // Cancel any pending matches\n this.cancelMatches()\n\n this.emit({\n type: 'onBeforeLoad',\n fromLocation: prevLocation,\n toLocation: next,\n pathChanged: pathDidChange,\n })\n\n let pendingMatches!: RouteMatch<any, any>[]\n const previousMatches = this.state.matches\n\n this.__store.batch(() => {\n this.cleanCache()\n\n // Match the routes\n pendingMatches = this.matchRoutes(next.pathname, next.search, {\n debug: true,\n })\n\n // Ingest the new matches\n // If a cached moved to pendingMatches, remove it from cachedMatches\n this.__store.setState((s) => ({\n ...s,\n isLoading: true,\n location: next,\n pendingMatches,\n cachedMatches: s.cachedMatches.filter((d) => {\n return !pendingMatches.find((e) => e.id === d.id)\n }),\n }))\n })\n\n try {\n try {\n // Load the matches\n await this.loadMatches({\n matches: pendingMatches,\n checkLatest: () => this.checkLatest(promise),\n })\n } catch (err) {\n // swallow this error, since we'll display the\n // errors on the route components\n }\n\n // Only apply the latest transition\n if ((latestPromise = this.checkLatest(promise))) {\n return latestPromise\n }\n\n const exitingMatches = previousMatches.filter(\n (match) => !pendingMatches.find((d) => d.id === match.id),\n )\n const enteringMatches = pendingMatches.filter(\n (match) => !previousMatches.find((d) => d.id === match.id),\n )\n const stayingMatches = previousMatches.filter((match) =>\n pendingMatches.find((d) => d.id === match.id),\n )\n\n // Commit the pending matches. If a previous match was\n // removed, place it in the cachedMatches\n this.__store.batch(() => {\n this.__store.setState((s) => ({\n ...s,\n isLoading: false,\n matches: s.pendingMatches!,\n pendingMatches: undefined,\n cachedMatches: [\n ...s.cachedMatches,\n ...exitingMatches.filter((d) => d.status !== 'error'),\n ],\n }))\n this.cleanCache()\n })\n\n //\n ;(\n [\n [exitingMatches, 'onLeave'],\n [enteringMatches, 'onEnter'],\n [stayingMatches, 'onStay'],\n ] as const\n ).forEach(([matches, hook]) => {\n matches.forEach((match) => {\n this.looseRoutesById[match.routeId]!.options[hook]?.(match)\n })\n })\n\n this.emit({\n type: 'onLoad',\n fromLocation: prevLocation,\n toLocation: next,\n pathChanged: pathDidChange,\n })\n\n resolve()\n } catch (err) {\n // Only apply the latest transition\n if ((latestPromise = this.checkLatest(promise))) {\n return latestPromise\n }\n\n reject(err)\n }\n })\n\n this.latestLoadPromise = promise\n\n return this.latestLoadPromise\n }\n\n cleanCache = () => {\n // This is where all of the garbage collection magic happens\n this.__store.setState((s) => {\n return {\n ...s,\n cachedMatches: s.cachedMatches.filter((d) => {\n const route = this.looseRoutesById[d.routeId]!\n\n if (!route.options.loader) {\n return false\n }\n\n // If the route was preloaded, use the preloadGcTime\n // otherwise, use the gcTime\n const gcTime =\n (d.preload\n ? route.options.preloadGcTime ?? this.options.defaultPreloadGcTime\n : route.options.gcTime ?? this.options.defaultGcTime) ??\n 5 * 60 * 1000\n\n return d.status !== 'error' && Date.now() - d.updatedAt < gcTime\n }),\n }\n })\n }\n\n preloadRoute = async (\n navigateOpts: ToOptions<TRouteTree> = this.state.location as any,\n ) => {\n let next = this.buildLocation(navigateOpts as any)\n\n let matches = this.matchRoutes(next.pathname, next.search, {\n throwOnError: true,\n })\n\n const loadedMatchIds = Object.fromEntries(\n [\n ...this.state.matches,\n ...(this.state.pendingMatches ?? []),\n ...this.state.cachedMatches,\n ]?.map((d) => [d.id, true]),\n )\n\n this.__store.batch(() => {\n matches.forEach((match) => {\n if (!loadedMatchIds[match.id]) {\n this.__store.setState((s) => ({\n ...s,\n cachedMatches: [...(s.cachedMatches as any), match],\n }))\n }\n })\n })\n\n matches = await this.loadMatches({\n matches,\n preload: true,\n checkLatest: () => undefined,\n })\n\n return matches\n }\n\n matchRoute = <\n TFrom extends RoutePaths<TRouteTree> = '/',\n TTo extends string = '',\n TResolved = ResolveRelativePath<TFrom, NoInfer<TTo>>,\n >(\n location: ToOptions<TRouteTree, TFrom, TTo>,\n opts?: MatchRouteOptions,\n ): false | RouteById<TRouteTree, TResolved>['types']['allParams'] => {\n const matchLocation = {\n ...location,\n to: location.to\n ? this.resolvePathWithBase((location.from || '') as string, location.to)\n : undefined,\n params: location.params || {},\n leaveParams: true,\n }\n const next = this.buildLocation(matchLocation as any)\n\n if (opts?.pending && this.state.status !== 'pending') {\n return false\n }\n\n const baseLocation = opts?.pending\n ? this.latestLocation\n : this.state.resolvedLocation\n\n if (!baseLocation) {\n return false\n }\n const match = matchPathname(this.basepath, baseLocation.pathname, {\n ...opts,\n to: next.pathname,\n }) as any\n\n if (!match) {\n return false\n }\n if (location.params) {\n if (!deepEqual(match, location.params, true)) {\n return false\n }\n }\n\n if (match && (opts?.includeSearch ?? true)) {\n return deepEqual(baseLocation.search, next.search, true) ? match : false\n }\n\n return match\n }\n\n injectHtml = async (html: string | (() => Promise<string> | string)) => {\n this.injectedHtml.push(html)\n }\n\n dehydrateData = <T>(key: any, getData: T | (() => Promise<T> | T)) => {\n if (typeof document === 'undefined') {\n const strKey = typeof key === 'string' ? key : JSON.stringify(key)\n\n this.injectHtml(async () => {\n const id = `__TSR_DEHYDRATED__${strKey}`\n const data =\n typeof getData === 'function' ? await (getData as any)() : getData\n return `<script id='${id}' suppressHydrationWarning>window[\"__TSR_DEHYDRATED__${escapeJSON(\n strKey,\n )}\"] = ${JSON.stringify(this.options.transformer.stringify(data))}\n ;(() => {\n var el = document.getElementById('${id}')\n el.parentElement.removeChild(el)\n })()\n </script>`\n })\n\n return () => this.hydrateData<T>(key)\n }\n\n return () => undefined\n }\n\n hydrateData = <T extends any = unknown>(key: any) => {\n if (typeof document !== 'undefined') {\n const strKey = typeof key === 'string' ? key : JSON.stringify(key)\n\n return this.options.transformer.parse(\n window[`__TSR_DEHYDRATED__${strKey}` as any] as unknown as string,\n ) as T\n }\n\n return undefined\n }\n\n dehydrate = (): DehydratedRouter => {\n const pickError =\n this.options.errorSerializer?.serialize ?? defaultSerializeError\n\n return {\n state: {\n dehydratedMatches: this.state.matches.map((d) => ({\n ...pick(d, [\n 'id',\n 'status',\n 'updatedAt',\n 'loaderData',\n // Not-founds that occur during SSR don't require the client to load data before\n // triggering in order to prevent the flicker of the loading component\n 'notFoundError',\n ]),\n // If an error occurs server-side during SSRing,\n // send a small subset of the error to the client\n error: d.error\n ? {\n data: pickError(d.error),\n __isServerError: true,\n }\n : undefined,\n })),\n },\n }\n }\n\n hydrate = async (__do_not_use_server_ctx?: string) => {\n let _ctx = __do_not_use_server_ctx\n // Client hydrates from window\n if (typeof document !== 'undefined') {\n _ctx = window.__TSR_DEHYDRATED__?.data\n }\n\n invariant(\n _ctx,\n 'Expected to find a __TSR_DEHYDRATED__ property on window... but we did not. Did you forget to render <DehydrateRouter /> in your app?',\n )\n\n const ctx = this.options.transformer.parse(_ctx) as HydrationCtx\n this.dehydratedData = ctx.payload as any\n this.options.hydrate?.(ctx.payload as any)\n const dehydratedState = ctx.router.state\n\n let matches = this.matchRoutes(\n this.state.location.pathname,\n this.state.location.search,\n ).map((match) => {\n const dehydratedMatch = dehydratedState.dehydratedMatches.find(\n (d) => d.id === match.id,\n )\n\n invariant(\n dehydratedMatch,\n `Could not find a client-side match for dehydrated match with id: ${match.id}!`,\n )\n\n if (dehydratedMatch) {\n const route = this.looseRoutesById[match.routeId]!\n\n return {\n ...match,\n ...dehydratedMatch,\n meta: route.options.meta?.({\n loaderData: dehydratedMatch.loaderData,\n }),\n links: route.options.links?.(),\n scripts: route.options.scripts?.(),\n }\n }\n return match\n })\n\n this.__store.setState((s) => {\n return {\n ...s,\n matches: matches as any,\n lastUpdated: Date.now(),\n }\n })\n }\n\n // Finds a match that has a notFoundComponent\n updateMatchesWithNotFound = (\n matches: AnyRouteMatch[],\n currentMatch: AnyRouteMatch,\n err: NotFoundError,\n ) => {\n const matchesByRouteId = Object.fromEntries(\n matches.map((match) => [match.routeId, match]),\n ) as Record<string, AnyRouteMatch>\n\n if (err.global) {\n matchesByRouteId[rootRouteId]!.notFoundError = err\n } else {\n // If the err contains a routeId, start searching up from that route\n let currentRoute = (this.routesById as any)[\n err.route ?? currentMatch.routeId\n ] as AnyRoute\n\n // Go up the tree until we find a route with a notFoundComponent\n while (!currentRoute.options.notFoundComponent) {\n currentRoute = currentRoute?.parentRoute\n\n invariant(\n currentRoute,\n 'Found invalid route tree while trying to find not-found handler.',\n )\n\n if (currentRoute.id === rootRouteId) break\n }\n\n const match = matchesByRouteId[currentRoute.id]\n invariant(match, 'Could not find match for route: ' + currentRoute.id)\n match.notFoundError = err\n }\n }\n\n hasNotFoundMatch = () => {\n return this.__store.state.matches.some((d) => d.notFoundError)\n }\n\n // resolveMatchPromise = (matchId: string, key: string, value: any) => {\n // state.matches\n // .find((d) => d.id === matchId)\n // ?.__promisesByKey[key]?.resolve(value)\n // }\n}\n\n// A function that takes an import() argument which is a function and returns a new function that will\n// proxy arguments from the caller to the imported function, retaining all type\n// information along the way\nexport function lazyFn<\n T extends Record<string, (...args: any[]) => any>,\n TKey extends keyof T = 'default',\n>(fn: () => Promise<T>, key?: TKey) {\n return async (\n ...args: Parameters<T[TKey]>\n ): Promise<Awaited<ReturnType<T[TKey]>>> => {\n const imported = await fn()\n return imported[key || 'default'](...args)\n }\n}\n\nexport class SearchParamError extends Error {}\n\nexport class PathParamError extends Error {}\n\nexport function getInitialRouterState(\n location: ParsedLocation,\n): RouterState<any> {\n return {\n isLoading: false,\n isTransitioning: false,\n status: 'idle',\n resolvedLocation: { ...location },\n location,\n matches: [],\n pendingMatches: [],\n cachedMatches: [],\n lastUpdated: 0,\n }\n}\n\nexport function defaultSerializeError(err: unknown) {\n if (err instanceof Error)\n return {\n name: err.name,\n message: err.message,\n }\n\n return {\n data: err,\n }\n}\n"],"names":["d","searchError","_a","_b","_c"],"mappings":";;;;;;;;;;AA8MO,MAAM,iBAAiB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA8BO,SAAS,aAKd,SACA;AACO,SAAA,IAAI,OAAkD,OAAO;AACtE;AAEO,MAAM,OAIX;AAAA;AAAA;AAAA;AAAA,EAkCA,YACE,SAKA;AAtCF,SAAA,kBAAsC,GAAG,KAAK;AAAA,MAC5C,KAAK,WAAW;AAAA,IACjB,CAAA;AAC0B,SAAA,kBAAA;AACO,SAAA,kBAAA;AAClC,SAAA,oBAAmC,QAAQ;AAC3C,SAAA,kCAAkB;AAClB,SAAA,eAAoC;AA+Ca,SAAA,uBAAA,CAAC,OAAO,GAAG;AAE5D,SAAA,SAAS,CACP,eAKG;AACH,UAAI,WAAW,eAAe;AACpB,gBAAA;AAAA,UACN;AAAA,QAAA;AAAA,MAEJ;AAEA,YAAM,kBAAkB,KAAK;AAC7B,WAAK,UAAU;AAAA,QACb,GAAG,KAAK;AAAA,QACR,GAAG;AAAA,MAAA;AAIH,UAAA,CAAC,KAAK,YACL,WAAW,YAAY,WAAW,aAAa,gBAAgB,UAChE;AAEE,YAAA,WAAW,aAAa,UACxB,WAAW,aAAa,MACxB,WAAW,aAAa,KACxB;AACA,eAAK,WAAW;AAAA,QAAA,OACX;AACL,eAAK,WAAW,IAAI,SAAS,WAAW,QAAQ,CAAC;AAAA,QACnD;AAAA,MACF;AAGE,UAAA,CAAC,KAAK,WACL,KAAK,QAAQ,WAAW,KAAK,QAAQ,YAAY,KAAK,SACvD;AACK,aAAA,UACH,KAAK,QAAQ,YACZ,OAAO,aAAa,cACjB,qBAAqB,IACrB,oBAAoB;AAAA,UAClB,gBAAgB,CAAC,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WAAO,KAAK,QAAQ;AAAA,EACtB;AAAA,EA+LA,IAAI,kBAAkB;AACpB,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AA6wCF;AAKgB,SAAA,OAGd,IAAsB,KAAY;AAClC,SAAO,UACF,SACuC;AACpC,UAAA,WAAW,MAAM;AACvB,WAAO,SAAS,OAAO,SAAS,EAAE,GAAG,IAAI;AAAA,EAAA;AAE7C;AAEO,MAAM,yBAAyB,MAAM;AAAC;AAEtC,MAAM,uBAAuB,MAAM;AAAC;AAEpC,SAAS,sBACd,UACkB;AACX,SAAA;AAAA,IACL,WAAW;AAAA,IACX,iBAAiB;AAAA,IACjB,QAAQ;AAAA,IACR,kBAAkB,EAAE,GAAG,SAAS;AAAA,IAChC;AAAA,IACA,SAAS,CAAC;AAAA,IACV,gBAAgB,CAAC;AAAA,IACjB,eAAe,CAAC;AAAA,IAChB,aAAa;AAAA,EAAA;AAEjB;AAEO,SAAS,sBAAsB,KAAc;AAClD,MAAI,eAAe;AACV,WAAA;AAAA,MACL,MAAM,IAAI;AAAA,MACV,SAAS,IAAI;AAAA,IAAA;AAGV,SAAA;AAAA,IACL,MAAM;AAAA,EAAA;AAEV;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/react-router",
3
- "version": "1.15.2",
3
+ "version": "1.15.3",
4
4
  "description": "",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -0,0 +1,105 @@
1
+ import invariant from 'tiny-invariant'
2
+
3
+ export const XTSROrigin = 'x-tsr-origin'
4
+
5
+ export interface JsonResponse<TData> extends Response {
6
+ json(): Promise<TData>
7
+ }
8
+
9
+ export type FetcherOptionsBase = {
10
+ method?: 'GET' | 'POST'
11
+ }
12
+
13
+ export type FetcherOptions = FetcherOptionsBase & {
14
+ requestInit?: RequestInit
15
+ }
16
+
17
+ export type FetchFnCtx = {
18
+ method: 'GET' | 'POST'
19
+ request: Request
20
+ }
21
+
22
+ export type FetchFn<TPayload, TResponse> = {
23
+ (payload: TPayload, ctx: FetchFnCtx): TResponse
24
+ url?: string
25
+ }
26
+
27
+ // export type AnyFetchFn = FetchFn<any, any>
28
+
29
+ // export type FetchFnReturn<T extends AnyFetchFn> =
30
+ // Awaited<ReturnType<T>> extends JsonResponse<infer R> ? R : ReturnType<T>
31
+
32
+ // export type FetcherFn<T extends AnyFetchFn> = Parameters<T>[0] extends undefined
33
+ // ? (
34
+ // payload?: Parameters<T>['0'],
35
+ // opts?: FetchFnCtx,
36
+ // ) => Promise<Awaited<FetchFnReturn<T>>>
37
+ // : (
38
+ // payload: Parameters<T>['0'],
39
+ // opts?: FetchFnCtx,
40
+ // ) => Promise<Awaited<FetchFnReturn<T>>>
41
+
42
+ // export type FetcherMethods<T extends AnyFetchFn> = {
43
+ // url: string
44
+ // fetch: (
45
+ // init: RequestInit,
46
+ // opts?: FetcherOptions,
47
+ // ) => Promise<Awaited<FetchFnReturn<T>>>
48
+ // }
49
+
50
+ // export type Fetcher<T extends AnyFetchFn> = FetcherFn<T> & FetcherMethods<T>
51
+
52
+ export type CompiledFetcherFnOptions<TPayload> = {
53
+ method: 'GET' | 'POST'
54
+ type: 'request' | 'payload'
55
+ payload: TPayload
56
+ requestInit?: RequestInit
57
+ }
58
+
59
+ export type CompiledFetcherFn<TPayload, TResponse> = {
60
+ (opts: CompiledFetcherFnOptions<TPayload>): Promise<TResponse>
61
+ url: string
62
+ }
63
+
64
+ export type Fetcher<TPayload, TResponse> = (TPayload extends undefined
65
+ ? {
66
+ (payload?: TPayload, opts?: FetcherOptions): Promise<TResponse>
67
+ }
68
+ : {
69
+ (payload: TPayload, opts?: FetcherOptions): Promise<TResponse>
70
+ }) & {
71
+ url: string
72
+ }
73
+
74
+ export function createServerFn<TPayload, TResponse>(
75
+ method: 'GET' | 'POST',
76
+ fn: FetchFn<TPayload, TResponse>,
77
+ ): Fetcher<TPayload, TResponse> {
78
+ // Cast the compiled function that will be injected by vinxi
79
+ const compiledFn = fn as unknown as CompiledFetcherFn<TPayload, TResponse>
80
+
81
+ console.log(
82
+ compiledFn,
83
+ compiledFn.toString(),
84
+ JSON.stringify(compiledFn, null, 2),
85
+ )
86
+
87
+ invariant(
88
+ compiledFn.url,
89
+ `createServerFn must be called with a function that is marked with the 'use server' pragma.`,
90
+ )
91
+
92
+ return Object.assign(
93
+ async (payload: TPayload, opts?: FetcherOptions) => {
94
+ return compiledFn({
95
+ method,
96
+ type: payload instanceof Request ? 'request' : 'payload',
97
+ payload,
98
+ requestInit: opts?.requestInit,
99
+ })
100
+ },
101
+ {
102
+ url: fn.url!,
103
+ },
104
+ ) as Fetcher<TPayload, TResponse>
105
+ }
package/src/index.tsx CHANGED
@@ -30,3 +30,4 @@ export * from './useRouter'
30
30
  export * from './useRouterState'
31
31
  export * from './utils'
32
32
  export * from './not-found'
33
+ export * from './createServerFn'
package/src/router.ts CHANGED
@@ -1243,7 +1243,10 @@ export class Router<
1243
1243
  }
1244
1244
 
1245
1245
  if (isNotFound(err)) {
1246
- this.updateMatchesWithNotFound(matches, match, err)
1246
+ if (!preload) {
1247
+ this.updateMatchesWithNotFound(matches, match, err)
1248
+ }
1249
+ return true
1247
1250
  }
1248
1251
 
1249
1252
  return false
@@ -1339,7 +1342,7 @@ export class Router<
1339
1342
  const loaderData = await loadPromise
1340
1343
  if ((latestPromise = checkLatest())) return await latestPromise
1341
1344
 
1342
- if (isRedirect(loaderData)) {
1345
+ if (isRedirect(loaderData) || isNotFound(loaderData)) {
1343
1346
  if (handleErrorAndRedirect(loaderData)) return
1344
1347
  }
1345
1348