@tanstack/router-core 0.0.1-beta.162 → 0.0.1-beta.163

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.
@@ -32,7 +32,7 @@ const stopBlocking = () => {
32
32
  function createHistory(opts) {
33
33
  let location = opts.getLocation();
34
34
  let unsub = () => {};
35
- let listeners = new Set();
35
+ let subscribers = new Set();
36
36
  let blockers = [];
37
37
  let queue = [];
38
38
  const tryFlush = () => {
@@ -46,7 +46,7 @@ function createHistory(opts) {
46
46
  while (queue.length) {
47
47
  queue.shift()?.();
48
48
  }
49
- if (!opts.listener) {
49
+ if (!opts.subscriber) {
50
50
  onUpdate();
51
51
  }
52
52
  };
@@ -56,20 +56,20 @@ function createHistory(opts) {
56
56
  };
57
57
  const onUpdate = () => {
58
58
  location = opts.getLocation();
59
- listeners.forEach(listener => listener());
59
+ subscribers.forEach(subscriber => subscriber());
60
60
  };
61
61
  return {
62
62
  get location() {
63
63
  return location;
64
64
  },
65
- listen: cb => {
66
- if (listeners.size === 0) {
67
- unsub = typeof opts.listener === 'function' ? opts.listener(onUpdate) : () => {};
65
+ subscribe: cb => {
66
+ if (subscribers.size === 0) {
67
+ unsub = typeof opts.subscriber === 'function' ? opts.subscriber(onUpdate) : () => {};
68
68
  }
69
- listeners.add(cb);
69
+ subscribers.add(cb);
70
70
  return () => {
71
- listeners.delete(cb);
72
- if (listeners.size === 0) {
71
+ subscribers.delete(cb);
72
+ if (subscribers.size === 0) {
73
73
  unsub();
74
74
  }
75
75
  };
@@ -122,7 +122,7 @@ function createBrowserHistory(opts) {
122
122
  const getLocation = () => parseLocation(getHref(), history.state);
123
123
  return createHistory({
124
124
  getLocation,
125
- listener: onUpdate => {
125
+ subscriber: onUpdate => {
126
126
  window.addEventListener(pushStateEvent, onUpdate);
127
127
  window.addEventListener(popStateEvent, onUpdate);
128
128
  var pushState = window.history.pushState;
@@ -177,7 +177,7 @@ function createMemoryHistory(opts = {
177
177
  const getLocation = () => parseLocation(entries[index], currentState);
178
178
  return createHistory({
179
179
  getLocation,
180
- listener: false,
180
+ subscriber: false,
181
181
  pushState: (path, state) => {
182
182
  currentState = {
183
183
  ...state,
@@ -1 +1 @@
1
- {"version":3,"file":"history.js","sources":["../../src/history.ts"],"sourcesContent":["// While the public API was clearly inspired by the \"history\" npm package,\n// This implementation attempts to be more lightweight by\n// making assumptions about the way TanStack Router works\n\nexport interface RouterHistory {\n location: RouterLocation\n listen: (cb: () => void) => () => void\n push: (path: string, state?: any) => void\n replace: (path: string, state?: any) => void\n go: (index: number) => void\n back: () => void\n forward: () => void\n createHref: (href: string) => string\n block: (blockerFn: BlockerFn) => () => void\n}\n\nexport interface ParsedPath {\n href: string\n pathname: string\n search: string\n hash: string\n}\n\nexport interface RouterLocation extends ParsedPath {\n state: any\n}\n\ntype BlockerFn = (retry: () => void, cancel: () => void) => void\n\nconst pushStateEvent = 'pushstate'\nconst popStateEvent = 'popstate'\nconst beforeUnloadEvent = 'beforeunload'\n\nconst beforeUnloadListener = (event: Event) => {\n event.preventDefault()\n // @ts-ignore\n return (event.returnValue = '')\n}\n\nconst stopBlocking = () => {\n removeEventListener(beforeUnloadEvent, beforeUnloadListener, {\n capture: true,\n })\n}\n\nfunction createHistory(opts: {\n getLocation: () => RouterLocation\n listener: false | ((onUpdate: () => void) => () => void)\n pushState: (path: string, state: any) => void\n replaceState: (path: string, state: any) => void\n go: (n: number) => void\n back: () => void\n forward: () => void\n createHref: (path: string) => string\n}): RouterHistory {\n let location = opts.getLocation()\n let unsub = () => {}\n let listeners = new Set<() => void>()\n let blockers: BlockerFn[] = []\n let queue: (() => void)[] = []\n\n const tryFlush = () => {\n if (blockers.length) {\n blockers[0]?.(tryFlush, () => {\n blockers = []\n stopBlocking()\n })\n return\n }\n\n while (queue.length) {\n queue.shift()?.()\n }\n\n if (!opts.listener) {\n onUpdate()\n }\n }\n\n const queueTask = (task: () => void) => {\n queue.push(task)\n tryFlush()\n }\n\n const onUpdate = () => {\n location = opts.getLocation()\n listeners.forEach((listener) => listener())\n }\n\n return {\n get location() {\n return location\n },\n listen: (cb: () => void) => {\n if (listeners.size === 0) {\n unsub =\n typeof opts.listener === 'function'\n ? opts.listener(onUpdate)\n : () => {}\n }\n listeners.add(cb)\n\n return () => {\n listeners.delete(cb)\n if (listeners.size === 0) {\n unsub()\n }\n }\n },\n push: (path: string, state: any) => {\n queueTask(() => {\n opts.pushState(path, state)\n })\n },\n replace: (path: string, state: any) => {\n queueTask(() => {\n opts.replaceState(path, state)\n })\n },\n go: (index) => {\n queueTask(() => {\n opts.go(index)\n })\n },\n back: () => {\n queueTask(() => {\n opts.back()\n })\n },\n forward: () => {\n queueTask(() => {\n opts.forward()\n })\n },\n createHref: (str) => opts.createHref(str),\n block: (cb) => {\n blockers.push(cb)\n\n if (blockers.length === 1) {\n addEventListener(beforeUnloadEvent, beforeUnloadListener, {\n capture: true,\n })\n }\n\n return () => {\n blockers = blockers.filter((b) => b !== cb)\n\n if (!blockers.length) {\n stopBlocking()\n }\n }\n },\n }\n}\n\nexport function createBrowserHistory(opts?: {\n getHref?: () => string\n createHref?: (path: string) => string\n}): RouterHistory {\n const getHref =\n opts?.getHref ??\n (() =>\n `${window.location.pathname}${window.location.search}${window.location.hash}`)\n const createHref = opts?.createHref ?? ((path) => path)\n const getLocation = () => parseLocation(getHref(), history.state)\n\n return createHistory({\n getLocation,\n listener: (onUpdate) => {\n window.addEventListener(pushStateEvent, onUpdate)\n window.addEventListener(popStateEvent, onUpdate)\n\n var pushState = window.history.pushState\n window.history.pushState = function () {\n let res = pushState.apply(history, arguments as any)\n onUpdate()\n return res\n }\n var replaceState = window.history.replaceState\n window.history.replaceState = function () {\n let res = replaceState.apply(history, arguments as any)\n onUpdate()\n return res\n }\n\n return () => {\n window.history.pushState = pushState\n window.history.replaceState = replaceState\n window.removeEventListener(pushStateEvent, onUpdate)\n window.removeEventListener(popStateEvent, onUpdate)\n }\n },\n pushState: (path, state) => {\n window.history.pushState(\n { ...state, key: createRandomKey() },\n '',\n createHref(path),\n )\n },\n replaceState: (path, state) => {\n window.history.replaceState(\n { ...state, key: createRandomKey() },\n '',\n createHref(path),\n )\n },\n back: () => window.history.back(),\n forward: () => window.history.forward(),\n go: (n) => window.history.go(n),\n createHref: (path) => createHref(path),\n })\n}\n\nexport function createHashHistory(): RouterHistory {\n return createBrowserHistory({\n getHref: () => window.location.hash.substring(1),\n createHref: (path) => `#${path}`,\n })\n}\n\nexport function createMemoryHistory(\n opts: {\n initialEntries: string[]\n initialIndex?: number\n } = {\n initialEntries: ['/'],\n },\n): RouterHistory {\n const entries = opts.initialEntries\n let index = opts.initialIndex ?? entries.length - 1\n let currentState = {}\n\n const getLocation = () => parseLocation(entries[index]!, currentState)\n\n return createHistory({\n getLocation,\n listener: false,\n pushState: (path, state) => {\n currentState = {\n ...state,\n key: createRandomKey(),\n }\n entries.push(path)\n index++\n },\n replaceState: (path, state) => {\n currentState = {\n ...state,\n key: createRandomKey(),\n }\n entries[index] = path\n },\n back: () => {\n index--\n },\n forward: () => {\n index = Math.min(index + 1, entries.length - 1)\n },\n go: (n) => window.history.go(n),\n createHref: (path) => path,\n })\n}\n\nfunction parseLocation(href: string, state: any): RouterLocation {\n let hashIndex = href.indexOf('#')\n let searchIndex = href.indexOf('?')\n\n return {\n href,\n pathname: href.substring(\n 0,\n hashIndex > 0\n ? searchIndex > 0\n ? Math.min(hashIndex, searchIndex)\n : hashIndex\n : searchIndex > 0\n ? searchIndex\n : href.length,\n ),\n hash: hashIndex > -1 ? href.substring(hashIndex) : '',\n search:\n searchIndex > -1\n ? href.slice(searchIndex, hashIndex === -1 ? undefined : hashIndex)\n : '',\n state,\n }\n}\n\n// Thanks co-pilot!\nfunction createRandomKey() {\n return (Math.random() + 1).toString(36).substring(7)\n}\n"],"names":["pushStateEvent","popStateEvent","beforeUnloadEvent","beforeUnloadListener","event","preventDefault","returnValue","stopBlocking","removeEventListener","capture","createHistory","opts","location","getLocation","unsub","listeners","Set","blockers","queue","tryFlush","length","shift","listener","onUpdate","queueTask","task","push","forEach","listen","cb","size","add","delete","path","state","pushState","replace","replaceState","go","index","back","forward","createHref","str","block","addEventListener","filter","b","createBrowserHistory","getHref","window","pathname","search","hash","parseLocation","history","res","apply","arguments","key","createRandomKey","n","createHashHistory","substring","createMemoryHistory","initialEntries","entries","initialIndex","currentState","Math","min","href","hashIndex","indexOf","searchIndex","slice","undefined","random","toString"],"mappings":";;;;;;;;;;;;;;AAAA;AACA;AACA;;AA2BA,MAAMA,cAAc,GAAG,WAAW,CAAA;AAClC,MAAMC,aAAa,GAAG,UAAU,CAAA;AAChC,MAAMC,iBAAiB,GAAG,cAAc,CAAA;AAExC,MAAMC,oBAAoB,GAAIC,KAAY,IAAK;EAC7CA,KAAK,CAACC,cAAc,EAAE,CAAA;AACtB;AACA,EAAA,OAAQD,KAAK,CAACE,WAAW,GAAG,EAAE,CAAA;AAChC,CAAC,CAAA;AAED,MAAMC,YAAY,GAAGA,MAAM;AACzBC,EAAAA,mBAAmB,CAACN,iBAAiB,EAAEC,oBAAoB,EAAE;AAC3DM,IAAAA,OAAO,EAAE,IAAA;AACX,GAAC,CAAC,CAAA;AACJ,CAAC,CAAA;AAED,SAASC,aAAaA,CAACC,IAStB,EAAiB;AAChB,EAAA,IAAIC,QAAQ,GAAGD,IAAI,CAACE,WAAW,EAAE,CAAA;AACjC,EAAA,IAAIC,KAAK,GAAGA,MAAM,EAAE,CAAA;AACpB,EAAA,IAAIC,SAAS,GAAG,IAAIC,GAAG,EAAc,CAAA;EACrC,IAAIC,QAAqB,GAAG,EAAE,CAAA;EAC9B,IAAIC,KAAqB,GAAG,EAAE,CAAA;EAE9B,MAAMC,QAAQ,GAAGA,MAAM;IACrB,IAAIF,QAAQ,CAACG,MAAM,EAAE;AACnBH,MAAAA,QAAQ,CAAC,CAAC,CAAC,GAAGE,QAAQ,EAAE,MAAM;AAC5BF,QAAAA,QAAQ,GAAG,EAAE,CAAA;AACbV,QAAAA,YAAY,EAAE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I,CAACQ,MAAM,EAAE,GAAG,CAAC,EAAEC,QAAQ,CAAC,EAAE,CAAC,CAACf,SAAS,CAAC,CAAC,CAAC,CAAA;AACtD;;;;;;"}
1
+ {"version":3,"file":"history.js","sources":["../../src/history.ts"],"sourcesContent":["// While the public API was clearly inspired by the \"history\" npm package,\n// This implementation attempts to be more lightweight by\n// making assumptions about the way TanStack Router works\n\nexport interface RouterHistory {\n location: RouterLocation\n subscribe: (cb: () => void) => () => void\n push: (path: string, state?: any) => void\n replace: (path: string, state?: any) => void\n go: (index: number) => void\n back: () => void\n forward: () => void\n createHref: (href: string) => string\n block: (blockerFn: BlockerFn) => () => void\n}\n\nexport interface ParsedPath {\n href: string\n pathname: string\n search: string\n hash: string\n}\n\nexport interface RouterLocation extends ParsedPath {\n state: any\n}\n\ntype BlockerFn = (retry: () => void, cancel: () => void) => void\n\nconst pushStateEvent = 'pushstate'\nconst popStateEvent = 'popstate'\nconst beforeUnloadEvent = 'beforeunload'\n\nconst beforeUnloadListener = (event: Event) => {\n event.preventDefault()\n // @ts-ignore\n return (event.returnValue = '')\n}\n\nconst stopBlocking = () => {\n removeEventListener(beforeUnloadEvent, beforeUnloadListener, {\n capture: true,\n })\n}\n\nfunction createHistory(opts: {\n getLocation: () => RouterLocation\n subscriber: false | ((onUpdate: () => void) => () => void)\n pushState: (path: string, state: any) => void\n replaceState: (path: string, state: any) => void\n go: (n: number) => void\n back: () => void\n forward: () => void\n createHref: (path: string) => string\n}): RouterHistory {\n let location = opts.getLocation()\n let unsub = () => {}\n let subscribers = new Set<() => void>()\n let blockers: BlockerFn[] = []\n let queue: (() => void)[] = []\n\n const tryFlush = () => {\n if (blockers.length) {\n blockers[0]?.(tryFlush, () => {\n blockers = []\n stopBlocking()\n })\n return\n }\n\n while (queue.length) {\n queue.shift()?.()\n }\n\n if (!opts.subscriber) {\n onUpdate()\n }\n }\n\n const queueTask = (task: () => void) => {\n queue.push(task)\n tryFlush()\n }\n\n const onUpdate = () => {\n location = opts.getLocation()\n subscribers.forEach((subscriber) => subscriber())\n }\n\n return {\n get location() {\n return location\n },\n subscribe: (cb: () => void) => {\n if (subscribers.size === 0) {\n unsub =\n typeof opts.subscriber === 'function'\n ? opts.subscriber(onUpdate)\n : () => {}\n }\n subscribers.add(cb)\n\n return () => {\n subscribers.delete(cb)\n if (subscribers.size === 0) {\n unsub()\n }\n }\n },\n push: (path: string, state: any) => {\n queueTask(() => {\n opts.pushState(path, state)\n })\n },\n replace: (path: string, state: any) => {\n queueTask(() => {\n opts.replaceState(path, state)\n })\n },\n go: (index) => {\n queueTask(() => {\n opts.go(index)\n })\n },\n back: () => {\n queueTask(() => {\n opts.back()\n })\n },\n forward: () => {\n queueTask(() => {\n opts.forward()\n })\n },\n createHref: (str) => opts.createHref(str),\n block: (cb) => {\n blockers.push(cb)\n\n if (blockers.length === 1) {\n addEventListener(beforeUnloadEvent, beforeUnloadListener, {\n capture: true,\n })\n }\n\n return () => {\n blockers = blockers.filter((b) => b !== cb)\n\n if (!blockers.length) {\n stopBlocking()\n }\n }\n },\n }\n}\n\nexport function createBrowserHistory(opts?: {\n getHref?: () => string\n createHref?: (path: string) => string\n}): RouterHistory {\n const getHref =\n opts?.getHref ??\n (() =>\n `${window.location.pathname}${window.location.search}${window.location.hash}`)\n const createHref = opts?.createHref ?? ((path) => path)\n const getLocation = () => parseLocation(getHref(), history.state)\n\n return createHistory({\n getLocation,\n subscriber: (onUpdate) => {\n window.addEventListener(pushStateEvent, onUpdate)\n window.addEventListener(popStateEvent, onUpdate)\n\n var pushState = window.history.pushState\n window.history.pushState = function () {\n let res = pushState.apply(history, arguments as any)\n onUpdate()\n return res\n }\n var replaceState = window.history.replaceState\n window.history.replaceState = function () {\n let res = replaceState.apply(history, arguments as any)\n onUpdate()\n return res\n }\n\n return () => {\n window.history.pushState = pushState\n window.history.replaceState = replaceState\n window.removeEventListener(pushStateEvent, onUpdate)\n window.removeEventListener(popStateEvent, onUpdate)\n }\n },\n pushState: (path, state) => {\n window.history.pushState(\n { ...state, key: createRandomKey() },\n '',\n createHref(path),\n )\n },\n replaceState: (path, state) => {\n window.history.replaceState(\n { ...state, key: createRandomKey() },\n '',\n createHref(path),\n )\n },\n back: () => window.history.back(),\n forward: () => window.history.forward(),\n go: (n) => window.history.go(n),\n createHref: (path) => createHref(path),\n })\n}\n\nexport function createHashHistory(): RouterHistory {\n return createBrowserHistory({\n getHref: () => window.location.hash.substring(1),\n createHref: (path) => `#${path}`,\n })\n}\n\nexport function createMemoryHistory(\n opts: {\n initialEntries: string[]\n initialIndex?: number\n } = {\n initialEntries: ['/'],\n },\n): RouterHistory {\n const entries = opts.initialEntries\n let index = opts.initialIndex ?? entries.length - 1\n let currentState = {}\n\n const getLocation = () => parseLocation(entries[index]!, currentState)\n\n return createHistory({\n getLocation,\n subscriber: false,\n pushState: (path, state) => {\n currentState = {\n ...state,\n key: createRandomKey(),\n }\n entries.push(path)\n index++\n },\n replaceState: (path, state) => {\n currentState = {\n ...state,\n key: createRandomKey(),\n }\n entries[index] = path\n },\n back: () => {\n index--\n },\n forward: () => {\n index = Math.min(index + 1, entries.length - 1)\n },\n go: (n) => window.history.go(n),\n createHref: (path) => path,\n })\n}\n\nfunction parseLocation(href: string, state: any): RouterLocation {\n let hashIndex = href.indexOf('#')\n let searchIndex = href.indexOf('?')\n\n return {\n href,\n pathname: href.substring(\n 0,\n hashIndex > 0\n ? searchIndex > 0\n ? Math.min(hashIndex, searchIndex)\n : hashIndex\n : searchIndex > 0\n ? searchIndex\n : href.length,\n ),\n hash: hashIndex > -1 ? href.substring(hashIndex) : '',\n search:\n searchIndex > -1\n ? href.slice(searchIndex, hashIndex === -1 ? undefined : hashIndex)\n : '',\n state,\n }\n}\n\n// Thanks co-pilot!\nfunction createRandomKey() {\n return (Math.random() + 1).toString(36).substring(7)\n}\n"],"names":["pushStateEvent","popStateEvent","beforeUnloadEvent","beforeUnloadListener","event","preventDefault","returnValue","stopBlocking","removeEventListener","capture","createHistory","opts","location","getLocation","unsub","subscribers","Set","blockers","queue","tryFlush","length","shift","subscriber","onUpdate","queueTask","task","push","forEach","subscribe","cb","size","add","delete","path","state","pushState","replace","replaceState","go","index","back","forward","createHref","str","block","addEventListener","filter","b","createBrowserHistory","getHref","window","pathname","search","hash","parseLocation","history","res","apply","arguments","key","createRandomKey","n","createHashHistory","substring","createMemoryHistory","initialEntries","entries","initialIndex","currentState","Math","min","href","hashIndex","indexOf","searchIndex","slice","undefined","random","toString"],"mappings":";;;;;;;;;;;;;;AAAA;AACA;AACA;;AA2BA,MAAMA,cAAc,GAAG,WAAW,CAAA;AAClC,MAAMC,aAAa,GAAG,UAAU,CAAA;AAChC,MAAMC,iBAAiB,GAAG,cAAc,CAAA;AAExC,MAAMC,oBAAoB,GAAIC,KAAY,IAAK;EAC7CA,KAAK,CAACC,cAAc,EAAE,CAAA;AACtB;AACA,EAAA,OAAQD,KAAK,CAACE,WAAW,GAAG,EAAE,CAAA;AAChC,CAAC,CAAA;AAED,MAAMC,YAAY,GAAGA,MAAM;AACzBC,EAAAA,mBAAmB,CAACN,iBAAiB,EAAEC,oBAAoB,EAAE;AAC3DM,IAAAA,OAAO,EAAE,IAAA;AACX,GAAC,CAAC,CAAA;AACJ,CAAC,CAAA;AAED,SAASC,aAAaA,CAACC,IAStB,EAAiB;AAChB,EAAA,IAAIC,QAAQ,GAAGD,IAAI,CAACE,WAAW,EAAE,CAAA;AACjC,EAAA,IAAIC,KAAK,GAAGA,MAAM,EAAE,CAAA;AACpB,EAAA,IAAIC,WAAW,GAAG,IAAIC,GAAG,EAAc,CAAA;EACvC,IAAIC,QAAqB,GAAG,EAAE,CAAA;EAC9B,IAAIC,KAAqB,GAAG,EAAE,CAAA;EAE9B,MAAMC,QAAQ,GAAGA,MAAM;IACrB,IAAIF,QAAQ,CAACG,MAAM,EAAE;AACnBH,MAAAA,QAAQ,CAAC,CAAC,CAAC,GAAGE,QAAQ,EAAE,MAAM;AAC5BF,QAAAA,QAAQ,GAAG,EAAE,CAAA;AAC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AAO,CAACS,IAAI,CAACQ,MAAM,EAAE,GAAG,CAAC,EAAEC,QAAQ,CAAC,EAAE,CAAC,CAACf,SAAS,CAAC,CAAC,CAAC,CAAA;AACtD;;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"route.js","sources":["../../src/route.ts"],"sourcesContent":["import { ParsePathParams } from './link'\nimport { AnyRouter, Router, RouteMatch, RegisteredRouter } from './router'\nimport { IsAny, NoInfer, PickRequired, UnionToIntersection } from './utils'\nimport invariant from 'tiny-invariant'\nimport { joinPaths, trimPath } from './path'\n\nexport const rootRouteId = '__root__' as const\nexport type RootRouteId = typeof rootRouteId\nexport type AnyPathParams = {}\nexport type AnySearchSchema = {}\nexport type AnyContext = {}\nexport interface RouteMeta {}\nexport interface RouteContext {}\nexport interface RegisterRouteComponent<TProps> {\n // RouteComponent: unknown // This is registered by the framework\n}\nexport interface RegisterRouteErrorComponent<TProps> {\n // RouteErrorComponent: unknown // This is registered by the framework\n}\n\nexport type RegisteredRouteComponent<TProps> =\n RegisterRouteComponent<TProps> extends {\n RouteComponent: infer T\n }\n ? T\n : (props: TProps) => unknown\n\nexport type RegisteredRouteErrorComponent<TProps> =\n RegisterRouteErrorComponent<TProps> extends {\n RouteErrorComponent: infer T\n }\n ? T\n : (props: TProps) => unknown\n\nexport type PreloadableObj = { preload?: () => Promise<void> }\n\nexport type RoutePathOptions<TCustomId, TPath> =\n | {\n path: TPath\n }\n | {\n id: TCustomId\n }\n\nexport type RoutePathOptionsIntersection<TCustomId, TPath> =\n UnionToIntersection<RoutePathOptions<TCustomId, TPath>>\n\nexport type MetaOptions = keyof PickRequired<RouteMeta> extends never\n ? {\n meta?: RouteMeta\n }\n : {\n meta: RouteMeta\n }\n\nexport type AnyRouteProps = RouteProps<any, any, any, any, any>\nexport type ComponentPropsFromRoute<TRoute> = TRoute extends Route<\n infer TParentRoute,\n infer TPath,\n infer TFullPath,\n infer TCustomId,\n infer TId,\n infer TLoader,\n infer TSearchSchema,\n infer TFullSearchSchema,\n infer TParams,\n infer TAllParams,\n infer TParentContext,\n infer TAllParentContext,\n infer TRouteContext,\n infer TContext,\n infer TRouterContext,\n infer TChildren,\n infer TRouteTree\n>\n ? RouteProps<TLoader, TFullSearchSchema, TAllParams, TRouteContext, TContext>\n : never\n\nexport type ComponentFromRoute<TRoute> = RegisteredRouteComponent<\n ComponentPropsFromRoute<TRoute>\n>\n\nexport type RouteLoaderFromRoute<TRoute extends AnyRoute> = LoaderFn<\n TRoute['types']['loader'],\n TRoute['types']['searchSchema'],\n TRoute['types']['fullSearchSchema'],\n TRoute['types']['allParams'],\n TRoute['types']['routeContext'],\n TRoute['types']['context']\n>\n\nexport type RouteProps<\n TLoader extends any = unknown,\n TFullSearchSchema extends AnySearchSchema = AnySearchSchema,\n TAllParams extends AnyPathParams = AnyPathParams,\n TRouteContext extends AnyContext = AnyContext,\n TContext extends AnyContext = AnyContext,\n> = {\n useMatch: () => RouteMatch<any, any>\n useLoader: () => UseLoaderResult<TLoader>\n useSearch: <\n TStrict extends boolean = true,\n TSearch = TFullSearchSchema,\n TSelected = TSearch,\n >(opts?: {\n strict?: TStrict\n select?: (search: TSearch) => TSelected\n }) => TStrict extends true ? TSelected : TSelected | undefined\n useParams: <\n TDefaultSelected = TAllParams,\n TSelected = TDefaultSelected,\n >(opts?: {\n select?: (params: TDefaultSelected) => TSelected\n }) => TSelected\n useContext: <\n TDefaultSelected = TContext,\n TSelected = TDefaultSelected,\n >(opts?: {\n select?: (context: TDefaultSelected) => TSelected\n }) => TSelected\n useRouteContext: <\n TDefaultSelected = TRouteContext,\n TSelected = TDefaultSelected,\n >(opts?: {\n select?: (context: TDefaultSelected) => TSelected\n }) => TSelected\n}\n\nexport type RouteOptions<\n TParentRoute extends AnyRoute = AnyRoute,\n TCustomId extends string = string,\n TPath extends string = string,\n TLoader = unknown,\n TParentSearchSchema extends AnySearchSchema = {},\n TSearchSchema extends AnySearchSchema = {},\n TFullSearchSchema extends AnySearchSchema = TSearchSchema,\n TParams extends AnyPathParams = AnyPathParams,\n TAllParams extends AnyPathParams = TParams,\n TParentContext extends AnyContext = AnyContext,\n TAllParentContext extends AnyContext = AnyContext,\n TRouteContext extends RouteContext = RouteContext,\n TAllContext extends AnyContext = AnyContext,\n> = BaseRouteOptions<\n TParentRoute,\n TCustomId,\n TPath,\n TLoader,\n TParentSearchSchema,\n TSearchSchema,\n TFullSearchSchema,\n TParams,\n TAllParams,\n TParentContext,\n TAllParentContext,\n TRouteContext,\n TAllContext\n> &\n UpdatableRouteOptions<\n TLoader,\n TSearchSchema,\n TFullSearchSchema,\n TAllParams,\n TRouteContext,\n TAllContext\n >\n\nexport type ParamsFallback<\n TPath extends string,\n TParams,\n> = unknown extends TParams ? Record<ParsePathParams<TPath>, string> : TParams\n\ntype Prefix<T extends string, U extends string> = U extends `${T}${infer _}`\n ? U\n : never\n\nexport type BaseRouteOptions<\n TParentRoute extends AnyRoute = AnyRoute,\n TCustomId extends string = string,\n TPath extends string = string,\n TLoader = unknown,\n TParentSearchSchema extends AnySearchSchema = {},\n TSearchSchema extends AnySearchSchema = {},\n TFullSearchSchema extends AnySearchSchema = TSearchSchema,\n TParams extends AnyPathParams = {},\n TAllParams = ParamsFallback<TPath, TParams>,\n TParentContext extends AnyContext = AnyContext,\n TAllParentContext extends AnyContext = AnyContext,\n TRouteContext extends RouteContext = RouteContext,\n TAllContext extends AnyContext = AnyContext,\n> = RoutePathOptions<TCustomId, TPath> & {\n layoutLimit?: string\n getParentRoute: () => TParentRoute\n validateSearch?: SearchSchemaValidator<TSearchSchema>\n loader?: LoaderFn<\n TLoader,\n TSearchSchema,\n TFullSearchSchema,\n TAllParams,\n NoInfer<TRouteContext>,\n TAllContext\n >\n} & ([TLoader] extends [never]\n ? {\n loader: 'Loaders must return a type other than never. If you are throwing a redirect() and not returning anything, return a redirect() instead.'\n }\n : {}) &\n (\n | {\n // Both or none\n parseParams?: (\n rawParams: IsAny<TPath, any, Record<ParsePathParams<TPath>, string>>,\n ) => TParams extends Record<ParsePathParams<TPath>, any>\n ? TParams\n : 'parseParams must return an object'\n stringifyParams?: (\n params: NoInfer<ParamsFallback<TPath, TParams>>,\n ) => Record<ParsePathParams<TPath>, string>\n }\n | {\n stringifyParams?: never\n parseParams?: never\n }\n ) &\n (keyof PickRequired<RouteContext> extends never\n ? {\n getContext?: GetContextFn<\n TParentRoute,\n TAllParams,\n TFullSearchSchema,\n TParentContext,\n TAllParentContext,\n TRouteContext\n >\n }\n : {\n getContext: GetContextFn<\n TParentRoute,\n TAllParams,\n TFullSearchSchema,\n TParentContext,\n TAllParentContext,\n TRouteContext\n >\n })\n\ntype GetContextFn<\n TParentRoute,\n TAllParams,\n TFullSearchSchema,\n TParentContext,\n TAllParentContext,\n TRouteContext,\n> = (\n opts: {\n params: TAllParams\n search: TFullSearchSchema\n } & (TParentRoute extends undefined\n ? {\n context?: TAllParentContext\n parentContext?: TParentContext\n }\n : {\n context: TAllParentContext\n parentContext: TParentContext\n }),\n) => TRouteContext\n\nexport type UpdatableRouteOptions<\n TLoader,\n TSearchSchema extends AnySearchSchema,\n TFullSearchSchema extends AnySearchSchema,\n TAllParams extends AnyPathParams,\n TRouteContext extends AnyContext,\n TContext extends AnyContext,\n> = MetaOptions & {\n key?: null | false | GetKeyFn<TFullSearchSchema, TAllParams>\n // If true, this route will be matched as case-sensitive\n caseSensitive?: boolean\n // If true, this route will be forcefully wrapped in a suspense boundary\n wrapInSuspense?: boolean\n // The content to be rendered when the route is matched. If no component is provided, defaults to `<Outlet />`\n component?: RegisteredRouteComponent<\n RouteProps<TLoader, TFullSearchSchema, TAllParams, TRouteContext, TContext>\n >\n // The content to be rendered when the route encounters an error\n errorComponent?: RegisteredRouteErrorComponent<\n { error: unknown } & Partial<\n RouteProps<\n TLoader,\n TFullSearchSchema,\n TAllParams,\n TRouteContext,\n TContext\n >\n >\n > //\n // If supported by your framework, the content to be rendered as the fallback content until the route is ready to render\n pendingComponent?: RegisteredRouteComponent<\n RouteProps<TLoader, TFullSearchSchema, TAllParams, TRouteContext, TContext>\n >\n // Filter functions that can manipulate search params *before* they are passed to links and navigate\n // calls that match this route.\n preSearchFilters?: SearchFilter<TFullSearchSchema>[]\n // Filter functions that can manipulate search params *after* they are passed to links and navigate\n // calls that match this route.\n postSearchFilters?: SearchFilter<TFullSearchSchema>[]\n // If set, preload matches of this route will be considered fresh for this many milliseconds.\n preloadMaxAge?: number\n // If set, a match of this route will be considered fresh for this many milliseconds.\n maxAge?: number\n // If set, a match of this route that becomes inactive (or unused) will be garbage collected after this many milliseconds\n gcMaxAge?: number\n // This async function is called before a route is loaded.\n // If an error is thrown here, the route's loader will not be called.\n // If thrown during a navigation, the navigation will be cancelled and the error will be passed to the `onLoadError` function.\n // If thrown during a preload event, the error will be logged to the console.\n beforeLoad?: (\n opts: LoaderContext<\n TSearchSchema,\n TFullSearchSchema,\n TAllParams,\n NoInfer<TRouteContext>,\n TContext\n >,\n ) => Promise<void> | void\n // This function will be called if the route's loader throws an error **during an attempted navigation**.\n // If you want to redirect due to an error, call `router.navigate()` from within this function.\n onBeforeLoadError?: (err: any) => void\n // This function will be called if the route's validateSearch option throws an error **during an attempted validation**.\n // If you want to redirect due to an error, call `router.navigate()` from within this function.\n // If you want to display the errorComponent, rethrow the error\n onValidateSearchError?: (err: any) => void\n onParseParamsError?: (err: any) => void\n onLoadError?: (err: any) => void\n onError?: (err: any) => void\n // This function is called\n // when moving from an inactive state to an active one. Likewise, when moving from\n // an active to an inactive state, the return function (if provided) is called.\n onLoaded?: (matchContext: {\n params: TAllParams\n search: TFullSearchSchema\n }) =>\n | void\n | undefined\n | ((match: { params: TAllParams; search: TFullSearchSchema }) => void)\n // This function is called when the route remains active from one transition to the next.\n onTransition?: (match: {\n params: TAllParams\n search: TFullSearchSchema\n }) => void\n}\n\nexport type ParseParamsOption<TPath extends string, TParams> = ParseParamsFn<\n TPath,\n TParams\n>\n\nexport type ParseParamsFn<TPath extends string, TParams> = (\n rawParams: IsAny<TPath, any, Record<ParsePathParams<TPath>, string>>,\n) => TParams extends Record<ParsePathParams<TPath>, any>\n ? TParams\n : 'parseParams must return an object'\n\nexport type ParseParamsObj<TPath extends string, TParams> = {\n parse?: ParseParamsFn<TPath, TParams>\n}\n\n// The parse type here allows a zod schema to be passed directly to the validator\nexport type SearchSchemaValidator<TReturn> =\n | SearchSchemaValidatorObj<TReturn>\n | SearchSchemaValidatorFn<TReturn>\n\nexport type SearchSchemaValidatorObj<TReturn> = {\n parse?: SearchSchemaValidatorFn<TReturn>\n}\n\nexport type SearchSchemaValidatorFn<TReturn> = (\n searchObj: Record<string, unknown>,\n) => TReturn\n\nexport type DefinedPathParamWarning =\n 'Path params cannot be redefined by child routes!'\n\nexport type ParentParams<TParentParams> = AnyPathParams extends TParentParams\n ? {}\n : {\n [Key in keyof TParentParams]?: DefinedPathParamWarning\n }\n\nexport type LoaderFn<\n TLoader = unknown,\n TSearchSchema extends AnySearchSchema = {},\n TFullSearchSchema extends AnySearchSchema = {},\n TAllParams = {},\n TContext extends AnyContext = AnyContext,\n TAllContext extends AnyContext = AnyContext,\n> = (\n match: LoaderContext<\n TSearchSchema,\n TFullSearchSchema,\n TAllParams,\n TContext,\n TAllContext\n > & {\n parentMatchPromise?: Promise<void>\n },\n) => Promise<TLoader> | TLoader\n\nexport type GetKeyFn<\n TFullSearchSchema extends AnySearchSchema = {},\n TAllParams = {},\n> = (loaderContext: { params: TAllParams; search: TFullSearchSchema }) => any\n\nexport interface LoaderContext<\n TSearchSchema extends AnySearchSchema = {},\n TFullSearchSchema extends AnySearchSchema = {},\n TAllParams = {},\n TContext extends AnyContext = AnyContext,\n TAllContext extends AnyContext = AnyContext,\n> {\n params: TAllParams\n routeSearch: TSearchSchema\n search: TFullSearchSchema\n abortController: AbortController\n preload: boolean\n routeContext: TContext\n context: TAllContext\n}\n\nexport type UnloaderFn<TPath extends string> = (\n routeMatch: RouteMatch<any, Route>,\n) => void\n\nexport type SearchFilter<T, U = T> = (prev: T) => U\n\nexport type ResolveId<\n TParentRoute,\n TCustomId extends string,\n TPath extends string,\n> = TParentRoute extends { id: infer TParentId extends string }\n ? RoutePrefix<TParentId, string extends TCustomId ? TPath : TCustomId>\n : RootRouteId\n\nexport type InferFullSearchSchema<TRoute> = TRoute extends {\n isRoot: true\n types: {\n searchSchema: infer TSearchSchema\n }\n}\n ? TSearchSchema\n : TRoute extends {\n types: {\n fullSearchSchema: infer TFullSearchSchema\n }\n }\n ? TFullSearchSchema\n : {}\n\nexport type ResolveFullSearchSchema<TParentRoute, TSearchSchema> =\n InferFullSearchSchema<TParentRoute> & TSearchSchema\n\nexport interface AnyRoute\n extends Route<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n > {}\n\nexport type MergeParamsFromParent<T, U> = IsAny<T, U, T & U>\n\nexport type UseLoaderResult<T> = T extends Record<PropertyKey, infer U>\n ? {\n [K in keyof T]: UseLoaderResultPromise<T[K]>\n }\n : UseLoaderResultPromise<T>\n\nexport type UseLoaderResultPromise<T> = T extends Promise<infer U>\n ? StreamedPromise<U>\n : T\n\nexport type StreamedPromise<T> = {\n promise: Promise<T>\n status: 'resolved' | 'pending'\n data: T\n resolve: (value: T) => void\n}\n\nexport type RouteConstraints = {\n TParentRoute: AnyRoute\n TPath: string\n TFullPath: string\n TCustomId: string\n TId: string\n TSearchSchema: AnySearchSchema\n TFullSearchSchema: AnySearchSchema\n TParams: Record<string, any>\n TAllParams: Record<string, any>\n TParentContext: AnyContext\n TAllParentContext: AnyContext\n TRouteContext: RouteContext\n TAllContext: AnyContext\n TRouterContext: AnyContext\n TChildren: unknown\n TRouteTree: AnyRoute\n}\n\nexport class Route<\n TParentRoute extends RouteConstraints['TParentRoute'] = AnyRoute,\n TPath extends RouteConstraints['TPath'] = '/',\n TFullPath extends RouteConstraints['TFullPath'] = ResolveFullPath<\n TParentRoute,\n TPath\n >,\n TCustomId extends RouteConstraints['TCustomId'] = string,\n TId extends RouteConstraints['TId'] = ResolveId<\n TParentRoute,\n TCustomId,\n TPath\n >,\n TLoader = unknown,\n TSearchSchema extends RouteConstraints['TSearchSchema'] = {},\n TFullSearchSchema extends RouteConstraints['TFullSearchSchema'] = ResolveFullSearchSchema<\n TParentRoute,\n TSearchSchema\n >,\n TParams extends RouteConstraints['TParams'] = Record<\n ParsePathParams<TPath>,\n string\n >,\n TAllParams extends RouteConstraints['TAllParams'] = MergeParamsFromParent<\n TParentRoute['types']['allParams'],\n TParams\n >,\n TParentContext extends RouteConstraints['TParentContext'] = TParentRoute['types']['routeContext'],\n TAllParentContext extends RouteConstraints['TAllParentContext'] = TParentRoute['types']['context'],\n TRouteContext extends RouteConstraints['TRouteContext'] = RouteContext,\n TAllContext extends RouteConstraints['TAllContext'] = MergeParamsFromParent<\n TParentRoute['types']['context'],\n TRouteContext\n >,\n TRouterContext extends RouteConstraints['TRouterContext'] = AnyContext,\n TChildren extends RouteConstraints['TChildren'] = unknown,\n TRouteTree extends RouteConstraints['TRouteTree'] = AnyRoute,\n> {\n types!: {\n parentRoute: TParentRoute\n path: TPath\n to: TrimPathRight<TFullPath>\n fullPath: TFullPath\n customId: TCustomId\n id: TId\n loader: TLoader\n searchSchema: TSearchSchema\n fullSearchSchema: TFullSearchSchema\n params: TParams\n allParams: TAllParams\n parentContext: TParentContext\n allParentContext: TAllParentContext\n routeContext: TRouteContext\n context: TAllContext\n children: TChildren\n routeTree: TRouteTree\n routerContext: TRouterContext\n }\n isRoot: TParentRoute extends Route<any> ? true : false\n options: RouteOptions<\n TParentRoute,\n TCustomId,\n TPath,\n TLoader,\n InferFullSearchSchema<TParentRoute>,\n TSearchSchema,\n TFullSearchSchema,\n TParams,\n TAllParams,\n TParentContext,\n TAllParentContext,\n TRouteContext,\n TAllContext\n > &\n UpdatableRouteOptions<\n TLoader,\n TSearchSchema,\n TFullSearchSchema,\n TAllParams,\n TRouteContext,\n TAllContext\n >\n\n // Set up in this.init()\n parentRoute!: TParentRoute\n id!: TId\n // customId!: TCustomId\n path!: TPath\n fullPath!: TFullPath\n to!: TrimPathRight<TFullPath>\n\n // Optional\n children?: TChildren\n originalIndex?: number\n router?: AnyRouter\n rank!: number\n\n constructor(\n options: RouteOptions<\n TParentRoute,\n TCustomId,\n TPath,\n TLoader,\n InferFullSearchSchema<TParentRoute>,\n TSearchSchema,\n TFullSearchSchema,\n TParams,\n TAllParams,\n TParentContext,\n TAllParentContext,\n TRouteContext,\n TAllContext\n > &\n UpdatableRouteOptions<\n TLoader,\n TSearchSchema,\n TFullSearchSchema,\n TAllParams,\n TRouteContext,\n TAllContext\n >,\n ) {\n this.options = (options as any) || {}\n this.isRoot = !options?.getParentRoute as any\n Route.__onInit(this as any)\n }\n\n init = (opts: { originalIndex: number; router: AnyRouter }) => {\n this.originalIndex = opts.originalIndex\n this.router = opts.router\n\n const options = this.options as RouteOptions<\n TParentRoute,\n TCustomId,\n TPath,\n InferFullSearchSchema<TParentRoute>,\n TSearchSchema,\n TParams\n > &\n RoutePathOptionsIntersection<TCustomId, TPath>\n\n const isRoot = !options?.path && !options?.id\n\n this.parentRoute = this.options?.getParentRoute?.()\n\n if (isRoot) {\n this.path = rootRouteId as TPath\n } else {\n invariant(\n this.parentRoute,\n `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a Route instance.`,\n )\n }\n\n let path: undefined | string = isRoot ? rootRouteId : options.path\n\n // If the path is anything other than an index path, trim it up\n if (path && path !== '/') {\n path = trimPath(path)\n }\n\n const customId = options?.id || path\n\n // Strip the parentId prefix from the first level of children\n let id = isRoot\n ? rootRouteId\n : joinPaths([\n (this.parentRoute.id as any) === rootRouteId\n ? ''\n : this.parentRoute.id,\n customId,\n ])\n\n if (path === rootRouteId) {\n path = '/'\n }\n\n if (id !== rootRouteId) {\n id = joinPaths(['/', id])\n }\n\n const fullPath =\n id === rootRouteId ? '/' : joinPaths([this.parentRoute.fullPath, path])\n\n this.path = path as TPath\n this.id = id as TId\n // this.customId = customId as TCustomId\n this.fullPath = fullPath as TFullPath\n this.to = fullPath as TrimPathRight<TFullPath>\n }\n\n addChildren = <TNewChildren extends AnyRoute[]>(\n children: TNewChildren,\n ): Route<\n TParentRoute,\n TPath,\n TFullPath,\n TCustomId,\n TId,\n TLoader,\n TSearchSchema,\n TFullSearchSchema,\n TParams,\n TAllParams,\n TParentContext,\n TAllParentContext,\n TRouteContext,\n TAllContext,\n TRouterContext,\n TNewChildren,\n TRouteTree\n > => {\n this.children = children as any\n return this as any\n }\n\n update = (\n options: UpdatableRouteOptions<\n TLoader,\n TSearchSchema,\n TFullSearchSchema,\n TAllParams,\n TRouteContext,\n TAllContext\n >,\n ) => {\n Object.assign(this.options, options)\n return this\n }\n\n static __onInit = (route: typeof this) => {\n // This is a dummy static method that should get\n // replaced by a framework specific implementation if necessary\n }\n}\n\nexport type AnyRootRoute = RootRoute<any, any, any, any>\n\nexport class RouterContext<TRouterContext extends {}> {\n constructor() {}\n\n createRootRoute = <\n TLoader = unknown,\n TSearchSchema extends AnySearchSchema = {},\n TRouteContext extends RouteContext = RouteContext,\n >(\n options?: Omit<\n RouteOptions<\n AnyRoute,\n RootRouteId,\n '',\n TLoader,\n TSearchSchema,\n TSearchSchema,\n TSearchSchema,\n {},\n {},\n TRouterContext,\n TRouterContext,\n TRouteContext,\n MergeParamsFromParent<TRouterContext, TRouteContext>\n >,\n | 'path'\n | 'id'\n | 'getParentRoute'\n | 'caseSensitive'\n | 'parseParams'\n | 'stringifyParams'\n >,\n ): RootRoute<TLoader, TSearchSchema, TRouteContext, TRouterContext> => {\n return new RootRoute(options) as any\n }\n}\n\nexport class RootRoute<\n TLoader = unknown,\n TSearchSchema extends AnySearchSchema = {},\n TRouteContext extends RouteContext = RouteContext,\n TRouterContext extends {} = {},\n> extends Route<\n any,\n '/',\n '/',\n string,\n RootRouteId,\n TLoader,\n TSearchSchema,\n TSearchSchema,\n {},\n {},\n TRouterContext,\n TRouterContext,\n TRouteContext,\n MergeParamsFromParent<TRouterContext, TRouteContext>,\n TRouterContext,\n any,\n any\n> {\n constructor(\n options?: Omit<\n RouteOptions<\n AnyRoute,\n RootRouteId,\n '',\n TLoader,\n TSearchSchema,\n TSearchSchema,\n TSearchSchema,\n {},\n {},\n TRouterContext,\n TRouterContext,\n TRouteContext,\n MergeParamsFromParent<TRouterContext, TRouteContext>\n >,\n | 'path'\n | 'id'\n | 'getParentRoute'\n | 'caseSensitive'\n | 'parseParams'\n | 'stringifyParams'\n >,\n ) {\n super(options as any)\n }\n}\n\nexport type ResolveFullPath<\n TParentRoute extends AnyRoute,\n TPath extends string,\n TPrefixed = RoutePrefix<TParentRoute['fullPath'], TPath>,\n> = TPrefixed extends RootRouteId ? '/' : TPrefixed\n\ntype RoutePrefix<\n TPrefix extends string,\n TPath extends string,\n> = string extends TPath\n ? RootRouteId\n : TPath extends string\n ? TPrefix extends RootRouteId\n ? TPath extends '/'\n ? '/'\n : `/${TrimPath<TPath>}`\n : `${TPrefix}/${TPath}` extends '/'\n ? '/'\n : `/${TrimPathLeft<`${TrimPathRight<TPrefix>}/${TrimPath<TPath>}`>}`\n : never\n\nexport type TrimPath<T extends string> = '' extends T\n ? ''\n : TrimPathRight<TrimPathLeft<T>>\n\nexport type TrimPathLeft<T extends string> =\n T extends `${RootRouteId}/${infer U}`\n ? TrimPathLeft<U>\n : T extends `/${infer U}`\n ? TrimPathLeft<U>\n : T\nexport type TrimPathRight<T extends string> = T extends '/'\n ? '/'\n : T extends `${infer U}/`\n ? TrimPathRight<U>\n : T\n"],"names":["rootRouteId","Route","constructor","options","isRoot","getParentRoute","__onInit","init","opts","originalIndex","router","path","id","parentRoute","invariant","trimPath","customId","joinPaths","fullPath","to","addChildren","children","update","Object","assign","route","RouterContext","createRootRoute","RootRoute"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAMO,MAAMA,WAAW,GAAG,WAAmB;;AAyW9C;;AAyJO,MAAMC,KAAK,CAqChB;AA8CA;;AAGA;;AAKA;;EAMAC,WAAWA,CACTC,OAsBG,EACH;AACA,IAAA,I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route.js","sources":["../../src/route.ts"],"sourcesContent":["import { ParsePathParams } from './link'\nimport { AnyRouter, Router, RouteMatch, RegisteredRouter } from './router'\nimport { IsAny, NoInfer, PickRequired, UnionToIntersection } from './utils'\nimport invariant from 'tiny-invariant'\nimport { joinPaths, trimPath } from './path'\n\nexport const rootRouteId = '__root__' as const\nexport type RootRouteId = typeof rootRouteId\nexport type AnyPathParams = {}\nexport type AnySearchSchema = {}\nexport type AnyContext = {}\nexport interface RouteMeta {}\nexport interface RouteContext {}\nexport interface RegisterRouteComponent<TProps> {\n // RouteComponent: unknown // This is registered by the framework\n}\nexport interface RegisterRouteErrorComponent<TProps> {\n // RouteErrorComponent: unknown // This is registered by the framework\n}\n\nexport type RegisteredRouteComponent<TProps> =\n RegisterRouteComponent<TProps> extends {\n RouteComponent: infer T\n }\n ? T\n : (props: TProps) => unknown\n\nexport type RegisteredRouteErrorComponent<TProps> =\n RegisterRouteErrorComponent<TProps> extends {\n RouteErrorComponent: infer T\n }\n ? T\n : (props: TProps) => unknown\n\nexport type PreloadableObj = { preload?: () => Promise<void> }\n\nexport type RoutePathOptions<TCustomId, TPath> =\n | {\n path: TPath\n }\n | {\n id: TCustomId\n }\n\nexport type RoutePathOptionsIntersection<TCustomId, TPath> =\n UnionToIntersection<RoutePathOptions<TCustomId, TPath>>\n\nexport type MetaOptions = keyof PickRequired<RouteMeta> extends never\n ? {\n meta?: RouteMeta\n }\n : {\n meta: RouteMeta\n }\n\nexport type AnyRouteProps = RouteProps<any, any, any, any, any>\nexport type ComponentPropsFromRoute<TRoute> = TRoute extends Route<\n infer TParentRoute,\n infer TPath,\n infer TFullPath,\n infer TCustomId,\n infer TId,\n infer TLoader,\n infer TSearchSchema,\n infer TFullSearchSchema,\n infer TParams,\n infer TAllParams,\n infer TParentContext,\n infer TAllParentContext,\n infer TRouteContext,\n infer TContext,\n infer TRouterContext,\n infer TChildren,\n infer TRouteTree\n>\n ? RouteProps<TLoader, TFullSearchSchema, TAllParams, TRouteContext, TContext>\n : never\n\nexport type ComponentFromRoute<TRoute> = RegisteredRouteComponent<\n ComponentPropsFromRoute<TRoute>\n>\n\nexport type RouteLoaderFromRoute<TRoute extends AnyRoute> = LoaderFn<\n TRoute['types']['loader'],\n TRoute['types']['searchSchema'],\n TRoute['types']['fullSearchSchema'],\n TRoute['types']['allParams'],\n TRoute['types']['routeContext'],\n TRoute['types']['context']\n>\n\nexport type RouteProps<\n TLoader extends any = unknown,\n TFullSearchSchema extends AnySearchSchema = AnySearchSchema,\n TAllParams extends AnyPathParams = AnyPathParams,\n TRouteContext extends AnyContext = AnyContext,\n TContext extends AnyContext = AnyContext,\n> = {\n useMatch: () => RouteMatch<any, any>\n useLoader: () => UseLoaderResult<TLoader>\n useSearch: <\n TStrict extends boolean = true,\n TSearch = TFullSearchSchema,\n TSelected = TSearch,\n >(opts?: {\n strict?: TStrict\n select?: (search: TSearch) => TSelected\n }) => TStrict extends true ? TSelected : TSelected | undefined\n useParams: <\n TDefaultSelected = TAllParams,\n TSelected = TDefaultSelected,\n >(opts?: {\n select?: (params: TDefaultSelected) => TSelected\n }) => TSelected\n useContext: <\n TDefaultSelected = TContext,\n TSelected = TDefaultSelected,\n >(opts?: {\n select?: (context: TDefaultSelected) => TSelected\n }) => TSelected\n useRouteContext: <\n TDefaultSelected = TRouteContext,\n TSelected = TDefaultSelected,\n >(opts?: {\n select?: (context: TDefaultSelected) => TSelected\n }) => TSelected\n}\n\nexport type RouteOptions<\n TParentRoute extends AnyRoute = AnyRoute,\n TCustomId extends string = string,\n TPath extends string = string,\n TLoader = unknown,\n TParentSearchSchema extends AnySearchSchema = {},\n TSearchSchema extends AnySearchSchema = {},\n TFullSearchSchema extends AnySearchSchema = TSearchSchema,\n TParams extends AnyPathParams = AnyPathParams,\n TAllParams extends AnyPathParams = TParams,\n TParentContext extends AnyContext = AnyContext,\n TAllParentContext extends AnyContext = AnyContext,\n TRouteContext extends RouteContext = RouteContext,\n TAllContext extends AnyContext = AnyContext,\n> = BaseRouteOptions<\n TParentRoute,\n TCustomId,\n TPath,\n TLoader,\n TParentSearchSchema,\n TSearchSchema,\n TFullSearchSchema,\n TParams,\n TAllParams,\n TParentContext,\n TAllParentContext,\n TRouteContext,\n TAllContext\n> &\n UpdatableRouteOptions<\n TLoader,\n TSearchSchema,\n TFullSearchSchema,\n TAllParams,\n TRouteContext,\n TAllContext\n >\n\nexport type ParamsFallback<\n TPath extends string,\n TParams,\n> = unknown extends TParams ? Record<ParsePathParams<TPath>, string> : TParams\n\ntype Prefix<T extends string, U extends string> = U extends `${T}${infer _}`\n ? U\n : never\n\nexport type BaseRouteOptions<\n TParentRoute extends AnyRoute = AnyRoute,\n TCustomId extends string = string,\n TPath extends string = string,\n TLoader = unknown,\n TParentSearchSchema extends AnySearchSchema = {},\n TSearchSchema extends AnySearchSchema = {},\n TFullSearchSchema extends AnySearchSchema = TSearchSchema,\n TParams extends AnyPathParams = {},\n TAllParams = ParamsFallback<TPath, TParams>,\n TParentContext extends AnyContext = AnyContext,\n TAllParentContext extends AnyContext = AnyContext,\n TRouteContext extends RouteContext = RouteContext,\n TAllContext extends AnyContext = AnyContext,\n> = RoutePathOptions<TCustomId, TPath> & {\n layoutLimit?: string\n getParentRoute: () => TParentRoute\n validateSearch?: SearchSchemaValidator<TSearchSchema>\n loader?: LoaderFn<\n TLoader,\n TSearchSchema,\n TFullSearchSchema,\n TAllParams,\n NoInfer<TRouteContext>,\n TAllContext\n >\n} & ([TLoader] extends [never]\n ? {\n loader: 'Loaders must return a type other than never. If you are throwing a redirect() and not returning anything, return a redirect() instead.'\n }\n : {}) &\n (\n | {\n // Both or none\n parseParams?: (\n rawParams: IsAny<TPath, any, Record<ParsePathParams<TPath>, string>>,\n ) => TParams extends Record<ParsePathParams<TPath>, any>\n ? TParams\n : 'parseParams must return an object'\n stringifyParams?: (\n params: NoInfer<ParamsFallback<TPath, TParams>>,\n ) => Record<ParsePathParams<TPath>, string>\n }\n | {\n stringifyParams?: never\n parseParams?: never\n }\n ) &\n (keyof PickRequired<RouteContext> extends never\n ? {\n getContext?: GetContextFn<\n TParentRoute,\n TAllParams,\n TFullSearchSchema,\n TParentContext,\n TAllParentContext,\n TRouteContext\n >\n }\n : {\n getContext: GetContextFn<\n TParentRoute,\n TAllParams,\n TFullSearchSchema,\n TParentContext,\n TAllParentContext,\n TRouteContext\n >\n })\n\ntype GetContextFn<\n TParentRoute,\n TAllParams,\n TFullSearchSchema,\n TParentContext,\n TAllParentContext,\n TRouteContext,\n> = (\n opts: {\n params: TAllParams\n search: TFullSearchSchema\n } & (TParentRoute extends undefined\n ? {\n context?: TAllParentContext\n parentContext?: TParentContext\n }\n : {\n context: TAllParentContext\n parentContext: TParentContext\n }),\n) => TRouteContext\n\nexport type UpdatableRouteOptions<\n TLoader,\n TSearchSchema extends AnySearchSchema,\n TFullSearchSchema extends AnySearchSchema,\n TAllParams extends AnyPathParams,\n TRouteContext extends AnyContext,\n TContext extends AnyContext,\n> = MetaOptions & {\n key?: null | false | GetKeyFn<TFullSearchSchema, TAllParams>\n // If true, this route will be matched as case-sensitive\n caseSensitive?: boolean\n // If true, this route will be forcefully wrapped in a suspense boundary\n wrapInSuspense?: boolean\n // The content to be rendered when the route is matched. If no component is provided, defaults to `<Outlet />`\n component?: RegisteredRouteComponent<\n RouteProps<TLoader, TFullSearchSchema, TAllParams, TRouteContext, TContext>\n >\n // The content to be rendered when the route encounters an error\n errorComponent?: RegisteredRouteErrorComponent<\n { error: unknown } & Partial<\n RouteProps<\n TLoader,\n TFullSearchSchema,\n TAllParams,\n TRouteContext,\n TContext\n >\n >\n > //\n // If supported by your framework, the content to be rendered as the fallback content until the route is ready to render\n pendingComponent?: RegisteredRouteComponent<\n RouteProps<TLoader, TFullSearchSchema, TAllParams, TRouteContext, TContext>\n >\n // Filter functions that can manipulate search params *before* they are passed to links and navigate\n // calls that match this route.\n preSearchFilters?: SearchFilter<TFullSearchSchema>[]\n // Filter functions that can manipulate search params *after* they are passed to links and navigate\n // calls that match this route.\n postSearchFilters?: SearchFilter<TFullSearchSchema>[]\n // If set, preload matches of this route will be considered fresh for this many milliseconds.\n preloadMaxAge?: number\n // If set, a match of this route will be considered fresh for this many milliseconds.\n maxAge?: number\n // If set, a match of this route that becomes inactive (or unused) will be garbage collected after this many milliseconds\n gcMaxAge?: number\n // This async function is called before a route is loaded.\n // If an error is thrown here, the route's loader will not be called.\n // If thrown during a navigation, the navigation will be cancelled and the error will be passed to the `onError` function.\n // If thrown during a preload event, the error will be logged to the console.\n beforeLoad?: (\n opts: LoaderContext<\n TSearchSchema,\n TFullSearchSchema,\n TAllParams,\n NoInfer<TRouteContext>,\n TContext\n >,\n ) => Promise<void> | void\n onError?: (err: any) => void\n // This function is called\n // when moving from an inactive state to an active one. Likewise, when moving from\n // an active to an inactive state, the return function (if provided) is called.\n onLoaded?: (matchContext: {\n params: TAllParams\n search: TFullSearchSchema\n }) =>\n | void\n | undefined\n | ((match: { params: TAllParams; search: TFullSearchSchema }) => void)\n // This function is called when the route remains active from one transition to the next.\n onTransition?: (match: {\n params: TAllParams\n search: TFullSearchSchema\n }) => void\n}\n\nexport type ParseParamsOption<TPath extends string, TParams> = ParseParamsFn<\n TPath,\n TParams\n>\n\nexport type ParseParamsFn<TPath extends string, TParams> = (\n rawParams: IsAny<TPath, any, Record<ParsePathParams<TPath>, string>>,\n) => TParams extends Record<ParsePathParams<TPath>, any>\n ? TParams\n : 'parseParams must return an object'\n\nexport type ParseParamsObj<TPath extends string, TParams> = {\n parse?: ParseParamsFn<TPath, TParams>\n}\n\n// The parse type here allows a zod schema to be passed directly to the validator\nexport type SearchSchemaValidator<TReturn> =\n | SearchSchemaValidatorObj<TReturn>\n | SearchSchemaValidatorFn<TReturn>\n\nexport type SearchSchemaValidatorObj<TReturn> = {\n parse?: SearchSchemaValidatorFn<TReturn>\n}\n\nexport type SearchSchemaValidatorFn<TReturn> = (\n searchObj: Record<string, unknown>,\n) => TReturn\n\nexport type DefinedPathParamWarning =\n 'Path params cannot be redefined by child routes!'\n\nexport type ParentParams<TParentParams> = AnyPathParams extends TParentParams\n ? {}\n : {\n [Key in keyof TParentParams]?: DefinedPathParamWarning\n }\n\nexport type LoaderFn<\n TLoader = unknown,\n TSearchSchema extends AnySearchSchema = {},\n TFullSearchSchema extends AnySearchSchema = {},\n TAllParams = {},\n TContext extends AnyContext = AnyContext,\n TAllContext extends AnyContext = AnyContext,\n> = (\n match: LoaderContext<\n TSearchSchema,\n TFullSearchSchema,\n TAllParams,\n TContext,\n TAllContext\n > & {\n parentMatchPromise?: Promise<void>\n },\n) => Promise<TLoader> | TLoader\n\nexport type GetKeyFn<\n TFullSearchSchema extends AnySearchSchema = {},\n TAllParams = {},\n> = (loaderContext: { params: TAllParams; search: TFullSearchSchema }) => any\n\nexport interface LoaderContext<\n TSearchSchema extends AnySearchSchema = {},\n TFullSearchSchema extends AnySearchSchema = {},\n TAllParams = {},\n TContext extends AnyContext = AnyContext,\n TAllContext extends AnyContext = AnyContext,\n> {\n params: TAllParams\n routeSearch: TSearchSchema\n search: TFullSearchSchema\n abortController: AbortController\n preload: boolean\n routeContext: TContext\n context: TAllContext\n}\n\nexport type UnloaderFn<TPath extends string> = (\n routeMatch: RouteMatch<any, Route>,\n) => void\n\nexport type SearchFilter<T, U = T> = (prev: T) => U\n\nexport type ResolveId<\n TParentRoute,\n TCustomId extends string,\n TPath extends string,\n> = TParentRoute extends { id: infer TParentId extends string }\n ? RoutePrefix<TParentId, string extends TCustomId ? TPath : TCustomId>\n : RootRouteId\n\nexport type InferFullSearchSchema<TRoute> = TRoute extends {\n isRoot: true\n types: {\n searchSchema: infer TSearchSchema\n }\n}\n ? TSearchSchema\n : TRoute extends {\n types: {\n fullSearchSchema: infer TFullSearchSchema\n }\n }\n ? TFullSearchSchema\n : {}\n\nexport type ResolveFullSearchSchema<TParentRoute, TSearchSchema> =\n InferFullSearchSchema<TParentRoute> & TSearchSchema\n\nexport interface AnyRoute\n extends Route<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n > {}\n\nexport type MergeParamsFromParent<T, U> = IsAny<T, U, T & U>\n\nexport type UseLoaderResult<T> = T extends Record<PropertyKey, infer U>\n ? {\n [K in keyof T]: UseLoaderResultPromise<T[K]>\n }\n : UseLoaderResultPromise<T>\n\nexport type UseLoaderResultPromise<T> = T extends Promise<infer U>\n ? StreamedPromise<U>\n : T\n\nexport type StreamedPromise<T> = {\n promise: Promise<T>\n status: 'resolved' | 'pending'\n data: T\n resolve: (value: T) => void\n}\n\nexport type RouteConstraints = {\n TParentRoute: AnyRoute\n TPath: string\n TFullPath: string\n TCustomId: string\n TId: string\n TSearchSchema: AnySearchSchema\n TFullSearchSchema: AnySearchSchema\n TParams: Record<string, any>\n TAllParams: Record<string, any>\n TParentContext: AnyContext\n TAllParentContext: AnyContext\n TRouteContext: RouteContext\n TAllContext: AnyContext\n TRouterContext: AnyContext\n TChildren: unknown\n TRouteTree: AnyRoute\n}\n\nexport class Route<\n TParentRoute extends RouteConstraints['TParentRoute'] = AnyRoute,\n TPath extends RouteConstraints['TPath'] = '/',\n TFullPath extends RouteConstraints['TFullPath'] = ResolveFullPath<\n TParentRoute,\n TPath\n >,\n TCustomId extends RouteConstraints['TCustomId'] = string,\n TId extends RouteConstraints['TId'] = ResolveId<\n TParentRoute,\n TCustomId,\n TPath\n >,\n TLoader = unknown,\n TSearchSchema extends RouteConstraints['TSearchSchema'] = {},\n TFullSearchSchema extends RouteConstraints['TFullSearchSchema'] = ResolveFullSearchSchema<\n TParentRoute,\n TSearchSchema\n >,\n TParams extends RouteConstraints['TParams'] = Record<\n ParsePathParams<TPath>,\n string\n >,\n TAllParams extends RouteConstraints['TAllParams'] = MergeParamsFromParent<\n TParentRoute['types']['allParams'],\n TParams\n >,\n TParentContext extends RouteConstraints['TParentContext'] = TParentRoute['types']['routeContext'],\n TAllParentContext extends RouteConstraints['TAllParentContext'] = TParentRoute['types']['context'],\n TRouteContext extends RouteConstraints['TRouteContext'] = RouteContext,\n TAllContext extends RouteConstraints['TAllContext'] = MergeParamsFromParent<\n TParentRoute['types']['context'],\n TRouteContext\n >,\n TRouterContext extends RouteConstraints['TRouterContext'] = AnyContext,\n TChildren extends RouteConstraints['TChildren'] = unknown,\n TRouteTree extends RouteConstraints['TRouteTree'] = AnyRoute,\n> {\n types!: {\n parentRoute: TParentRoute\n path: TPath\n to: TrimPathRight<TFullPath>\n fullPath: TFullPath\n customId: TCustomId\n id: TId\n loader: TLoader\n searchSchema: TSearchSchema\n fullSearchSchema: TFullSearchSchema\n params: TParams\n allParams: TAllParams\n parentContext: TParentContext\n allParentContext: TAllParentContext\n routeContext: TRouteContext\n context: TAllContext\n children: TChildren\n routeTree: TRouteTree\n routerContext: TRouterContext\n }\n isRoot: TParentRoute extends Route<any> ? true : false\n options: RouteOptions<\n TParentRoute,\n TCustomId,\n TPath,\n TLoader,\n InferFullSearchSchema<TParentRoute>,\n TSearchSchema,\n TFullSearchSchema,\n TParams,\n TAllParams,\n TParentContext,\n TAllParentContext,\n TRouteContext,\n TAllContext\n > &\n UpdatableRouteOptions<\n TLoader,\n TSearchSchema,\n TFullSearchSchema,\n TAllParams,\n TRouteContext,\n TAllContext\n >\n\n // Set up in this.init()\n parentRoute!: TParentRoute\n id!: TId\n // customId!: TCustomId\n path!: TPath\n fullPath!: TFullPath\n to!: TrimPathRight<TFullPath>\n\n // Optional\n children?: TChildren\n originalIndex?: number\n router?: AnyRouter\n rank!: number\n\n constructor(\n options: RouteOptions<\n TParentRoute,\n TCustomId,\n TPath,\n TLoader,\n InferFullSearchSchema<TParentRoute>,\n TSearchSchema,\n TFullSearchSchema,\n TParams,\n TAllParams,\n TParentContext,\n TAllParentContext,\n TRouteContext,\n TAllContext\n > &\n UpdatableRouteOptions<\n TLoader,\n TSearchSchema,\n TFullSearchSchema,\n TAllParams,\n TRouteContext,\n TAllContext\n >,\n ) {\n this.options = (options as any) || {}\n this.isRoot = !options?.getParentRoute as any\n Route.__onInit(this as any)\n }\n\n init = (opts: { originalIndex: number; router: AnyRouter }) => {\n this.originalIndex = opts.originalIndex\n this.router = opts.router\n\n const options = this.options as RouteOptions<\n TParentRoute,\n TCustomId,\n TPath,\n InferFullSearchSchema<TParentRoute>,\n TSearchSchema,\n TParams\n > &\n RoutePathOptionsIntersection<TCustomId, TPath>\n\n const isRoot = !options?.path && !options?.id\n\n this.parentRoute = this.options?.getParentRoute?.()\n\n if (isRoot) {\n this.path = rootRouteId as TPath\n } else {\n invariant(\n this.parentRoute,\n `Child Route instances must pass a 'getParentRoute: () => ParentRoute' option that returns a Route instance.`,\n )\n }\n\n let path: undefined | string = isRoot ? rootRouteId : options.path\n\n // If the path is anything other than an index path, trim it up\n if (path && path !== '/') {\n path = trimPath(path)\n }\n\n const customId = options?.id || path\n\n // Strip the parentId prefix from the first level of children\n let id = isRoot\n ? rootRouteId\n : joinPaths([\n (this.parentRoute.id as any) === rootRouteId\n ? ''\n : this.parentRoute.id,\n customId,\n ])\n\n if (path === rootRouteId) {\n path = '/'\n }\n\n if (id !== rootRouteId) {\n id = joinPaths(['/', id])\n }\n\n const fullPath =\n id === rootRouteId ? '/' : joinPaths([this.parentRoute.fullPath, path])\n\n this.path = path as TPath\n this.id = id as TId\n // this.customId = customId as TCustomId\n this.fullPath = fullPath as TFullPath\n this.to = fullPath as TrimPathRight<TFullPath>\n }\n\n addChildren = <TNewChildren extends AnyRoute[]>(\n children: TNewChildren,\n ): Route<\n TParentRoute,\n TPath,\n TFullPath,\n TCustomId,\n TId,\n TLoader,\n TSearchSchema,\n TFullSearchSchema,\n TParams,\n TAllParams,\n TParentContext,\n TAllParentContext,\n TRouteContext,\n TAllContext,\n TRouterContext,\n TNewChildren,\n TRouteTree\n > => {\n this.children = children as any\n return this as any\n }\n\n update = (\n options: UpdatableRouteOptions<\n TLoader,\n TSearchSchema,\n TFullSearchSchema,\n TAllParams,\n TRouteContext,\n TAllContext\n >,\n ) => {\n Object.assign(this.options, options)\n return this\n }\n\n static __onInit = (route: typeof this) => {\n // This is a dummy static method that should get\n // replaced by a framework specific implementation if necessary\n }\n}\n\nexport type AnyRootRoute = RootRoute<any, any, any, any>\n\nexport class RouterContext<TRouterContext extends {}> {\n constructor() {}\n\n createRootRoute = <\n TLoader = unknown,\n TSearchSchema extends AnySearchSchema = {},\n TRouteContext extends RouteContext = RouteContext,\n >(\n options?: Omit<\n RouteOptions<\n AnyRoute,\n RootRouteId,\n '',\n TLoader,\n TSearchSchema,\n TSearchSchema,\n TSearchSchema,\n {},\n {},\n TRouterContext,\n TRouterContext,\n TRouteContext,\n MergeParamsFromParent<TRouterContext, TRouteContext>\n >,\n | 'path'\n | 'id'\n | 'getParentRoute'\n | 'caseSensitive'\n | 'parseParams'\n | 'stringifyParams'\n >,\n ): RootRoute<TLoader, TSearchSchema, TRouteContext, TRouterContext> => {\n return new RootRoute(options) as any\n }\n}\n\nexport class RootRoute<\n TLoader = unknown,\n TSearchSchema extends AnySearchSchema = {},\n TRouteContext extends RouteContext = RouteContext,\n TRouterContext extends {} = {},\n> extends Route<\n any,\n '/',\n '/',\n string,\n RootRouteId,\n TLoader,\n TSearchSchema,\n TSearchSchema,\n {},\n {},\n TRouterContext,\n TRouterContext,\n TRouteContext,\n MergeParamsFromParent<TRouterContext, TRouteContext>,\n TRouterContext,\n any,\n any\n> {\n constructor(\n options?: Omit<\n RouteOptions<\n AnyRoute,\n RootRouteId,\n '',\n TLoader,\n TSearchSchema,\n TSearchSchema,\n TSearchSchema,\n {},\n {},\n TRouterContext,\n TRouterContext,\n TRouteContext,\n MergeParamsFromParent<TRouterContext, TRouteContext>\n >,\n | 'path'\n | 'id'\n | 'getParentRoute'\n | 'caseSensitive'\n | 'parseParams'\n | 'stringifyParams'\n >,\n ) {\n super(options as any)\n }\n}\n\nexport type ResolveFullPath<\n TParentRoute extends AnyRoute,\n TPath extends string,\n TPrefixed = RoutePrefix<TParentRoute['fullPath'], TPath>,\n> = TPrefixed extends RootRouteId ? '/' : TPrefixed\n\ntype RoutePrefix<\n TPrefix extends string,\n TPath extends string,\n> = string extends TPath\n ? RootRouteId\n : TPath extends string\n ? TPrefix extends RootRouteId\n ? TPath extends '/'\n ? '/'\n : `/${TrimPath<TPath>}`\n : `${TPrefix}/${TPath}` extends '/'\n ? '/'\n : `/${TrimPathLeft<`${TrimPathRight<TPrefix>}/${TrimPath<TPath>}`>}`\n : never\n\nexport type TrimPath<T extends string> = '' extends T\n ? ''\n : TrimPathRight<TrimPathLeft<T>>\n\nexport type TrimPathLeft<T extends string> =\n T extends `${RootRouteId}/${infer U}`\n ? TrimPathLeft<U>\n : T extends `/${infer U}`\n ? TrimPathLeft<U>\n : T\nexport type TrimPathRight<T extends string> = T extends '/'\n ? '/'\n : T extends `${infer U}/`\n ? TrimPathRight<U>\n : T\n"],"names":["rootRouteId","Route","constructor","options","isRoot","getParentRoute","__onInit","init","opts","originalIndex","router","path","id","parentRoute","invariant","trimPath","customId","joinPaths","fullPath","to","addChildren","children","update","Object","assign","route","RouterContext","createRootRoute","RootRoute"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAMO,MAAMA,WAAW,GAAG,WAAmB;;AAgW9C;;AAyJO,MAAMC,KAAK,CAqChB;AA8CA;;AAGA;;AAKA;;EAMAC,WAAWA,CACTC,OAsBG,EACH;AACA,IAAA,IAAI,CAACA,OAAO,GAAIA,OAAO,IAAY,EAAE,CAAA;AACrC,IAAA,IAAI,CAACC,MAAM,GAAG,CAACD,OAAO,EAAEE,cAAqB,CAAA;AAC7CJ,IAAAA,KAAK,CAACK,QAAQ,CAAC,IAAW,CAAC,CAAA;AAC7B,GAAA;EAEAC,IAAI,GAAIC,IAAkD,IAAK;AAC7D,IAAA,IAAI,CAACC,aAAa,GAAGD,IAAI,CAACC,aAAa,CAAA;AACvC,IAAA,IAAI,CAACC,MAAM,GAAGF,IAAI,CAACE,MAAM,CAAA;AAEzB,IAAA,MAAMP,OAAO,GAAG,IAAI,CAACA,OAQ2B,CAAA;IAEhD,MAAMC,M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,CAACC,EAAE,GAAGA,EAAS,CAAA;AACnB;IACA,IAAI,CAACM,QAAQ,GAAGA,QAAqB,CAAA;IACrC,IAAI,CAACC,EAAE,GAAGD,QAAoC,CAAA;GAC/C,CAAA;EAEDE,WAAW,GACTC,QAAsB,IAmBnB;IACH,IAAI,CAACA,QAAQ,GAAGA,QAAe,CAAA;AAC/B,IAAA,OAAO,IAAI,CAAA;GACZ,CAAA;EAEDC,MAAM,GACJnB,OAOC,IACE;IACHoB,MAAM,CAACC,MAAM,CAAC,IAAI,CAACrB,OAAO,EAAEA,OAAO,CAAC,CAAA;AACpC,IAAA,OAAO,IAAI,CAAA;GACZ,CAAA;EAED,OAAOG,QAAQ,GAAImB,KAAkB,IAAK;AACxC;AACA;GACD,CAAA;AACH,CAAA;AAIO,MAAMC,aAAa,CAA4B;EACpDxB,WAAWA,GAAG,EAAC;EAEfyB,eAAe,GAKbxB,OAsBC,IACoE;AACrE,IAAA,OAAO,IAAIyB,SAAS,CAACzB,OAAO,CAAC,CAAA;GAC9B,CAAA;AACH,CAAA;AAEO,MAAMyB,SAAS,SAKZ3B,KAAK,CAkBb;EACAC,WAAWA,CACTC,OAsBC,EACD;IACA,KAAK,CAACA,OAAc,CAAC,CAAA;AACvB,GAAA;AACF;;;;;;;"}
@@ -79,6 +79,24 @@ class Router {
79
79
  });
80
80
  }
81
81
  }
82
+ subscribers = new Set();
83
+ subscribe = (eventType, fn) => {
84
+ const listener = {
85
+ eventType,
86
+ fn
87
+ };
88
+ this.subscribers.add(listener);
89
+ return () => {
90
+ this.subscribers.delete(listener);
91
+ };
92
+ };
93
+ #emit = routerEvent => {
94
+ this.subscribers.forEach(listener => {
95
+ if (listener.eventType === routerEvent.type) {
96
+ listener.fn(routerEvent);
97
+ }
98
+ });
99
+ };
82
100
  reset = () => {
83
101
  this.__store.setState(s => Object.assign(s, getInitialRouterState()));
84
102
  };
@@ -109,7 +127,7 @@ class Router {
109
127
  resolvedLocation: parsedLocation,
110
128
  location: parsedLocation
111
129
  }));
112
- this.#unsubHistory = this.history.listen(() => {
130
+ this.#unsubHistory = this.history.subscribe(() => {
113
131
  this.safeLoad({
114
132
  next: this.#parseLocation(this.state.location)
115
133
  });
@@ -151,6 +169,8 @@ class Router {
151
169
  latestLoadPromise = Promise.resolve();
152
170
  load = async opts => {
153
171
  const promise = new Promise(async (resolve, reject) => {
172
+ const prevLocation = this.state.resolvedLocation;
173
+ const pathDidChange = !!(opts?.next && prevLocation.href !== opts.next.href);
154
174
  let latestPromise;
155
175
  const checkLatest = () => {
156
176
  return this.latestLoadPromise !== promise ? this.latestLoadPromise : undefined;
@@ -160,6 +180,12 @@ class Router {
160
180
  // this.cancelMatches()
161
181
 
162
182
  let pendingMatches;
183
+ this.#emit({
184
+ type: 'onBeforeLoad',
185
+ from: prevLocation,
186
+ to: opts?.next ?? this.state.location,
187
+ pathChanged: pathDidChange
188
+ });
163
189
  this.__store.batch(() => {
164
190
  if (opts?.next) {
165
191
  // Ingest the new location
@@ -194,7 +220,6 @@ class Router {
194
220
  if (latestPromise = checkLatest()) {
195
221
  return latestPromise;
196
222
  }
197
- const prevLocation = this.state.resolvedLocation;
198
223
  this.__store.setState(s => ({
199
224
  ...s,
200
225
  status: 'idle',
@@ -202,9 +227,12 @@ class Router {
202
227
  matchIds: s.pendingMatchIds,
203
228
  pendingMatchIds: []
204
229
  }));
205
- if (prevLocation.href !== this.state.location.href) {
206
- this.options.onRouteChange?.();
207
- }
230
+ this.#emit({
231
+ type: 'onLoad',
232
+ from: prevLocation,
233
+ to: this.state.location,
234
+ pathChanged: pathDidChange
235
+ });
208
236
  resolve();
209
237
  } catch (err) {
210
238
  // Only apply the latest transition
@@ -454,14 +482,14 @@ class Router {
454
482
  try {
455
483
  for (const [index, match] of resolvedMatches.entries()) {
456
484
  const route = this.getRoute(match.routeId);
457
- const handleError = (err, handler) => {
485
+ const handleError = (err, code) => {
486
+ err.routerCode = code;
458
487
  firstBadMatchIndex = firstBadMatchIndex ?? index;
459
- handler = handler || route.options.onError;
460
488
  if (isRedirect(err)) {
461
489
  throw err;
462
490
  }
463
491
  try {
464
- handler?.(err);
492
+ route.options.onError?.(err);
465
493
  } catch (errorHandlerErr) {
466
494
  err = errorHandlerErr;
467
495
  if (isRedirect(errorHandlerErr)) {
@@ -476,10 +504,10 @@ class Router {
476
504
  }));
477
505
  };
478
506
  if (match.paramsError) {
479
- handleError(match.paramsError, route.options.onParseParamsError);
507
+ handleError(match.paramsError, 'PARSE_PARAMS');
480
508
  }
481
509
  if (match.searchError) {
482
- handleError(match.searchError, route.options.onValidateSearchError);
510
+ handleError(match.searchError, 'VALIDATE_SEARCH');
483
511
  }
484
512
  let didError = false;
485
513
  try {
@@ -488,7 +516,7 @@ class Router {
488
516
  preload: !!opts?.preload
489
517
  });
490
518
  } catch (err) {
491
- handleError(err, route.options.onBeforeLoadError);
519
+ handleError(err, 'BEFORE_LOAD');
492
520
  didError = true;
493
521
  }
494
522
 
@@ -546,28 +574,18 @@ class Router {
546
574
  const [_, loader] = await Promise.all([componentsPromise, loaderPromise]);
547
575
  if (latestPromise = checkLatest()) return await latestPromise;
548
576
  this.setRouteMatchData(match.id, () => loader, opts);
549
- } catch (loaderError) {
550
- let latestError = loaderError;
577
+ } catch (error) {
551
578
  if (latestPromise = checkLatest()) return await latestPromise;
552
- if (handleIfRedirect(loaderError)) return;
553
- if (route.options.onLoadError) {
554
- try {
555
- route.options.onLoadError(loaderError);
556
- } catch (onLoadError) {
557
- latestError = onLoadError;
558
- if (handleIfRedirect(onLoadError)) return;
559
- }
560
- }
561
- if ((!route.options.onLoadError || latestError !== loaderError) && route.options.onError) {
562
- try {
563
- route.options.onError(latestError);
564
- } catch (onErrorError) {
565
- if (handleIfRedirect(onErrorError)) return;
566
- }
579
+ if (handleIfRedirect(error)) return;
580
+ try {
581
+ route.options.onError?.(error);
582
+ } catch (onErrorError) {
583
+ error = onErrorError;
584
+ if (handleIfRedirect(onErrorError)) return;
567
585
  }
568
586
  this.setRouteMatch(match.id, s => ({
569
587
  ...s,
570
- error: loaderError,
588
+ error,
571
589
  status: 'error',
572
590
  isFetching: false,
573
591
  updatedAt: Date.now()