@tanstack/router-core 1.131.26 → 1.131.28

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.
@@ -7,7 +7,6 @@ function getSafeSessionStorage() {
7
7
  return window.sessionStorage;
8
8
  }
9
9
  } catch {
10
- return void 0;
11
10
  }
12
11
  return void 0;
13
12
  }
@@ -46,12 +45,12 @@ function getCssSelector(el) {
46
45
  const path = [];
47
46
  let parent;
48
47
  while (parent = el.parentNode) {
49
- path.unshift(
50
- `${el.tagName}:nth-child(${[].indexOf.call(parent.children, el) + 1})`
48
+ path.push(
49
+ `${el.tagName}:nth-child(${Array.prototype.indexOf.call(parent.children, el) + 1})`
51
50
  );
52
51
  el = parent;
53
52
  }
54
- return `${path.join(" > ")}`.toLowerCase();
53
+ return `${path.reverse().join(" > ")}`.toLowerCase();
55
54
  }
56
55
  let ignoreScroll = false;
57
56
  function restoreScroll({
@@ -62,7 +61,7 @@ function restoreScroll({
62
61
  scrollToTopSelectors,
63
62
  location
64
63
  }) {
65
- var _a;
64
+ var _a, _b;
66
65
  let byKey;
67
66
  try {
68
67
  byKey = JSON.parse(sessionStorage.getItem(storageKey2) || "{}");
@@ -73,7 +72,7 @@ function restoreScroll({
73
72
  const resolvedKey = key || ((_a = window.history.state) == null ? void 0 : _a.key);
74
73
  const elementEntries = byKey[resolvedKey];
75
74
  ignoreScroll = true;
76
- (() => {
75
+ scroll: {
77
76
  if (shouldScrollRestoration && elementEntries && Object.keys(elementEntries).length > 0) {
78
77
  for (const elementSelector in elementEntries) {
79
78
  const entry = elementEntries[elementSelector];
@@ -91,33 +90,29 @@ function restoreScroll({
91
90
  }
92
91
  }
93
92
  }
94
- return;
93
+ break scroll;
95
94
  }
96
- const hash = (location ?? window.location).hash.split("#")[1];
95
+ const hash = (location ?? window.location).hash.split("#", 2)[1];
97
96
  if (hash) {
98
- const hashScrollIntoViewOptions = (window.history.state || {}).__hashScrollIntoViewOptions ?? true;
97
+ const hashScrollIntoViewOptions = ((_b = window.history.state) == null ? void 0 : _b.__hashScrollIntoViewOptions) ?? true;
99
98
  if (hashScrollIntoViewOptions) {
100
99
  const el = document.getElementById(hash);
101
100
  if (el) {
102
101
  el.scrollIntoView(hashScrollIntoViewOptions);
103
102
  }
104
103
  }
105
- return;
104
+ break scroll;
106
105
  }
107
- [
108
- "window",
109
- ...(scrollToTopSelectors == null ? void 0 : scrollToTopSelectors.filter((d) => d !== "window")) ?? []
110
- ].forEach((selector) => {
111
- const element = selector === "window" ? window : typeof selector === "function" ? selector() : document.querySelector(selector);
112
- if (element) {
113
- element.scrollTo({
114
- top: 0,
115
- left: 0,
116
- behavior
117
- });
106
+ const scrollOptions = { top: 0, left: 0, behavior };
107
+ window.scrollTo(scrollOptions);
108
+ if (scrollToTopSelectors) {
109
+ for (const selector of scrollToTopSelectors) {
110
+ if (selector === "window") continue;
111
+ const element = typeof selector === "function" ? selector() : document.querySelector(selector);
112
+ if (element) element.scrollTo(scrollOptions);
118
113
  }
119
- });
120
- })();
114
+ }
115
+ }
121
116
  ignoreScroll = false;
122
117
  }
123
118
  function setupScrollRestoration(router, force) {
@@ -154,8 +149,8 @@ function setupScrollRestoration(router, force) {
154
149
  }
155
150
  const restoreKey = getKey(router.state.location);
156
151
  scrollRestorationCache.set((state) => {
157
- const keyEntry = state[restoreKey] = state[restoreKey] || {};
158
- const elementEntry = keyEntry[elementSelector] = keyEntry[elementSelector] || {};
152
+ const keyEntry = state[restoreKey] || (state[restoreKey] = {});
153
+ const elementEntry = keyEntry[elementSelector] || (keyEntry[elementSelector] = {});
159
154
  if (elementSelector === "window") {
160
155
  elementEntry.scrollX = window.scrollX || 0;
161
156
  elementEntry.scrollY = window.scrollY || 0;
@@ -188,7 +183,7 @@ function setupScrollRestoration(router, force) {
188
183
  });
189
184
  if (router.isScrollRestoring) {
190
185
  scrollRestorationCache.set((state) => {
191
- state[cacheKey] = state[cacheKey] || {};
186
+ state[cacheKey] || (state[cacheKey] = {});
192
187
  return state;
193
188
  });
194
189
  }
@@ -1 +1 @@
1
- {"version":3,"file":"scroll-restoration.cjs","sources":["../../src/scroll-restoration.ts"],"sourcesContent":["import { functionalUpdate } from './utils'\nimport type { AnyRouter } from './router'\nimport type { ParsedLocation } from './location'\nimport type { NonNullableUpdater } from './utils'\nimport type { HistoryLocation } from '@tanstack/history'\n\nexport type ScrollRestorationEntry = { scrollX: number; scrollY: number }\n\nexport type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>\n\nexport type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>\n\nexport type ScrollRestorationCache = {\n state: ScrollRestorationByKey\n set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void\n}\nexport type ScrollRestorationOptions = {\n getKey?: (location: ParsedLocation) => string\n scrollBehavior?: ScrollToOptions['behavior']\n}\n\nfunction getSafeSessionStorage() {\n try {\n if (\n typeof window !== 'undefined' &&\n typeof window.sessionStorage === 'object'\n ) {\n return window.sessionStorage\n }\n } catch {\n return undefined\n }\n return undefined\n}\n\nexport const storageKey = 'tsr-scroll-restoration-v1_3'\n\nconst throttle = (fn: (...args: Array<any>) => void, wait: number) => {\n let timeout: any\n return (...args: Array<any>) => {\n if (!timeout) {\n timeout = setTimeout(() => {\n fn(...args)\n timeout = null\n }, wait)\n }\n }\n}\n\nfunction createScrollRestorationCache(): ScrollRestorationCache | undefined {\n const safeSessionStorage = getSafeSessionStorage()\n if (!safeSessionStorage) {\n return undefined\n }\n\n const persistedState = safeSessionStorage.getItem(storageKey)\n let state: ScrollRestorationByKey = persistedState\n ? JSON.parse(persistedState)\n : {}\n\n return {\n state,\n // This setter is simply to make sure that we set the sessionStorage right\n // after the state is updated. It doesn't necessarily need to be a functional\n // update.\n set: (updater) => (\n (state = functionalUpdate(updater, state) || state),\n safeSessionStorage.setItem(storageKey, JSON.stringify(state))\n ),\n }\n}\n\nexport const scrollRestorationCache = createScrollRestorationCache()\n\n/**\n * The default `getKey` function for `useScrollRestoration`.\n * It returns the `key` from the location state or the `href` of the location.\n *\n * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.\n */\n\nexport const defaultGetScrollRestorationKey = (location: ParsedLocation) => {\n return location.state.__TSR_key! || location.href\n}\n\nexport function getCssSelector(el: any): string {\n const path = []\n let parent\n while ((parent = el.parentNode)) {\n path.unshift(\n `${el.tagName}:nth-child(${([].indexOf as any).call(parent.children, el) + 1})`,\n )\n el = parent\n }\n return `${path.join(' > ')}`.toLowerCase()\n}\n\nlet ignoreScroll = false\n\n// NOTE: This function must remain pure and not use any outside variables\n// unless they are passed in as arguments. Why? Because we need to be able to\n// toString() it into a script tag to execute as early as possible in the browser\n// during SSR. Additionally, we also call it from within the router lifecycle\nexport function restoreScroll({\n storageKey,\n key,\n behavior,\n shouldScrollRestoration,\n scrollToTopSelectors,\n location,\n}: {\n storageKey: string\n key?: string\n behavior?: ScrollToOptions['behavior']\n shouldScrollRestoration?: boolean\n scrollToTopSelectors?: Array<string | (() => Element | null | undefined)>\n location?: HistoryLocation\n}) {\n let byKey: ScrollRestorationByKey\n\n try {\n byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}')\n } catch (error: any) {\n console.error(error)\n return\n }\n\n const resolvedKey = key || window.history.state?.key\n const elementEntries = byKey[resolvedKey]\n\n //\n ignoreScroll = true\n\n //\n ;(() => {\n // If we have a cached entry for this location state,\n // we always need to prefer that over the hash scroll.\n if (\n shouldScrollRestoration &&\n elementEntries &&\n Object.keys(elementEntries).length > 0\n ) {\n for (const elementSelector in elementEntries) {\n const entry = elementEntries[elementSelector]!\n if (elementSelector === 'window') {\n window.scrollTo({\n top: entry.scrollY,\n left: entry.scrollX,\n behavior,\n })\n } else if (elementSelector) {\n const element = document.querySelector(elementSelector)\n if (element) {\n element.scrollLeft = entry.scrollX\n element.scrollTop = entry.scrollY\n }\n }\n }\n\n return\n }\n\n // If we don't have a cached entry for the hash,\n // Which means we've never seen this location before,\n // we need to check if there is a hash in the URL.\n // If there is, we need to scroll it's ID into view.\n const hash = (location ?? window.location).hash.split('#')[1]\n\n if (hash) {\n const hashScrollIntoViewOptions =\n (window.history.state || {}).__hashScrollIntoViewOptions ?? true\n\n if (hashScrollIntoViewOptions) {\n const el = document.getElementById(hash)\n if (el) {\n el.scrollIntoView(hashScrollIntoViewOptions)\n }\n }\n\n return\n }\n\n // If there is no cached entry for the hash and there is no hash in the URL,\n // we need to scroll to the top of the page for every scrollToTop element\n ;[\n 'window',\n ...(scrollToTopSelectors?.filter((d) => d !== 'window') ?? []),\n ].forEach((selector) => {\n const element =\n selector === 'window'\n ? window\n : typeof selector === 'function'\n ? selector()\n : document.querySelector(selector)\n if (element) {\n element.scrollTo({\n top: 0,\n left: 0,\n behavior,\n })\n }\n })\n })()\n\n //\n ignoreScroll = false\n}\n\nexport function setupScrollRestoration(router: AnyRouter, force?: boolean) {\n if (scrollRestorationCache === undefined) {\n return\n }\n const shouldScrollRestoration =\n force ?? router.options.scrollRestoration ?? false\n\n if (shouldScrollRestoration) {\n router.isScrollRestoring = true\n }\n\n if (typeof document === 'undefined' || router.isScrollRestorationSetup) {\n return\n }\n\n router.isScrollRestorationSetup = true\n\n //\n ignoreScroll = false\n\n const getKey =\n router.options.getScrollRestorationKey || defaultGetScrollRestorationKey\n\n window.history.scrollRestoration = 'manual'\n\n // // Create a MutationObserver to monitor DOM changes\n // const mutationObserver = new MutationObserver(() => {\n // ;ignoreScroll = true\n // requestAnimationFrame(() => {\n // ;ignoreScroll = false\n\n // // Attempt to restore scroll position on each dom\n // // mutation until the user scrolls. We do this\n // // because dynamic content may come in at different\n // // ticks after the initial render and we want to\n // // keep up with that content as much as possible.\n // // As soon as the user scrolls, we no longer need\n // // to attempt router.\n // // console.log('mutation observer restoreScroll')\n // restoreScroll(\n // storageKey,\n // getKey(router.state.location),\n // router.options.scrollRestorationBehavior,\n // )\n // })\n // })\n\n // const observeDom = () => {\n // // Observe changes to the entire document\n // mutationObserver.observe(document, {\n // childList: true, // Detect added or removed child nodes\n // subtree: true, // Monitor all descendants\n // characterData: true, // Detect text content changes\n // })\n // }\n\n // const unobserveDom = () => {\n // mutationObserver.disconnect()\n // }\n\n // observeDom()\n\n const onScroll = (event: Event) => {\n // unobserveDom()\n\n if (ignoreScroll || !router.isScrollRestoring) {\n return\n }\n\n let elementSelector = ''\n\n if (event.target === document || event.target === window) {\n elementSelector = 'window'\n } else {\n const attrId = (event.target as Element).getAttribute(\n 'data-scroll-restoration-id',\n )\n\n if (attrId) {\n elementSelector = `[data-scroll-restoration-id=\"${attrId}\"]`\n } else {\n elementSelector = getCssSelector(event.target)\n }\n }\n\n const restoreKey = getKey(router.state.location)\n\n scrollRestorationCache.set((state) => {\n const keyEntry = (state[restoreKey] =\n state[restoreKey] || ({} as ScrollRestorationByElement))\n\n const elementEntry = (keyEntry[elementSelector] =\n keyEntry[elementSelector] || ({} as ScrollRestorationEntry))\n\n if (elementSelector === 'window') {\n elementEntry.scrollX = window.scrollX || 0\n elementEntry.scrollY = window.scrollY || 0\n } else if (elementSelector) {\n const element = document.querySelector(elementSelector)\n if (element) {\n elementEntry.scrollX = element.scrollLeft || 0\n elementEntry.scrollY = element.scrollTop || 0\n }\n }\n\n return state\n })\n }\n\n // Throttle the scroll event to avoid excessive updates\n if (typeof document !== 'undefined') {\n document.addEventListener('scroll', throttle(onScroll, 100), true)\n }\n\n router.subscribe('onRendered', (event) => {\n // unobserveDom()\n\n const cacheKey = getKey(event.toLocation)\n\n // If the user doesn't want to restore the scroll position,\n // we don't need to do anything.\n if (!router.resetNextScroll) {\n router.resetNextScroll = true\n return\n }\n\n restoreScroll({\n storageKey,\n key: cacheKey,\n behavior: router.options.scrollRestorationBehavior,\n shouldScrollRestoration: router.isScrollRestoring,\n scrollToTopSelectors: router.options.scrollToTopSelectors,\n location: router.history.location,\n })\n\n if (router.isScrollRestoring) {\n // Mark the location as having been seen\n scrollRestorationCache.set((state) => {\n state[cacheKey] = state[cacheKey] || ({} as ScrollRestorationByElement)\n\n return state\n })\n }\n })\n}\n\n/**\n * @internal\n * Handles hash-based scrolling after navigation completes.\n * To be used in framework-specific <Transitioner> components during the onResolved event.\n *\n * Provides hash scrolling for programmatic navigation when default browser handling is prevented.\n * @param router The router instance containing current location and state\n */\nexport function handleHashScroll(router: AnyRouter) {\n if (typeof document !== 'undefined' && (document as any).querySelector) {\n const hashScrollIntoViewOptions =\n router.state.location.state.__hashScrollIntoViewOptions ?? true\n\n if (hashScrollIntoViewOptions && router.state.location.hash !== '') {\n const el = document.getElementById(router.state.location.hash)\n if (el) {\n el.scrollIntoView(hashScrollIntoViewOptions)\n }\n }\n }\n}\n"],"names":["functionalUpdate","storageKey"],"mappings":";;;AAqBA,SAAS,wBAAwB;AAC3B,MAAA;AACF,QACE,OAAO,WAAW,eAClB,OAAO,OAAO,mBAAmB,UACjC;AACA,aAAO,OAAO;AAAA,IAAA;AAAA,EAChB,QACM;AACC,WAAA;AAAA,EAAA;AAEF,SAAA;AACT;AAEO,MAAM,aAAa;AAE1B,MAAM,WAAW,CAAC,IAAmC,SAAiB;AAChE,MAAA;AACJ,SAAO,IAAI,SAAqB;AAC9B,QAAI,CAAC,SAAS;AACZ,gBAAU,WAAW,MAAM;AACzB,WAAG,GAAG,IAAI;AACA,kBAAA;AAAA,SACT,IAAI;AAAA,IAAA;AAAA,EAEX;AACF;AAEA,SAAS,+BAAmE;AAC1E,QAAM,qBAAqB,sBAAsB;AACjD,MAAI,CAAC,oBAAoB;AAChB,WAAA;AAAA,EAAA;AAGH,QAAA,iBAAiB,mBAAmB,QAAQ,UAAU;AAC5D,MAAI,QAAgC,iBAChC,KAAK,MAAM,cAAc,IACzB,CAAC;AAEE,SAAA;AAAA,IACL;AAAA;AAAA;AAAA;AAAA,IAIA,KAAK,CAAC,aACH,QAAQA,MAAAA,iBAAiB,SAAS,KAAK,KAAK,OAC7C,mBAAmB,QAAQ,YAAY,KAAK,UAAU,KAAK,CAAC;AAAA,EAEhE;AACF;AAEO,MAAM,yBAAyB,6BAA6B;AAStD,MAAA,iCAAiC,CAA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4BACJ,OAAO,MAAM,SAAS,MAAM,+BAA+B;AAE7D,QAAI,6BAA6B,OAAO,MAAM,SAAS,SAAS,IAAI;AAClE,YAAM,KAAK,SAAS,eAAe,OAAO,MAAM,SAAS,IAAI;AAC7D,UAAI,IAAI;AACN,WAAG,eAAe,yBAAyB;AAAA,MAAA;AAAA,IAC7C;AAAA,EACF;AAEJ;;;;;;;;"}
1
+ {"version":3,"file":"scroll-restoration.cjs","sources":["../../src/scroll-restoration.ts"],"sourcesContent":["import { functionalUpdate } from './utils'\nimport type { AnyRouter } from './router'\nimport type { ParsedLocation } from './location'\nimport type { NonNullableUpdater } from './utils'\nimport type { HistoryLocation } from '@tanstack/history'\n\nexport type ScrollRestorationEntry = { scrollX: number; scrollY: number }\n\nexport type ScrollRestorationByElement = Record<string, ScrollRestorationEntry>\n\nexport type ScrollRestorationByKey = Record<string, ScrollRestorationByElement>\n\nexport type ScrollRestorationCache = {\n state: ScrollRestorationByKey\n set: (updater: NonNullableUpdater<ScrollRestorationByKey>) => void\n}\nexport type ScrollRestorationOptions = {\n getKey?: (location: ParsedLocation) => string\n scrollBehavior?: ScrollToOptions['behavior']\n}\n\nfunction getSafeSessionStorage() {\n try {\n if (\n typeof window !== 'undefined' &&\n typeof window.sessionStorage === 'object'\n ) {\n return window.sessionStorage\n }\n } catch {\n // silent\n }\n return undefined\n}\n\nexport const storageKey = 'tsr-scroll-restoration-v1_3'\n\nconst throttle = (fn: (...args: Array<any>) => void, wait: number) => {\n let timeout: any\n return (...args: Array<any>) => {\n if (!timeout) {\n timeout = setTimeout(() => {\n fn(...args)\n timeout = null\n }, wait)\n }\n }\n}\n\nfunction createScrollRestorationCache(): ScrollRestorationCache | undefined {\n const safeSessionStorage = getSafeSessionStorage()\n if (!safeSessionStorage) {\n return undefined\n }\n\n const persistedState = safeSessionStorage.getItem(storageKey)\n let state: ScrollRestorationByKey = persistedState\n ? JSON.parse(persistedState)\n : {}\n\n return {\n state,\n // This setter is simply to make sure that we set the sessionStorage right\n // after the state is updated. It doesn't necessarily need to be a functional\n // update.\n set: (updater) => (\n (state = functionalUpdate(updater, state) || state),\n safeSessionStorage.setItem(storageKey, JSON.stringify(state))\n ),\n }\n}\n\nexport const scrollRestorationCache = createScrollRestorationCache()\n\n/**\n * The default `getKey` function for `useScrollRestoration`.\n * It returns the `key` from the location state or the `href` of the location.\n *\n * The `location.href` is used as a fallback to support the use case where the location state is not available like the initial render.\n */\n\nexport const defaultGetScrollRestorationKey = (location: ParsedLocation) => {\n return location.state.__TSR_key! || location.href\n}\n\nexport function getCssSelector(el: any): string {\n const path = []\n let parent: HTMLElement\n while ((parent = el.parentNode)) {\n path.push(\n `${el.tagName}:nth-child(${Array.prototype.indexOf.call(parent.children, el) + 1})`,\n )\n el = parent\n }\n return `${path.reverse().join(' > ')}`.toLowerCase()\n}\n\nlet ignoreScroll = false\n\n// NOTE: This function must remain pure and not use any outside variables\n// unless they are passed in as arguments. Why? Because we need to be able to\n// toString() it into a script tag to execute as early as possible in the browser\n// during SSR. Additionally, we also call it from within the router lifecycle\nexport function restoreScroll({\n storageKey,\n key,\n behavior,\n shouldScrollRestoration,\n scrollToTopSelectors,\n location,\n}: {\n storageKey: string\n key?: string\n behavior?: ScrollToOptions['behavior']\n shouldScrollRestoration?: boolean\n scrollToTopSelectors?: Array<string | (() => Element | null | undefined)>\n location?: HistoryLocation\n}) {\n let byKey: ScrollRestorationByKey\n\n try {\n byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}')\n } catch (error) {\n console.error(error)\n return\n }\n\n const resolvedKey = key || window.history.state?.key\n const elementEntries = byKey[resolvedKey]\n\n //\n ignoreScroll = true\n\n //\n scroll: {\n // If we have a cached entry for this location state,\n // we always need to prefer that over the hash scroll.\n if (\n shouldScrollRestoration &&\n elementEntries &&\n Object.keys(elementEntries).length > 0\n ) {\n for (const elementSelector in elementEntries) {\n const entry = elementEntries[elementSelector]!\n if (elementSelector === 'window') {\n window.scrollTo({\n top: entry.scrollY,\n left: entry.scrollX,\n behavior,\n })\n } else if (elementSelector) {\n const element = document.querySelector(elementSelector)\n if (element) {\n element.scrollLeft = entry.scrollX\n element.scrollTop = entry.scrollY\n }\n }\n }\n\n break scroll\n }\n\n // If we don't have a cached entry for the hash,\n // Which means we've never seen this location before,\n // we need to check if there is a hash in the URL.\n // If there is, we need to scroll it's ID into view.\n const hash = (location ?? window.location).hash.split('#', 2)[1]\n\n if (hash) {\n const hashScrollIntoViewOptions =\n window.history.state?.__hashScrollIntoViewOptions ?? true\n\n if (hashScrollIntoViewOptions) {\n const el = document.getElementById(hash)\n if (el) {\n el.scrollIntoView(hashScrollIntoViewOptions)\n }\n }\n\n break scroll\n }\n\n // If there is no cached entry for the hash and there is no hash in the URL,\n // we need to scroll to the top of the page for every scrollToTop element\n const scrollOptions = { top: 0, left: 0, behavior }\n window.scrollTo(scrollOptions)\n if (scrollToTopSelectors) {\n for (const selector of scrollToTopSelectors) {\n if (selector === 'window') continue\n const element =\n typeof selector === 'function'\n ? selector()\n : document.querySelector(selector)\n if (element) element.scrollTo(scrollOptions)\n }\n }\n }\n\n //\n ignoreScroll = false\n}\n\nexport function setupScrollRestoration(router: AnyRouter, force?: boolean) {\n if (scrollRestorationCache === undefined) {\n return\n }\n const shouldScrollRestoration =\n force ?? router.options.scrollRestoration ?? false\n\n if (shouldScrollRestoration) {\n router.isScrollRestoring = true\n }\n\n if (typeof document === 'undefined' || router.isScrollRestorationSetup) {\n return\n }\n\n router.isScrollRestorationSetup = true\n\n //\n ignoreScroll = false\n\n const getKey =\n router.options.getScrollRestorationKey || defaultGetScrollRestorationKey\n\n window.history.scrollRestoration = 'manual'\n\n // // Create a MutationObserver to monitor DOM changes\n // const mutationObserver = new MutationObserver(() => {\n // ;ignoreScroll = true\n // requestAnimationFrame(() => {\n // ;ignoreScroll = false\n\n // // Attempt to restore scroll position on each dom\n // // mutation until the user scrolls. We do this\n // // because dynamic content may come in at different\n // // ticks after the initial render and we want to\n // // keep up with that content as much as possible.\n // // As soon as the user scrolls, we no longer need\n // // to attempt router.\n // // console.log('mutation observer restoreScroll')\n // restoreScroll(\n // storageKey,\n // getKey(router.state.location),\n // router.options.scrollRestorationBehavior,\n // )\n // })\n // })\n\n // const observeDom = () => {\n // // Observe changes to the entire document\n // mutationObserver.observe(document, {\n // childList: true, // Detect added or removed child nodes\n // subtree: true, // Monitor all descendants\n // characterData: true, // Detect text content changes\n // })\n // }\n\n // const unobserveDom = () => {\n // mutationObserver.disconnect()\n // }\n\n // observeDom()\n\n const onScroll = (event: Event) => {\n // unobserveDom()\n\n if (ignoreScroll || !router.isScrollRestoring) {\n return\n }\n\n let elementSelector = ''\n\n if (event.target === document || event.target === window) {\n elementSelector = 'window'\n } else {\n const attrId = (event.target as Element).getAttribute(\n 'data-scroll-restoration-id',\n )\n\n if (attrId) {\n elementSelector = `[data-scroll-restoration-id=\"${attrId}\"]`\n } else {\n elementSelector = getCssSelector(event.target)\n }\n }\n\n const restoreKey = getKey(router.state.location)\n\n scrollRestorationCache.set((state) => {\n const keyEntry = (state[restoreKey] ||= {} as ScrollRestorationByElement)\n\n const elementEntry = (keyEntry[elementSelector] ||=\n {} as ScrollRestorationEntry)\n\n if (elementSelector === 'window') {\n elementEntry.scrollX = window.scrollX || 0\n elementEntry.scrollY = window.scrollY || 0\n } else if (elementSelector) {\n const element = document.querySelector(elementSelector)\n if (element) {\n elementEntry.scrollX = element.scrollLeft || 0\n elementEntry.scrollY = element.scrollTop || 0\n }\n }\n\n return state\n })\n }\n\n // Throttle the scroll event to avoid excessive updates\n if (typeof document !== 'undefined') {\n document.addEventListener('scroll', throttle(onScroll, 100), true)\n }\n\n router.subscribe('onRendered', (event) => {\n // unobserveDom()\n\n const cacheKey = getKey(event.toLocation)\n\n // If the user doesn't want to restore the scroll position,\n // we don't need to do anything.\n if (!router.resetNextScroll) {\n router.resetNextScroll = true\n return\n }\n\n restoreScroll({\n storageKey,\n key: cacheKey,\n behavior: router.options.scrollRestorationBehavior,\n shouldScrollRestoration: router.isScrollRestoring,\n scrollToTopSelectors: router.options.scrollToTopSelectors,\n location: router.history.location,\n })\n\n if (router.isScrollRestoring) {\n // Mark the location as having been seen\n scrollRestorationCache.set((state) => {\n state[cacheKey] ||= {} as ScrollRestorationByElement\n\n return state\n })\n }\n })\n}\n\n/**\n * @internal\n * Handles hash-based scrolling after navigation completes.\n * To be used in framework-specific <Transitioner> components during the onResolved event.\n *\n * Provides hash scrolling for programmatic navigation when default browser handling is prevented.\n * @param router The router instance containing current location and state\n */\nexport function handleHashScroll(router: AnyRouter) {\n if (typeof document !== 'undefined' && (document as any).querySelector) {\n const hashScrollIntoViewOptions =\n router.state.location.state.__hashScrollIntoViewOptions ?? true\n\n if (hashScrollIntoViewOptions && router.state.location.hash !== '') {\n const el = document.getElementById(router.state.location.hash)\n if (el) {\n el.scrollIntoView(hashScrollIntoViewOptions)\n }\n }\n }\n}\n"],"names":["functionalUpdate","storageKey"],"mappings":";;;AAqBA,SAAS,wBAAwB;AAC3B,MAAA;AACF,QACE,OAAO,WAAW,eAClB,OAAO,OAAO,mBAAmB,UACjC;AACA,aAAO,OAAO;AAAA,IAAA;AAAA,EAChB,QACM;AAAA,EAAA;AAGD,SAAA;AACT;AAEO,MAAM,aAAa;AAE1B,MAAM,WAAW,CAAC,IAAmC,SAAiB;AAChE,MAAA;AACJ,SAAO,IAAI,SAAqB;AAC9B,QAAI,CAAC,SAAS;AACZ,gBAAU,WAAW,MAAM;AACzB,WAAG,GAAG,IAAI;AACA,kBAAA;AAAA,SACT,IAAI;AAAA,IAAA;AAAA,EAEX;AACF;AAEA,SAAS,+BAAmE;AAC1E,QAAM,qBAAqB,sBAAsB;AACjD,MAAI,CAAC,oBAAoB;AAChB,WAAA;AAAA,EAAA;AAGH,QAAA,iBAAiB,mBAAmB,QAAQ,UAAU;AAC5D,MAAI,QAAgC,iBAChC,KAAK,MAAM,cAAc,IACzB,CAAC;AAEE,SAAA;AAAA,IACL;AAAA;AAAA;AAAA;AAAA,IAIA,KAAK,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,MAAI,OAAO,aAAa,eAAgB,SAAiB,eAAe;AACtE,UAAM,4BACJ,OAAO,MAAM,SAAS,MAAM,+BAA+B;AAE7D,QAAI,6BAA6B,OAAO,MAAM,SAAS,SAAS,IAAI;AAClE,YAAM,KAAK,SAAS,eAAe,OAAO,MAAM,SAAS,IAAI;AAC7D,UAAI,IAAI;AACN,WAAG,eAAe,yBAAyB;AAAA,MAAA;AAAA,IAC7C;AAAA,EACF;AAEJ;;;;;;;;"}
@@ -8,7 +8,7 @@ const defaultStringifySearch = stringifySearchWith(
8
8
  );
9
9
  function parseSearchWith(parser) {
10
10
  return (searchStr) => {
11
- if (searchStr.substring(0, 1) === "?") {
11
+ if (searchStr[0] === "?") {
12
12
  searchStr = searchStr.substring(1);
13
13
  }
14
14
  const query = qss.decode(searchStr);
@@ -17,7 +17,7 @@ function parseSearchWith(parser) {
17
17
  if (typeof value === "string") {
18
18
  try {
19
19
  query[key] = parser(value);
20
- } catch (err) {
20
+ } catch (_err) {
21
21
  }
22
22
  }
23
23
  }
@@ -25,32 +25,24 @@ function parseSearchWith(parser) {
25
25
  };
26
26
  }
27
27
  function stringifySearchWith(stringify, parser) {
28
+ const hasParser = typeof parser === "function";
28
29
  function stringifyValue(val) {
29
30
  if (typeof val === "object" && val !== null) {
30
31
  try {
31
32
  return stringify(val);
32
- } catch (err) {
33
+ } catch (_err) {
33
34
  }
34
- } else if (typeof val === "string" && typeof parser === "function") {
35
+ } else if (hasParser && typeof val === "string") {
35
36
  try {
36
37
  parser(val);
37
38
  return stringify(val);
38
- } catch (err) {
39
+ } catch (_err) {
39
40
  }
40
41
  }
41
42
  return val;
42
43
  }
43
44
  return (search) => {
44
- search = { ...search };
45
- Object.keys(search).forEach((key) => {
46
- const val = search[key];
47
- if (typeof val === "undefined" || val === void 0) {
48
- delete search[key];
49
- } else {
50
- search[key] = stringifyValue(val);
51
- }
52
- });
53
- const searchStr = qss.encode(search).toString();
45
+ const searchStr = qss.encode(search, stringifyValue);
54
46
  return searchStr ? `?${searchStr}` : "";
55
47
  };
56
48
  }
@@ -1 +1 @@
1
- {"version":3,"file":"searchParams.cjs","sources":["../../src/searchParams.ts"],"sourcesContent":["import { decode, encode } from './qss'\nimport type { AnySchema } from './validators'\n\nexport const defaultParseSearch = parseSearchWith(JSON.parse)\nexport const defaultStringifySearch = stringifySearchWith(\n JSON.stringify,\n JSON.parse,\n)\n\nexport function parseSearchWith(parser: (str: string) => any) {\n return (searchStr: string): AnySchema => {\n if (searchStr.substring(0, 1) === '?') {\n searchStr = searchStr.substring(1)\n }\n\n const query: Record<string, unknown> = decode(searchStr)\n\n // Try to parse any query params that might be json\n for (const key in query) {\n const value = query[key]\n if (typeof value === 'string') {\n try {\n query[key] = parser(value)\n } catch (err) {\n //\n }\n }\n }\n\n return query\n }\n}\n\nexport function stringifySearchWith(\n stringify: (search: any) => string,\n parser?: (str: string) => any,\n) {\n function stringifyValue(val: any) {\n if (typeof val === 'object' && val !== null) {\n try {\n return stringify(val)\n } catch (err) {\n // silent\n }\n } else if (typeof val === 'string' && typeof parser === 'function') {\n try {\n // Check if it's a valid parseable string.\n // If it is, then stringify it again.\n parser(val)\n return stringify(val)\n } catch (err) {\n // silent\n }\n }\n return val\n }\n\n return (search: Record<string, any>) => {\n search = { ...search }\n\n Object.keys(search).forEach((key) => {\n const val = search[key]\n if (typeof val === 'undefined' || val === undefined) {\n delete search[key]\n } else {\n search[key] = stringifyValue(val)\n }\n })\n\n const searchStr = encode(search as Record<string, string>).toString()\n\n return searchStr ? `?${searchStr}` : ''\n }\n}\n\nexport type SearchSerializer = (searchObj: Record<string, any>) => string\nexport type SearchParser = (searchStr: string) => Record<string, any>\n"],"names":["decode","encode"],"mappings":";;;AAGa,MAAA,qBAAqB,gBAAgB,KAAK,KAAK;AACrD,MAAM,yBAAyB;AAAA,EACpC,KAAK;AAAA,EACL,KAAK;AACP;AAEO,SAAS,gBAAgB,QAA8B;AAC5D,SAAO,CAAC,cAAiC;AACvC,QAAI,UAAU,UAAU,GAAG,CAAC,MAAM,KAAK;AACzB,kBAAA,UAAU,UAAU,CAAC;AAAA,IAAA;AAG7B,UAAA,QAAiCA,WAAO,SAAS;AAGvD,eAAW,OAAO,OAAO;AACjB,YAAA,QAAQ,MAAM,GAAG;AACnB,UAAA,OAAO,UAAU,UAAU;AACzB,YAAA;AACI,gBAAA,GAAG,IAAI,OAAO,KAAK;AAAA,iBAClB,KAAK;AAAA,QAAA;AAAA,MAEd;AAAA,IACF;AAGK,WAAA;AAAA,EACT;AACF;AAEgB,SAAA,oBACd,WACA,QACA;AACA,WAAS,eAAe,KAAU;AAChC,QAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM;AACvC,UAAA;AACF,eAAO,UAAU,GAAG;AAAA,eACb,KAAK;AAAA,MAAA;AAAA,eAGL,OAAO,QAAQ,YAAY,OAAO,WAAW,YAAY;AAC9D,UAAA;AAGF,eAAO,GAAG;AACV,eAAO,UAAU,GAAG;AAAA,eACb,KAAK;AAAA,MAAA;AAAA,IAEd;AAEK,WAAA;AAAA,EAAA;AAGT,SAAO,CAAC,WAAgC;AAC7B,aAAA,EAAE,GAAG,OAAO;AAErB,WAAO,KAAK,MAAM,EAAE,QAAQ,CAAC,QAAQ;AAC7B,YAAA,MAAM,OAAO,GAAG;AACtB,UAAI,OAAO,QAAQ,eAAe,QAAQ,QAAW;AACnD,eAAO,OAAO,GAAG;AAAA,MAAA,OACZ;AACE,eAAA,GAAG,IAAI,eAAe,GAAG;AAAA,MAAA;AAAA,IAClC,CACD;AAED,UAAM,YAAYC,IAAAA,OAAO,MAAgC,EAAE,SAAS;AAE7D,WAAA,YAAY,IAAI,SAAS,KAAK;AAAA,EACvC;AACF;;;;;"}
1
+ {"version":3,"file":"searchParams.cjs","sources":["../../src/searchParams.ts"],"sourcesContent":["import { decode, encode } from './qss'\nimport type { AnySchema } from './validators'\n\nexport const defaultParseSearch = parseSearchWith(JSON.parse)\nexport const defaultStringifySearch = stringifySearchWith(\n JSON.stringify,\n JSON.parse,\n)\n\nexport function parseSearchWith(parser: (str: string) => any) {\n return (searchStr: string): AnySchema => {\n if (searchStr[0] === '?') {\n searchStr = searchStr.substring(1)\n }\n\n const query: Record<string, unknown> = decode(searchStr)\n\n // Try to parse any query params that might be json\n for (const key in query) {\n const value = query[key]\n if (typeof value === 'string') {\n try {\n query[key] = parser(value)\n } catch (_err) {\n // silent\n }\n }\n }\n\n return query\n }\n}\n\nexport function stringifySearchWith(\n stringify: (search: any) => string,\n parser?: (str: string) => any,\n) {\n const hasParser = typeof parser === 'function'\n function stringifyValue(val: any) {\n if (typeof val === 'object' && val !== null) {\n try {\n return stringify(val)\n } catch (_err) {\n // silent\n }\n } else if (hasParser && typeof val === 'string') {\n try {\n // Check if it's a valid parseable string.\n // If it is, then stringify it again.\n parser(val)\n return stringify(val)\n } catch (_err) {\n // silent\n }\n }\n return val\n }\n\n return (search: Record<string, any>) => {\n const searchStr = encode(search, stringifyValue)\n return searchStr ? `?${searchStr}` : ''\n }\n}\n\nexport type SearchSerializer = (searchObj: Record<string, any>) => string\nexport type SearchParser = (searchStr: string) => Record<string, any>\n"],"names":["decode","encode"],"mappings":";;;AAGa,MAAA,qBAAqB,gBAAgB,KAAK,KAAK;AACrD,MAAM,yBAAyB;AAAA,EACpC,KAAK;AAAA,EACL,KAAK;AACP;AAEO,SAAS,gBAAgB,QAA8B;AAC5D,SAAO,CAAC,cAAiC;AACnC,QAAA,UAAU,CAAC,MAAM,KAAK;AACZ,kBAAA,UAAU,UAAU,CAAC;AAAA,IAAA;AAG7B,UAAA,QAAiCA,WAAO,SAAS;AAGvD,eAAW,OAAO,OAAO;AACjB,YAAA,QAAQ,MAAM,GAAG;AACnB,UAAA,OAAO,UAAU,UAAU;AACzB,YAAA;AACI,gBAAA,GAAG,IAAI,OAAO,KAAK;AAAA,iBAClB,MAAM;AAAA,QAAA;AAAA,MAEf;AAAA,IACF;AAGK,WAAA;AAAA,EACT;AACF;AAEgB,SAAA,oBACd,WACA,QACA;AACM,QAAA,YAAY,OAAO,WAAW;AACpC,WAAS,eAAe,KAAU;AAChC,QAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM;AACvC,UAAA;AACF,eAAO,UAAU,GAAG;AAAA,eACb,MAAM;AAAA,MAAA;AAAA,IAGN,WAAA,aAAa,OAAO,QAAQ,UAAU;AAC3C,UAAA;AAGF,eAAO,GAAG;AACV,eAAO,UAAU,GAAG;AAAA,eACb,MAAM;AAAA,MAAA;AAAA,IAEf;AAEK,WAAA;AAAA,EAAA;AAGT,SAAO,CAAC,WAAgC;AAChC,UAAA,YAAYC,IAAAA,OAAO,QAAQ,cAAc;AACxC,WAAA,YAAY,IAAI,SAAS,KAAK;AAAA,EACvC;AACF;;;;;"}
@@ -76,10 +76,8 @@ const shouldSkipLoader = (inner, matchId) => {
76
76
  if (!inner.router.isServer && match._nonReactive.dehydrated) {
77
77
  return true;
78
78
  }
79
- if (inner.router.isServer) {
80
- if (match.ssr === false) {
81
- return true;
82
- }
79
+ if (inner.router.isServer && match.ssr === false) {
80
+ return true;
83
81
  }
84
82
  return false;
85
83
  };
@@ -180,20 +178,16 @@ const setupPendingTimeout = (inner, matchId, route, match) => {
180
178
  match._nonReactive.pendingTimeout = pendingTimeout;
181
179
  }
182
180
  };
183
- const shouldExecuteBeforeLoad = (inner, matchId, route) => {
181
+ const preBeforeLoadSetup = (inner, matchId, route) => {
184
182
  const existingMatch = inner.router.getMatch(matchId);
185
183
  if (!existingMatch._nonReactive.beforeLoadPromise && !existingMatch._nonReactive.loaderPromise)
186
- return true;
184
+ return;
187
185
  setupPendingTimeout(inner, matchId, route, existingMatch);
188
186
  const then = () => {
189
- let result = true;
190
187
  const match = inner.router.getMatch(matchId);
191
- if (match.status === "error") {
192
- result = true;
193
- } else if (match.preload && (match.status === "redirected" || match.status === "notFound")) {
188
+ if (match.preload && (match.status === "redirected" || match.status === "notFound")) {
194
189
  handleRedirectAndNotFound(inner, match, match.error);
195
190
  }
196
- return result;
197
191
  };
198
192
  return existingMatch._nonReactive.beforeLoadPromise ? existingMatch._nonReactive.beforeLoadPromise.then(then) : then();
199
193
  };
@@ -316,19 +310,10 @@ const handleBeforeLoad = (inner, index) => {
316
310
  };
317
311
  const queueExecution = () => {
318
312
  if (shouldSkipLoader(inner, matchId)) return;
319
- const shouldExecuteBeforeLoadResult = shouldExecuteBeforeLoad(
320
- inner,
321
- matchId,
322
- route
323
- );
324
- return isPromise(shouldExecuteBeforeLoadResult) ? shouldExecuteBeforeLoadResult.then(execute) : execute(shouldExecuteBeforeLoadResult);
325
- };
326
- const execute = (shouldExec) => {
327
- if (shouldExec) {
328
- return executeBeforeLoad(inner, matchId, index, route);
329
- }
330
- return;
313
+ const result = preBeforeLoadSetup(inner, matchId, route);
314
+ return isPromise(result) ? result.then(execute) : execute();
331
315
  };
316
+ const execute = () => executeBeforeLoad(inner, matchId, index, route);
332
317
  return serverSsr();
333
318
  };
334
319
  const executeHead = (inner, matchId, route) => {
@@ -1 +1 @@
1
- {"version":3,"file":"load-matches.js","sources":["../../src/load-matches.ts"],"sourcesContent":["import { batch } from '@tanstack/store'\nimport invariant from 'tiny-invariant'\nimport { createControlledPromise, isPromise } from './utils'\nimport { isNotFound } from './not-found'\nimport { rootRouteId } from './root'\nimport { isRedirect } from './redirect'\nimport type { NotFoundError } from './not-found'\nimport type { ParsedLocation } from './location'\nimport type {\n AnyRoute,\n BeforeLoadContextOptions,\n LoaderFnContext,\n SsrContextOptions,\n} from './route'\nimport type { AnyRouteMatch, MakeRouteMatch } from './Matches'\nimport type { AnyRouter, UpdateMatchFn } from './router'\n\n/**\n * An object of this shape is created when calling `loadMatches`.\n * It contains everything we need for all other functions in this file\n * to work. (It's basically the function's argument, plus a few mutable states)\n */\ntype InnerLoadContext = {\n /** the calling router instance */\n router: AnyRouter\n location: ParsedLocation\n /** mutable state, scoped to a `loadMatches` call */\n firstBadMatchIndex?: number\n /** mutable state, scoped to a `loadMatches` call */\n rendered?: boolean\n updateMatch: UpdateMatchFn\n matches: Array<AnyRouteMatch>\n preload?: boolean\n onReady?: () => Promise<void>\n sync?: boolean\n /** mutable state, scoped to a `loadMatches` call */\n matchPromises: Array<Promise<AnyRouteMatch>>\n}\n\nconst triggerOnReady = (inner: InnerLoadContext): void | Promise<void> => {\n if (!inner.rendered) {\n inner.rendered = true\n return inner.onReady?.()\n }\n}\n\nconst resolvePreload = (inner: InnerLoadContext, matchId: string): boolean => {\n return !!(\n inner.preload && !inner.router.state.matches.some((d) => d.id === matchId)\n )\n}\n\nconst _handleNotFound = (inner: InnerLoadContext, err: NotFoundError) => {\n // Find the route that should handle the not found error\n // First check if a specific route is requested to show the error\n const routeCursor =\n inner.router.routesById[err.routeId ?? ''] ?? inner.router.routeTree\n\n // Ensure a NotFoundComponent exists on the route\n if (\n !routeCursor.options.notFoundComponent &&\n (inner.router.options as any)?.defaultNotFoundComponent\n ) {\n routeCursor.options.notFoundComponent = (\n inner.router.options as any\n ).defaultNotFoundComponent\n }\n\n // Ensure we have a notFoundComponent\n invariant(\n routeCursor.options.notFoundComponent,\n 'No notFoundComponent found. Please set a notFoundComponent on your route or provide a defaultNotFoundComponent to the router.',\n )\n\n // Find the match for this route\n const matchForRoute = inner.matches.find((m) => m.routeId === routeCursor.id)\n\n invariant(matchForRoute, 'Could not find match for route: ' + routeCursor.id)\n\n // Assign the error to the match - using non-null assertion since we've checked with invariant\n inner.updateMatch(matchForRoute.id, (prev) => ({\n ...prev,\n status: 'notFound',\n error: err,\n isFetching: false,\n }))\n\n if ((err as any).routerCode === 'BEFORE_LOAD' && routeCursor.parentRoute) {\n err.routeId = routeCursor.parentRoute.id\n _handleNotFound(inner, err)\n }\n}\n\nconst handleRedirectAndNotFound = (\n inner: InnerLoadContext,\n match: AnyRouteMatch | undefined,\n err: unknown,\n): void => {\n if (!isRedirect(err) && !isNotFound(err)) return\n\n if (isRedirect(err) && err.redirectHandled && !err.options.reloadDocument) {\n throw err\n }\n\n // in case of a redirecting match during preload, the match does not exist\n if (match) {\n match._nonReactive.beforeLoadPromise?.resolve()\n match._nonReactive.loaderPromise?.resolve()\n match._nonReactive.beforeLoadPromise = undefined\n match._nonReactive.loaderPromise = undefined\n\n const status = isRedirect(err) ? 'redirected' : 'notFound'\n\n inner.updateMatch(match.id, (prev) => ({\n ...prev,\n status,\n isFetching: false,\n error: err,\n }))\n\n if (isNotFound(err) && !err.routeId) {\n err.routeId = match.routeId\n }\n\n match._nonReactive.loadPromise?.resolve()\n }\n\n if (isRedirect(err)) {\n inner.rendered = true\n err.options._fromLocation = inner.location\n err.redirectHandled = true\n err = inner.router.resolveRedirect(err)\n throw err\n } else {\n _handleNotFound(inner, err)\n throw err\n }\n}\n\nconst shouldSkipLoader = (\n inner: InnerLoadContext,\n matchId: string,\n): boolean => {\n const match = inner.router.getMatch(matchId)!\n // upon hydration, we skip the loader if the match has been dehydrated on the server\n if (!inner.router.isServer && match._nonReactive.dehydrated) {\n return true\n }\n\n if (inner.router.isServer) {\n if (match.ssr === false) {\n return true\n }\n }\n return false\n}\n\nconst handleSerialError = (\n inner: InnerLoadContext,\n index: number,\n err: any,\n routerCode: string,\n): void => {\n const { id: matchId, routeId } = inner.matches[index]!\n const route = inner.router.looseRoutesById[routeId]!\n\n // Much like suspense, we use a promise here to know if\n // we've been outdated by a new loadMatches call and\n // should abort the current async operation\n if (err instanceof Promise) {\n throw err\n }\n\n err.routerCode = routerCode\n inner.firstBadMatchIndex ??= index\n handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err)\n\n try {\n route.options.onError?.(err)\n } catch (errorHandlerErr) {\n err = errorHandlerErr\n handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err)\n }\n\n inner.updateMatch(matchId, (prev) => {\n prev._nonReactive.beforeLoadPromise?.resolve()\n prev._nonReactive.beforeLoadPromise = undefined\n prev._nonReactive.loadPromise?.resolve()\n\n return {\n ...prev,\n error: err,\n status: 'error',\n isFetching: false,\n updatedAt: Date.now(),\n abortController: new AbortController(),\n }\n })\n}\n\nconst isBeforeLoadSsr = (\n inner: InnerLoadContext,\n matchId: string,\n index: number,\n route: AnyRoute,\n): void | Promise<void> => {\n const existingMatch = inner.router.getMatch(matchId)!\n const parentMatchId = inner.matches[index - 1]?.id\n const parentMatch = parentMatchId\n ? inner.router.getMatch(parentMatchId)!\n : undefined\n\n // in SPA mode, only SSR the root route\n if (inner.router.isShell()) {\n existingMatch.ssr = matchId === rootRouteId\n return\n }\n\n if (parentMatch?.ssr === false) {\n existingMatch.ssr = false\n return\n }\n\n const parentOverride = (tempSsr: boolean | 'data-only') => {\n if (tempSsr === true && parentMatch?.ssr === 'data-only') {\n return 'data-only'\n }\n return tempSsr\n }\n\n const defaultSsr = inner.router.options.defaultSsr ?? true\n\n if (route.options.ssr === undefined) {\n existingMatch.ssr = parentOverride(defaultSsr)\n return\n }\n\n if (typeof route.options.ssr !== 'function') {\n existingMatch.ssr = parentOverride(route.options.ssr)\n return\n }\n const { search, params } = existingMatch\n\n const ssrFnContext: SsrContextOptions<any, any, any> = {\n search: makeMaybe(search, existingMatch.searchError),\n params: makeMaybe(params, existingMatch.paramsError),\n location: inner.location,\n matches: inner.matches.map((match) => ({\n index: match.index,\n pathname: match.pathname,\n fullPath: match.fullPath,\n staticData: match.staticData,\n id: match.id,\n routeId: match.routeId,\n search: makeMaybe(match.search, match.searchError),\n params: makeMaybe(match.params, match.paramsError),\n ssr: match.ssr,\n })),\n }\n\n const tempSsr = route.options.ssr(ssrFnContext)\n if (isPromise(tempSsr)) {\n return tempSsr.then((ssr) => {\n existingMatch.ssr = parentOverride(ssr ?? defaultSsr)\n })\n }\n\n existingMatch.ssr = parentOverride(tempSsr ?? defaultSsr)\n return\n}\n\nconst setupPendingTimeout = (\n inner: InnerLoadContext,\n matchId: string,\n route: AnyRoute,\n match: AnyRouteMatch,\n): void => {\n if (match._nonReactive.pendingTimeout !== undefined) return\n\n const pendingMs =\n route.options.pendingMs ?? inner.router.options.defaultPendingMs\n const shouldPending = !!(\n inner.onReady &&\n !inner.router.isServer &&\n !resolvePreload(inner, matchId) &&\n (route.options.loader ||\n route.options.beforeLoad ||\n routeNeedsPreload(route)) &&\n typeof pendingMs === 'number' &&\n pendingMs !== Infinity &&\n (route.options.pendingComponent ??\n (inner.router.options as any)?.defaultPendingComponent)\n )\n\n if (shouldPending) {\n const pendingTimeout = setTimeout(() => {\n // Update the match and prematurely resolve the loadMatches promise so that\n // the pending component can start rendering\n triggerOnReady(inner)\n }, pendingMs)\n match._nonReactive.pendingTimeout = pendingTimeout\n }\n}\n\nconst shouldExecuteBeforeLoad = (\n inner: InnerLoadContext,\n matchId: string,\n route: AnyRoute,\n): boolean | Promise<boolean> => {\n const existingMatch = inner.router.getMatch(matchId)!\n\n // If we are in the middle of a load, either of these will be present\n // (not to be confused with `loadPromise`, which is always defined)\n if (\n !existingMatch._nonReactive.beforeLoadPromise &&\n !existingMatch._nonReactive.loaderPromise\n )\n return true\n\n setupPendingTimeout(inner, matchId, route, existingMatch)\n\n const then = () => {\n let result = true\n const match = inner.router.getMatch(matchId)!\n if (match.status === 'error') {\n result = true\n } else if (\n match.preload &&\n (match.status === 'redirected' || match.status === 'notFound')\n ) {\n handleRedirectAndNotFound(inner, match, match.error)\n }\n return result\n }\n\n // Wait for the beforeLoad to resolve before we continue\n return existingMatch._nonReactive.beforeLoadPromise\n ? existingMatch._nonReactive.beforeLoadPromise.then(then)\n : then()\n}\n\nconst executeBeforeLoad = (\n inner: InnerLoadContext,\n matchId: string,\n index: number,\n route: AnyRoute,\n): void | Promise<void> => {\n const match = inner.router.getMatch(matchId)!\n\n // explicitly capture the previous loadPromise\n const prevLoadPromise = match._nonReactive.loadPromise\n match._nonReactive.loadPromise = createControlledPromise<void>(() => {\n prevLoadPromise?.resolve()\n })\n\n const { paramsError, searchError } = match\n\n if (paramsError) {\n handleSerialError(inner, index, paramsError, 'PARSE_PARAMS')\n }\n\n if (searchError) {\n handleSerialError(inner, index, searchError, 'VALIDATE_SEARCH')\n }\n\n setupPendingTimeout(inner, matchId, route, match)\n\n const abortController = new AbortController()\n\n const parentMatchId = inner.matches[index - 1]?.id\n const parentMatch = parentMatchId\n ? inner.router.getMatch(parentMatchId)!\n : undefined\n const parentMatchContext =\n parentMatch?.context ?? inner.router.options.context ?? undefined\n\n const context = { ...parentMatchContext, ...match.__routeContext }\n\n let isPending = false\n const pending = () => {\n if (isPending) return\n isPending = true\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: 'beforeLoad',\n fetchCount: prev.fetchCount + 1,\n abortController,\n context,\n }))\n }\n\n const resolve = () => {\n match._nonReactive.beforeLoadPromise?.resolve()\n match._nonReactive.beforeLoadPromise = undefined\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: false,\n }))\n }\n\n // if there is no `beforeLoad` option, skip everything, batch update the store, return early\n if (!route.options.beforeLoad) {\n batch(() => {\n pending()\n resolve()\n })\n return\n }\n\n match._nonReactive.beforeLoadPromise = createControlledPromise<void>()\n\n const { search, params, cause } = match\n const preload = resolvePreload(inner, matchId)\n const beforeLoadFnContext: BeforeLoadContextOptions<any, any, any, any, any> =\n {\n search,\n abortController,\n params,\n preload,\n context,\n location: inner.location,\n navigate: (opts: any) =>\n inner.router.navigate({\n ...opts,\n _fromLocation: inner.location,\n }),\n buildLocation: inner.router.buildLocation,\n cause: preload ? 'preload' : cause,\n matches: inner.matches,\n }\n\n const updateContext = (beforeLoadContext: any) => {\n if (beforeLoadContext === undefined) {\n batch(() => {\n pending()\n resolve()\n })\n return\n }\n if (isRedirect(beforeLoadContext) || isNotFound(beforeLoadContext)) {\n pending()\n handleSerialError(inner, index, beforeLoadContext, 'BEFORE_LOAD')\n }\n\n batch(() => {\n pending()\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n __beforeLoadContext: beforeLoadContext,\n context: {\n ...prev.context,\n ...beforeLoadContext,\n },\n }))\n resolve()\n })\n }\n\n let beforeLoadContext\n try {\n beforeLoadContext = route.options.beforeLoad(beforeLoadFnContext)\n if (isPromise(beforeLoadContext)) {\n pending()\n return beforeLoadContext\n .catch((err) => {\n handleSerialError(inner, index, err, 'BEFORE_LOAD')\n })\n .then(updateContext)\n }\n } catch (err) {\n pending()\n handleSerialError(inner, index, err, 'BEFORE_LOAD')\n }\n\n updateContext(beforeLoadContext)\n return\n}\n\nconst handleBeforeLoad = (\n inner: InnerLoadContext,\n index: number,\n): void | Promise<void> => {\n const { id: matchId, routeId } = inner.matches[index]!\n const route = inner.router.looseRoutesById[routeId]!\n\n const serverSsr = () => {\n // on the server, determine whether SSR the current match or not\n if (inner.router.isServer) {\n const maybePromise = isBeforeLoadSsr(inner, matchId, index, route)\n if (isPromise(maybePromise)) return maybePromise.then(queueExecution)\n }\n return queueExecution()\n }\n\n const queueExecution = () => {\n if (shouldSkipLoader(inner, matchId)) return\n const shouldExecuteBeforeLoadResult = shouldExecuteBeforeLoad(\n inner,\n matchId,\n route,\n )\n return isPromise(shouldExecuteBeforeLoadResult)\n ? shouldExecuteBeforeLoadResult.then(execute)\n : execute(shouldExecuteBeforeLoadResult)\n }\n\n const execute = (shouldExec: boolean) => {\n if (shouldExec) {\n // If we are not in the middle of a load OR the previous load failed, start it\n return executeBeforeLoad(inner, matchId, index, route)\n }\n return\n }\n\n return serverSsr()\n}\n\nconst executeHead = (\n inner: InnerLoadContext,\n matchId: string,\n route: AnyRoute,\n): void | Promise<\n Pick<\n AnyRouteMatch,\n 'meta' | 'links' | 'headScripts' | 'headers' | 'scripts' | 'styles'\n >\n> => {\n const match = inner.router.getMatch(matchId)\n // in case of a redirecting match during preload, the match does not exist\n if (!match) {\n return\n }\n if (!route.options.head && !route.options.scripts && !route.options.headers) {\n return\n }\n const assetContext = {\n matches: inner.matches,\n match,\n params: match.params,\n loaderData: match.loaderData,\n }\n\n return Promise.all([\n route.options.head?.(assetContext),\n route.options.scripts?.(assetContext),\n route.options.headers?.(assetContext),\n ]).then(([headFnContent, scripts, headers]) => {\n const meta = headFnContent?.meta\n const links = headFnContent?.links\n const headScripts = headFnContent?.scripts\n const styles = headFnContent?.styles\n\n return {\n meta,\n links,\n headScripts,\n headers,\n scripts,\n styles,\n }\n })\n}\n\nconst getLoaderContext = (\n inner: InnerLoadContext,\n matchId: string,\n index: number,\n route: AnyRoute,\n): LoaderFnContext => {\n const parentMatchPromise = inner.matchPromises[index - 1] as any\n const { params, loaderDeps, abortController, context, cause } =\n inner.router.getMatch(matchId)!\n\n const preload = resolvePreload(inner, matchId)\n\n return {\n params,\n deps: loaderDeps,\n preload: !!preload,\n parentMatchPromise,\n abortController,\n context,\n location: inner.location,\n navigate: (opts) =>\n inner.router.navigate({\n ...opts,\n _fromLocation: inner.location,\n }),\n cause: preload ? 'preload' : cause,\n route,\n }\n}\n\nconst runLoader = async (\n inner: InnerLoadContext,\n matchId: string,\n index: number,\n route: AnyRoute,\n): Promise<void> => {\n try {\n // If the Matches component rendered\n // the pending component and needs to show it for\n // a minimum duration, we''ll wait for it to resolve\n // before committing to the match and resolving\n // the loadPromise\n\n const match = inner.router.getMatch(matchId)!\n\n // Actually run the loader and handle the result\n try {\n if (!inner.router.isServer || match.ssr === true) {\n loadRouteChunk(route)\n }\n\n // Kick off the loader!\n const loaderResult = route.options.loader?.(\n getLoaderContext(inner, matchId, index, route),\n )\n const loaderResultIsPromise =\n route.options.loader && isPromise(loaderResult)\n\n const willLoadSomething = !!(\n loaderResultIsPromise ||\n route._lazyPromise ||\n route._componentsPromise ||\n route.options.head ||\n route.options.scripts ||\n route.options.headers ||\n match._nonReactive.minPendingPromise\n )\n\n if (willLoadSomething) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: 'loader',\n }))\n }\n\n if (route.options.loader) {\n const loaderData = loaderResultIsPromise\n ? await loaderResult\n : loaderResult\n\n handleRedirectAndNotFound(\n inner,\n inner.router.getMatch(matchId),\n loaderData,\n )\n if (loaderData !== undefined) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n loaderData,\n }))\n }\n }\n\n // Lazy option can modify the route options,\n // so we need to wait for it to resolve before\n // we can use the options\n if (route._lazyPromise) await route._lazyPromise\n const headResult = executeHead(inner, matchId, route)\n const head = headResult ? await headResult : undefined\n const pendingPromise = match._nonReactive.minPendingPromise\n if (pendingPromise) await pendingPromise\n\n // Last but not least, wait for the the components\n // to be preloaded before we resolve the match\n if (route._componentsPromise) await route._componentsPromise\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n error: undefined,\n status: 'success',\n isFetching: false,\n updatedAt: Date.now(),\n ...head,\n }))\n } catch (e) {\n let error = e\n\n const pendingPromise = match._nonReactive.minPendingPromise\n if (pendingPromise) await pendingPromise\n\n handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), e)\n\n try {\n route.options.onError?.(e)\n } catch (onErrorError) {\n error = onErrorError\n handleRedirectAndNotFound(\n inner,\n inner.router.getMatch(matchId),\n onErrorError,\n )\n }\n const headResult = executeHead(inner, matchId, route)\n const head = headResult ? await headResult : undefined\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n error,\n status: 'error',\n isFetching: false,\n ...head,\n }))\n }\n } catch (err) {\n const match = inner.router.getMatch(matchId)\n // in case of a redirecting match during preload, the match does not exist\n if (match) {\n const headResult = executeHead(inner, matchId, route)\n if (headResult) {\n const head = await headResult\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n ...head,\n }))\n }\n match._nonReactive.loaderPromise = undefined\n }\n handleRedirectAndNotFound(inner, match, err)\n }\n}\n\nconst loadRouteMatch = async (\n inner: InnerLoadContext,\n index: number,\n): Promise<AnyRouteMatch> => {\n const { id: matchId, routeId } = inner.matches[index]!\n let loaderShouldRunAsync = false\n let loaderIsRunningAsync = false\n const route = inner.router.looseRoutesById[routeId]!\n\n if (shouldSkipLoader(inner, matchId)) {\n if (inner.router.isServer) {\n const headResult = executeHead(inner, matchId, route)\n if (headResult) {\n const head = await headResult\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n ...head,\n }))\n }\n return inner.router.getMatch(matchId)!\n }\n } else {\n const prevMatch = inner.router.getMatch(matchId)!\n // there is a loaderPromise, so we are in the middle of a load\n if (prevMatch._nonReactive.loaderPromise) {\n // do not block if we already have stale data we can show\n // but only if the ongoing load is not a preload since error handling is different for preloads\n // and we don't want to swallow errors\n if (prevMatch.status === 'success' && !inner.sync && !prevMatch.preload) {\n return prevMatch\n }\n await prevMatch._nonReactive.loaderPromise\n const match = inner.router.getMatch(matchId)!\n if (match.error) {\n handleRedirectAndNotFound(inner, match, match.error)\n }\n } else {\n // This is where all of the stale-while-revalidate magic happens\n const age = Date.now() - prevMatch.updatedAt\n\n const preload = resolvePreload(inner, matchId)\n\n const staleAge = preload\n ? (route.options.preloadStaleTime ??\n inner.router.options.defaultPreloadStaleTime ??\n 30_000) // 30 seconds for preloads by default\n : (route.options.staleTime ??\n inner.router.options.defaultStaleTime ??\n 0)\n\n const shouldReloadOption = route.options.shouldReload\n\n // Default to reloading the route all the time\n // Allow shouldReload to get the last say,\n // if provided.\n const shouldReload =\n typeof shouldReloadOption === 'function'\n ? shouldReloadOption(getLoaderContext(inner, matchId, index, route))\n : shouldReloadOption\n\n const nextPreload =\n !!preload && !inner.router.state.matches.some((d) => d.id === matchId)\n const match = inner.router.getMatch(matchId)!\n match._nonReactive.loaderPromise = createControlledPromise<void>()\n if (nextPreload !== match.preload) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n preload: nextPreload,\n }))\n }\n\n // If the route is successful and still fresh, just resolve\n const { status, invalid } = match\n loaderShouldRunAsync =\n status === 'success' && (invalid || (shouldReload ?? age > staleAge))\n if (preload && route.options.preload === false) {\n // Do nothing\n } else if (loaderShouldRunAsync && !inner.sync) {\n loaderIsRunningAsync = true\n ;(async () => {\n try {\n await runLoader(inner, matchId, index, route)\n const match = inner.router.getMatch(matchId)!\n match._nonReactive.loaderPromise?.resolve()\n match._nonReactive.loadPromise?.resolve()\n match._nonReactive.loaderPromise = undefined\n } catch (err) {\n if (isRedirect(err)) {\n await inner.router.navigate(err.options)\n }\n }\n })()\n } else if (status !== 'success' || (loaderShouldRunAsync && inner.sync)) {\n await runLoader(inner, matchId, index, route)\n } else {\n // if the loader did not run, still update head.\n // reason: parent's beforeLoad may have changed the route context\n // and only now do we know the route context (and that the loader would not run)\n const headResult = executeHead(inner, matchId, route)\n if (headResult) {\n const head = await headResult\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n ...head,\n }))\n }\n }\n }\n }\n const match = inner.router.getMatch(matchId)!\n if (!loaderIsRunningAsync) {\n match._nonReactive.loaderPromise?.resolve()\n match._nonReactive.loadPromise?.resolve()\n }\n\n clearTimeout(match._nonReactive.pendingTimeout)\n match._nonReactive.pendingTimeout = undefined\n if (!loaderIsRunningAsync) match._nonReactive.loaderPromise = undefined\n match._nonReactive.dehydrated = undefined\n const nextIsFetching = loaderIsRunningAsync ? match.isFetching : false\n if (nextIsFetching !== match.isFetching || match.invalid !== false) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: nextIsFetching,\n invalid: false,\n }))\n return inner.router.getMatch(matchId)!\n } else {\n return match\n }\n}\n\nexport async function loadMatches(arg: {\n router: AnyRouter\n location: ParsedLocation\n matches: Array<AnyRouteMatch>\n preload?: boolean\n onReady?: () => Promise<void>\n updateMatch: UpdateMatchFn\n sync?: boolean\n}): Promise<Array<MakeRouteMatch>> {\n const inner: InnerLoadContext = Object.assign(arg, {\n matchPromises: [],\n })\n\n // make sure the pending component is immediately rendered when hydrating a match that is not SSRed\n // the pending component was already rendered on the server and we want to keep it shown on the client until minPendingMs is reached\n if (\n !inner.router.isServer &&\n inner.router.state.matches.some((d) => d._forcePending)\n ) {\n triggerOnReady(inner)\n }\n\n try {\n // Execute all beforeLoads one by one\n for (let i = 0; i < inner.matches.length; i++) {\n const beforeLoad = handleBeforeLoad(inner, i)\n if (isPromise(beforeLoad)) await beforeLoad\n }\n\n // Execute all loaders in parallel\n const max = inner.firstBadMatchIndex ?? inner.matches.length\n for (let i = 0; i < max; i++) {\n inner.matchPromises.push(loadRouteMatch(inner, i))\n }\n await Promise.all(inner.matchPromises)\n\n const readyPromise = triggerOnReady(inner)\n if (isPromise(readyPromise)) await readyPromise\n } catch (err) {\n if (isNotFound(err) && !inner.preload) {\n const readyPromise = triggerOnReady(inner)\n if (isPromise(readyPromise)) await readyPromise\n throw err\n }\n if (isRedirect(err)) {\n throw err\n }\n }\n\n return inner.matches\n}\n\nexport async function loadRouteChunk(route: AnyRoute) {\n if (!route._lazyLoaded && route._lazyPromise === undefined) {\n if (route.lazyFn) {\n route._lazyPromise = route.lazyFn().then((lazyRoute) => {\n // explicitly don't copy over the lazy route's id\n const { id: _id, ...options } = lazyRoute.options\n Object.assign(route.options, options)\n route._lazyLoaded = true\n route._lazyPromise = undefined // gc promise, we won't need it anymore\n })\n } else {\n route._lazyLoaded = true\n }\n }\n\n // If for some reason lazy resolves more lazy components...\n // We'll wait for that before we attempt to preload the\n // components themselves.\n if (!route._componentsLoaded && route._componentsPromise === undefined) {\n const loadComponents = () => {\n const preloads = []\n for (const type of componentTypes) {\n const preload = (route.options[type] as any)?.preload\n if (preload) preloads.push(preload())\n }\n if (preloads.length)\n return Promise.all(preloads).then(() => {\n route._componentsLoaded = true\n route._componentsPromise = undefined // gc promise, we won't need it anymore\n })\n route._componentsLoaded = true\n route._componentsPromise = undefined // gc promise, we won't need it anymore\n return\n }\n route._componentsPromise = route._lazyPromise\n ? route._lazyPromise.then(loadComponents)\n : loadComponents()\n }\n return route._componentsPromise\n}\n\nfunction makeMaybe<TValue, TError>(\n value: TValue,\n error: TError,\n): { status: 'success'; value: TValue } | { status: 'error'; error: TError } {\n if (error) {\n return { status: 'error' as const, error }\n }\n return { status: 'success' as const, value }\n}\n\nexport function routeNeedsPreload(route: AnyRoute) {\n for (const componentType of componentTypes) {\n if ((route.options[componentType] as any)?.preload) {\n return true\n }\n }\n return false\n}\n\nexport const componentTypes = [\n 'component',\n 'errorComponent',\n 'pendingComponent',\n 'notFoundComponent',\n] as const\n"],"names":["_a","_b","tempSsr","beforeLoadContext","match"],"mappings":";;;;;;AAuCA,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AAC,cAAc;AAEtD,cAAM,EAAE,IAAI,KAAK,GAAG,YAAY,UAAU;AACnC,eAAA,OAAO,MAAM,SAAS,OAAO;AACpC,cAAM,cAAc;AACpB,cAAM,eAAe;AAAA,MAAA,CACtB;AAAA,IAAA,OACI;AACL,YAAM,cAAc;AAAA,IAAA;AAAA,EACtB;AAMF,MAAI,CAAC,MAAM,qBAAqB,MAAM,uBAAuB,QAAW;AACtE,UAAM,iBAAiB,MAAM;;AAC3B,YAAM,WAAW,CAAC;AAClB,iBAAW,QAAQ,gBAAgB;AACjC,cAAM,WAAW,WAAM,QAAQ,IAAI,MAAlB,mBAA6B;AAC9C,YAAI,QAAS,UAAS,KAAK,QAAA,CAAS;AAAA,MAAA;AAEtC,UAAI,SAAS;AACX,eAAO,QAAQ,IAAI,QAAQ,EAAE,KAAK,MAAM;AACtC,gBAAM,oBAAoB;AAC1B,gBAAM,qBAAqB;AAAA,QAAA,CAC5B;AACH,YAAM,oBAAoB;AAC1B,YAAM,qBAAqB;AAC3B;AAAA,IACF;AACM,UAAA,qBAAqB,MAAM,eAC7B,MAAM,aAAa,KAAK,cAAc,IACtC,eAAe;AAAA,EAAA;AAErB,SAAO,MAAM;AACf;AAEA,SAAS,UACP,OACA,OAC2E;AAC3E,MAAI,OAAO;AACF,WAAA,EAAE,QAAQ,SAAkB,MAAM;AAAA,EAAA;AAEpC,SAAA,EAAE,QAAQ,WAAoB,MAAM;AAC7C;AAEO,SAAS,kBAAkB,OAAiB;;AACjD,aAAW,iBAAiB,gBAAgB;AAC1C,SAAK,WAAM,QAAQ,aAAa,MAA3B,mBAAsC,SAAS;AAC3C,aAAA;AAAA,IAAA;AAAA,EACT;AAEK,SAAA;AACT;AAEO,MAAM,iBAAiB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;"}
1
+ {"version":3,"file":"load-matches.js","sources":["../../src/load-matches.ts"],"sourcesContent":["import { batch } from '@tanstack/store'\nimport invariant from 'tiny-invariant'\nimport { createControlledPromise, isPromise } from './utils'\nimport { isNotFound } from './not-found'\nimport { rootRouteId } from './root'\nimport { isRedirect } from './redirect'\nimport type { NotFoundError } from './not-found'\nimport type { ParsedLocation } from './location'\nimport type {\n AnyRoute,\n BeforeLoadContextOptions,\n LoaderFnContext,\n SsrContextOptions,\n} from './route'\nimport type { AnyRouteMatch, MakeRouteMatch } from './Matches'\nimport type { AnyRouter, UpdateMatchFn } from './router'\n\n/**\n * An object of this shape is created when calling `loadMatches`.\n * It contains everything we need for all other functions in this file\n * to work. (It's basically the function's argument, plus a few mutable states)\n */\ntype InnerLoadContext = {\n /** the calling router instance */\n router: AnyRouter\n location: ParsedLocation\n /** mutable state, scoped to a `loadMatches` call */\n firstBadMatchIndex?: number\n /** mutable state, scoped to a `loadMatches` call */\n rendered?: boolean\n updateMatch: UpdateMatchFn\n matches: Array<AnyRouteMatch>\n preload?: boolean\n onReady?: () => Promise<void>\n sync?: boolean\n /** mutable state, scoped to a `loadMatches` call */\n matchPromises: Array<Promise<AnyRouteMatch>>\n}\n\nconst triggerOnReady = (inner: InnerLoadContext): void | Promise<void> => {\n if (!inner.rendered) {\n inner.rendered = true\n return inner.onReady?.()\n }\n}\n\nconst resolvePreload = (inner: InnerLoadContext, matchId: string): boolean => {\n return !!(\n inner.preload && !inner.router.state.matches.some((d) => d.id === matchId)\n )\n}\n\nconst _handleNotFound = (inner: InnerLoadContext, err: NotFoundError) => {\n // Find the route that should handle the not found error\n // First check if a specific route is requested to show the error\n const routeCursor =\n inner.router.routesById[err.routeId ?? ''] ?? inner.router.routeTree\n\n // Ensure a NotFoundComponent exists on the route\n if (\n !routeCursor.options.notFoundComponent &&\n (inner.router.options as any)?.defaultNotFoundComponent\n ) {\n routeCursor.options.notFoundComponent = (\n inner.router.options as any\n ).defaultNotFoundComponent\n }\n\n // Ensure we have a notFoundComponent\n invariant(\n routeCursor.options.notFoundComponent,\n 'No notFoundComponent found. Please set a notFoundComponent on your route or provide a defaultNotFoundComponent to the router.',\n )\n\n // Find the match for this route\n const matchForRoute = inner.matches.find((m) => m.routeId === routeCursor.id)\n\n invariant(matchForRoute, 'Could not find match for route: ' + routeCursor.id)\n\n // Assign the error to the match - using non-null assertion since we've checked with invariant\n inner.updateMatch(matchForRoute.id, (prev) => ({\n ...prev,\n status: 'notFound',\n error: err,\n isFetching: false,\n }))\n\n if ((err as any).routerCode === 'BEFORE_LOAD' && routeCursor.parentRoute) {\n err.routeId = routeCursor.parentRoute.id\n _handleNotFound(inner, err)\n }\n}\n\nconst handleRedirectAndNotFound = (\n inner: InnerLoadContext,\n match: AnyRouteMatch | undefined,\n err: unknown,\n): void => {\n if (!isRedirect(err) && !isNotFound(err)) return\n\n if (isRedirect(err) && err.redirectHandled && !err.options.reloadDocument) {\n throw err\n }\n\n // in case of a redirecting match during preload, the match does not exist\n if (match) {\n match._nonReactive.beforeLoadPromise?.resolve()\n match._nonReactive.loaderPromise?.resolve()\n match._nonReactive.beforeLoadPromise = undefined\n match._nonReactive.loaderPromise = undefined\n\n const status = isRedirect(err) ? 'redirected' : 'notFound'\n\n inner.updateMatch(match.id, (prev) => ({\n ...prev,\n status,\n isFetching: false,\n error: err,\n }))\n\n if (isNotFound(err) && !err.routeId) {\n err.routeId = match.routeId\n }\n\n match._nonReactive.loadPromise?.resolve()\n }\n\n if (isRedirect(err)) {\n inner.rendered = true\n err.options._fromLocation = inner.location\n err.redirectHandled = true\n err = inner.router.resolveRedirect(err)\n throw err\n } else {\n _handleNotFound(inner, err)\n throw err\n }\n}\n\nconst shouldSkipLoader = (\n inner: InnerLoadContext,\n matchId: string,\n): boolean => {\n const match = inner.router.getMatch(matchId)!\n // upon hydration, we skip the loader if the match has been dehydrated on the server\n if (!inner.router.isServer && match._nonReactive.dehydrated) {\n return true\n }\n\n if (inner.router.isServer && match.ssr === false) {\n return true\n }\n\n return false\n}\n\nconst handleSerialError = (\n inner: InnerLoadContext,\n index: number,\n err: any,\n routerCode: string,\n): void => {\n const { id: matchId, routeId } = inner.matches[index]!\n const route = inner.router.looseRoutesById[routeId]!\n\n // Much like suspense, we use a promise here to know if\n // we've been outdated by a new loadMatches call and\n // should abort the current async operation\n if (err instanceof Promise) {\n throw err\n }\n\n err.routerCode = routerCode\n inner.firstBadMatchIndex ??= index\n handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err)\n\n try {\n route.options.onError?.(err)\n } catch (errorHandlerErr) {\n err = errorHandlerErr\n handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), err)\n }\n\n inner.updateMatch(matchId, (prev) => {\n prev._nonReactive.beforeLoadPromise?.resolve()\n prev._nonReactive.beforeLoadPromise = undefined\n prev._nonReactive.loadPromise?.resolve()\n\n return {\n ...prev,\n error: err,\n status: 'error',\n isFetching: false,\n updatedAt: Date.now(),\n abortController: new AbortController(),\n }\n })\n}\n\nconst isBeforeLoadSsr = (\n inner: InnerLoadContext,\n matchId: string,\n index: number,\n route: AnyRoute,\n): void | Promise<void> => {\n const existingMatch = inner.router.getMatch(matchId)!\n const parentMatchId = inner.matches[index - 1]?.id\n const parentMatch = parentMatchId\n ? inner.router.getMatch(parentMatchId)!\n : undefined\n\n // in SPA mode, only SSR the root route\n if (inner.router.isShell()) {\n existingMatch.ssr = matchId === rootRouteId\n return\n }\n\n if (parentMatch?.ssr === false) {\n existingMatch.ssr = false\n return\n }\n\n const parentOverride = (tempSsr: boolean | 'data-only') => {\n if (tempSsr === true && parentMatch?.ssr === 'data-only') {\n return 'data-only'\n }\n return tempSsr\n }\n\n const defaultSsr = inner.router.options.defaultSsr ?? true\n\n if (route.options.ssr === undefined) {\n existingMatch.ssr = parentOverride(defaultSsr)\n return\n }\n\n if (typeof route.options.ssr !== 'function') {\n existingMatch.ssr = parentOverride(route.options.ssr)\n return\n }\n const { search, params } = existingMatch\n\n const ssrFnContext: SsrContextOptions<any, any, any> = {\n search: makeMaybe(search, existingMatch.searchError),\n params: makeMaybe(params, existingMatch.paramsError),\n location: inner.location,\n matches: inner.matches.map((match) => ({\n index: match.index,\n pathname: match.pathname,\n fullPath: match.fullPath,\n staticData: match.staticData,\n id: match.id,\n routeId: match.routeId,\n search: makeMaybe(match.search, match.searchError),\n params: makeMaybe(match.params, match.paramsError),\n ssr: match.ssr,\n })),\n }\n\n const tempSsr = route.options.ssr(ssrFnContext)\n if (isPromise(tempSsr)) {\n return tempSsr.then((ssr) => {\n existingMatch.ssr = parentOverride(ssr ?? defaultSsr)\n })\n }\n\n existingMatch.ssr = parentOverride(tempSsr ?? defaultSsr)\n return\n}\n\nconst setupPendingTimeout = (\n inner: InnerLoadContext,\n matchId: string,\n route: AnyRoute,\n match: AnyRouteMatch,\n): void => {\n if (match._nonReactive.pendingTimeout !== undefined) return\n\n const pendingMs =\n route.options.pendingMs ?? inner.router.options.defaultPendingMs\n const shouldPending = !!(\n inner.onReady &&\n !inner.router.isServer &&\n !resolvePreload(inner, matchId) &&\n (route.options.loader ||\n route.options.beforeLoad ||\n routeNeedsPreload(route)) &&\n typeof pendingMs === 'number' &&\n pendingMs !== Infinity &&\n (route.options.pendingComponent ??\n (inner.router.options as any)?.defaultPendingComponent)\n )\n\n if (shouldPending) {\n const pendingTimeout = setTimeout(() => {\n // Update the match and prematurely resolve the loadMatches promise so that\n // the pending component can start rendering\n triggerOnReady(inner)\n }, pendingMs)\n match._nonReactive.pendingTimeout = pendingTimeout\n }\n}\n\nconst preBeforeLoadSetup = (\n inner: InnerLoadContext,\n matchId: string,\n route: AnyRoute,\n): void | Promise<void> => {\n const existingMatch = inner.router.getMatch(matchId)!\n\n // If we are in the middle of a load, either of these will be present\n // (not to be confused with `loadPromise`, which is always defined)\n if (\n !existingMatch._nonReactive.beforeLoadPromise &&\n !existingMatch._nonReactive.loaderPromise\n )\n return\n\n setupPendingTimeout(inner, matchId, route, existingMatch)\n\n const then = () => {\n const match = inner.router.getMatch(matchId)!\n if (\n match.preload &&\n (match.status === 'redirected' || match.status === 'notFound')\n ) {\n handleRedirectAndNotFound(inner, match, match.error)\n }\n }\n\n // Wait for the previous beforeLoad to resolve before we continue\n return existingMatch._nonReactive.beforeLoadPromise\n ? existingMatch._nonReactive.beforeLoadPromise.then(then)\n : then()\n}\n\nconst executeBeforeLoad = (\n inner: InnerLoadContext,\n matchId: string,\n index: number,\n route: AnyRoute,\n): void | Promise<void> => {\n const match = inner.router.getMatch(matchId)!\n\n // explicitly capture the previous loadPromise\n const prevLoadPromise = match._nonReactive.loadPromise\n match._nonReactive.loadPromise = createControlledPromise<void>(() => {\n prevLoadPromise?.resolve()\n })\n\n const { paramsError, searchError } = match\n\n if (paramsError) {\n handleSerialError(inner, index, paramsError, 'PARSE_PARAMS')\n }\n\n if (searchError) {\n handleSerialError(inner, index, searchError, 'VALIDATE_SEARCH')\n }\n\n setupPendingTimeout(inner, matchId, route, match)\n\n const abortController = new AbortController()\n\n const parentMatchId = inner.matches[index - 1]?.id\n const parentMatch = parentMatchId\n ? inner.router.getMatch(parentMatchId)!\n : undefined\n const parentMatchContext =\n parentMatch?.context ?? inner.router.options.context ?? undefined\n\n const context = { ...parentMatchContext, ...match.__routeContext }\n\n let isPending = false\n const pending = () => {\n if (isPending) return\n isPending = true\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: 'beforeLoad',\n fetchCount: prev.fetchCount + 1,\n abortController,\n context,\n }))\n }\n\n const resolve = () => {\n match._nonReactive.beforeLoadPromise?.resolve()\n match._nonReactive.beforeLoadPromise = undefined\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: false,\n }))\n }\n\n // if there is no `beforeLoad` option, skip everything, batch update the store, return early\n if (!route.options.beforeLoad) {\n batch(() => {\n pending()\n resolve()\n })\n return\n }\n\n match._nonReactive.beforeLoadPromise = createControlledPromise<void>()\n\n const { search, params, cause } = match\n const preload = resolvePreload(inner, matchId)\n const beforeLoadFnContext: BeforeLoadContextOptions<any, any, any, any, any> =\n {\n search,\n abortController,\n params,\n preload,\n context,\n location: inner.location,\n navigate: (opts: any) =>\n inner.router.navigate({\n ...opts,\n _fromLocation: inner.location,\n }),\n buildLocation: inner.router.buildLocation,\n cause: preload ? 'preload' : cause,\n matches: inner.matches,\n }\n\n const updateContext = (beforeLoadContext: any) => {\n if (beforeLoadContext === undefined) {\n batch(() => {\n pending()\n resolve()\n })\n return\n }\n if (isRedirect(beforeLoadContext) || isNotFound(beforeLoadContext)) {\n pending()\n handleSerialError(inner, index, beforeLoadContext, 'BEFORE_LOAD')\n }\n\n batch(() => {\n pending()\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n __beforeLoadContext: beforeLoadContext,\n context: {\n ...prev.context,\n ...beforeLoadContext,\n },\n }))\n resolve()\n })\n }\n\n let beforeLoadContext\n try {\n beforeLoadContext = route.options.beforeLoad(beforeLoadFnContext)\n if (isPromise(beforeLoadContext)) {\n pending()\n return beforeLoadContext\n .catch((err) => {\n handleSerialError(inner, index, err, 'BEFORE_LOAD')\n })\n .then(updateContext)\n }\n } catch (err) {\n pending()\n handleSerialError(inner, index, err, 'BEFORE_LOAD')\n }\n\n updateContext(beforeLoadContext)\n return\n}\n\nconst handleBeforeLoad = (\n inner: InnerLoadContext,\n index: number,\n): void | Promise<void> => {\n const { id: matchId, routeId } = inner.matches[index]!\n const route = inner.router.looseRoutesById[routeId]!\n\n const serverSsr = () => {\n // on the server, determine whether SSR the current match or not\n if (inner.router.isServer) {\n const maybePromise = isBeforeLoadSsr(inner, matchId, index, route)\n if (isPromise(maybePromise)) return maybePromise.then(queueExecution)\n }\n return queueExecution()\n }\n\n const queueExecution = () => {\n if (shouldSkipLoader(inner, matchId)) return\n const result = preBeforeLoadSetup(inner, matchId, route)\n return isPromise(result) ? result.then(execute) : execute()\n }\n\n const execute = () => executeBeforeLoad(inner, matchId, index, route)\n\n return serverSsr()\n}\n\nconst executeHead = (\n inner: InnerLoadContext,\n matchId: string,\n route: AnyRoute,\n): void | Promise<\n Pick<\n AnyRouteMatch,\n 'meta' | 'links' | 'headScripts' | 'headers' | 'scripts' | 'styles'\n >\n> => {\n const match = inner.router.getMatch(matchId)\n // in case of a redirecting match during preload, the match does not exist\n if (!match) {\n return\n }\n if (!route.options.head && !route.options.scripts && !route.options.headers) {\n return\n }\n const assetContext = {\n matches: inner.matches,\n match,\n params: match.params,\n loaderData: match.loaderData,\n }\n\n return Promise.all([\n route.options.head?.(assetContext),\n route.options.scripts?.(assetContext),\n route.options.headers?.(assetContext),\n ]).then(([headFnContent, scripts, headers]) => {\n const meta = headFnContent?.meta\n const links = headFnContent?.links\n const headScripts = headFnContent?.scripts\n const styles = headFnContent?.styles\n\n return {\n meta,\n links,\n headScripts,\n headers,\n scripts,\n styles,\n }\n })\n}\n\nconst getLoaderContext = (\n inner: InnerLoadContext,\n matchId: string,\n index: number,\n route: AnyRoute,\n): LoaderFnContext => {\n const parentMatchPromise = inner.matchPromises[index - 1] as any\n const { params, loaderDeps, abortController, context, cause } =\n inner.router.getMatch(matchId)!\n\n const preload = resolvePreload(inner, matchId)\n\n return {\n params,\n deps: loaderDeps,\n preload: !!preload,\n parentMatchPromise,\n abortController,\n context,\n location: inner.location,\n navigate: (opts) =>\n inner.router.navigate({\n ...opts,\n _fromLocation: inner.location,\n }),\n cause: preload ? 'preload' : cause,\n route,\n }\n}\n\nconst runLoader = async (\n inner: InnerLoadContext,\n matchId: string,\n index: number,\n route: AnyRoute,\n): Promise<void> => {\n try {\n // If the Matches component rendered\n // the pending component and needs to show it for\n // a minimum duration, we''ll wait for it to resolve\n // before committing to the match and resolving\n // the loadPromise\n\n const match = inner.router.getMatch(matchId)!\n\n // Actually run the loader and handle the result\n try {\n if (!inner.router.isServer || match.ssr === true) {\n loadRouteChunk(route)\n }\n\n // Kick off the loader!\n const loaderResult = route.options.loader?.(\n getLoaderContext(inner, matchId, index, route),\n )\n const loaderResultIsPromise =\n route.options.loader && isPromise(loaderResult)\n\n const willLoadSomething = !!(\n loaderResultIsPromise ||\n route._lazyPromise ||\n route._componentsPromise ||\n route.options.head ||\n route.options.scripts ||\n route.options.headers ||\n match._nonReactive.minPendingPromise\n )\n\n if (willLoadSomething) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: 'loader',\n }))\n }\n\n if (route.options.loader) {\n const loaderData = loaderResultIsPromise\n ? await loaderResult\n : loaderResult\n\n handleRedirectAndNotFound(\n inner,\n inner.router.getMatch(matchId),\n loaderData,\n )\n if (loaderData !== undefined) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n loaderData,\n }))\n }\n }\n\n // Lazy option can modify the route options,\n // so we need to wait for it to resolve before\n // we can use the options\n if (route._lazyPromise) await route._lazyPromise\n const headResult = executeHead(inner, matchId, route)\n const head = headResult ? await headResult : undefined\n const pendingPromise = match._nonReactive.minPendingPromise\n if (pendingPromise) await pendingPromise\n\n // Last but not least, wait for the the components\n // to be preloaded before we resolve the match\n if (route._componentsPromise) await route._componentsPromise\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n error: undefined,\n status: 'success',\n isFetching: false,\n updatedAt: Date.now(),\n ...head,\n }))\n } catch (e) {\n let error = e\n\n const pendingPromise = match._nonReactive.minPendingPromise\n if (pendingPromise) await pendingPromise\n\n handleRedirectAndNotFound(inner, inner.router.getMatch(matchId), e)\n\n try {\n route.options.onError?.(e)\n } catch (onErrorError) {\n error = onErrorError\n handleRedirectAndNotFound(\n inner,\n inner.router.getMatch(matchId),\n onErrorError,\n )\n }\n const headResult = executeHead(inner, matchId, route)\n const head = headResult ? await headResult : undefined\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n error,\n status: 'error',\n isFetching: false,\n ...head,\n }))\n }\n } catch (err) {\n const match = inner.router.getMatch(matchId)\n // in case of a redirecting match during preload, the match does not exist\n if (match) {\n const headResult = executeHead(inner, matchId, route)\n if (headResult) {\n const head = await headResult\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n ...head,\n }))\n }\n match._nonReactive.loaderPromise = undefined\n }\n handleRedirectAndNotFound(inner, match, err)\n }\n}\n\nconst loadRouteMatch = async (\n inner: InnerLoadContext,\n index: number,\n): Promise<AnyRouteMatch> => {\n const { id: matchId, routeId } = inner.matches[index]!\n let loaderShouldRunAsync = false\n let loaderIsRunningAsync = false\n const route = inner.router.looseRoutesById[routeId]!\n\n if (shouldSkipLoader(inner, matchId)) {\n if (inner.router.isServer) {\n const headResult = executeHead(inner, matchId, route)\n if (headResult) {\n const head = await headResult\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n ...head,\n }))\n }\n return inner.router.getMatch(matchId)!\n }\n } else {\n const prevMatch = inner.router.getMatch(matchId)!\n // there is a loaderPromise, so we are in the middle of a load\n if (prevMatch._nonReactive.loaderPromise) {\n // do not block if we already have stale data we can show\n // but only if the ongoing load is not a preload since error handling is different for preloads\n // and we don't want to swallow errors\n if (prevMatch.status === 'success' && !inner.sync && !prevMatch.preload) {\n return prevMatch\n }\n await prevMatch._nonReactive.loaderPromise\n const match = inner.router.getMatch(matchId)!\n if (match.error) {\n handleRedirectAndNotFound(inner, match, match.error)\n }\n } else {\n // This is where all of the stale-while-revalidate magic happens\n const age = Date.now() - prevMatch.updatedAt\n\n const preload = resolvePreload(inner, matchId)\n\n const staleAge = preload\n ? (route.options.preloadStaleTime ??\n inner.router.options.defaultPreloadStaleTime ??\n 30_000) // 30 seconds for preloads by default\n : (route.options.staleTime ??\n inner.router.options.defaultStaleTime ??\n 0)\n\n const shouldReloadOption = route.options.shouldReload\n\n // Default to reloading the route all the time\n // Allow shouldReload to get the last say,\n // if provided.\n const shouldReload =\n typeof shouldReloadOption === 'function'\n ? shouldReloadOption(getLoaderContext(inner, matchId, index, route))\n : shouldReloadOption\n\n const nextPreload =\n !!preload && !inner.router.state.matches.some((d) => d.id === matchId)\n const match = inner.router.getMatch(matchId)!\n match._nonReactive.loaderPromise = createControlledPromise<void>()\n if (nextPreload !== match.preload) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n preload: nextPreload,\n }))\n }\n\n // If the route is successful and still fresh, just resolve\n const { status, invalid } = match\n loaderShouldRunAsync =\n status === 'success' && (invalid || (shouldReload ?? age > staleAge))\n if (preload && route.options.preload === false) {\n // Do nothing\n } else if (loaderShouldRunAsync && !inner.sync) {\n loaderIsRunningAsync = true\n ;(async () => {\n try {\n await runLoader(inner, matchId, index, route)\n const match = inner.router.getMatch(matchId)!\n match._nonReactive.loaderPromise?.resolve()\n match._nonReactive.loadPromise?.resolve()\n match._nonReactive.loaderPromise = undefined\n } catch (err) {\n if (isRedirect(err)) {\n await inner.router.navigate(err.options)\n }\n }\n })()\n } else if (status !== 'success' || (loaderShouldRunAsync && inner.sync)) {\n await runLoader(inner, matchId, index, route)\n } else {\n // if the loader did not run, still update head.\n // reason: parent's beforeLoad may have changed the route context\n // and only now do we know the route context (and that the loader would not run)\n const headResult = executeHead(inner, matchId, route)\n if (headResult) {\n const head = await headResult\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n ...head,\n }))\n }\n }\n }\n }\n const match = inner.router.getMatch(matchId)!\n if (!loaderIsRunningAsync) {\n match._nonReactive.loaderPromise?.resolve()\n match._nonReactive.loadPromise?.resolve()\n }\n\n clearTimeout(match._nonReactive.pendingTimeout)\n match._nonReactive.pendingTimeout = undefined\n if (!loaderIsRunningAsync) match._nonReactive.loaderPromise = undefined\n match._nonReactive.dehydrated = undefined\n const nextIsFetching = loaderIsRunningAsync ? match.isFetching : false\n if (nextIsFetching !== match.isFetching || match.invalid !== false) {\n inner.updateMatch(matchId, (prev) => ({\n ...prev,\n isFetching: nextIsFetching,\n invalid: false,\n }))\n return inner.router.getMatch(matchId)!\n } else {\n return match\n }\n}\n\nexport async function loadMatches(arg: {\n router: AnyRouter\n location: ParsedLocation\n matches: Array<AnyRouteMatch>\n preload?: boolean\n onReady?: () => Promise<void>\n updateMatch: UpdateMatchFn\n sync?: boolean\n}): Promise<Array<MakeRouteMatch>> {\n const inner: InnerLoadContext = Object.assign(arg, {\n matchPromises: [],\n })\n\n // make sure the pending component is immediately rendered when hydrating a match that is not SSRed\n // the pending component was already rendered on the server and we want to keep it shown on the client until minPendingMs is reached\n if (\n !inner.router.isServer &&\n inner.router.state.matches.some((d) => d._forcePending)\n ) {\n triggerOnReady(inner)\n }\n\n try {\n // Execute all beforeLoads one by one\n for (let i = 0; i < inner.matches.length; i++) {\n const beforeLoad = handleBeforeLoad(inner, i)\n if (isPromise(beforeLoad)) await beforeLoad\n }\n\n // Execute all loaders in parallel\n const max = inner.firstBadMatchIndex ?? inner.matches.length\n for (let i = 0; i < max; i++) {\n inner.matchPromises.push(loadRouteMatch(inner, i))\n }\n await Promise.all(inner.matchPromises)\n\n const readyPromise = triggerOnReady(inner)\n if (isPromise(readyPromise)) await readyPromise\n } catch (err) {\n if (isNotFound(err) && !inner.preload) {\n const readyPromise = triggerOnReady(inner)\n if (isPromise(readyPromise)) await readyPromise\n throw err\n }\n if (isRedirect(err)) {\n throw err\n }\n }\n\n return inner.matches\n}\n\nexport async function loadRouteChunk(route: AnyRoute) {\n if (!route._lazyLoaded && route._lazyPromise === undefined) {\n if (route.lazyFn) {\n route._lazyPromise = route.lazyFn().then((lazyRoute) => {\n // explicitly don't copy over the lazy route's id\n const { id: _id, ...options } = lazyRoute.options\n Object.assign(route.options, options)\n route._lazyLoaded = true\n route._lazyPromise = undefined // gc promise, we won't need it anymore\n })\n } else {\n route._lazyLoaded = true\n }\n }\n\n // If for some reason lazy resolves more lazy components...\n // We'll wait for that before we attempt to preload the\n // components themselves.\n if (!route._componentsLoaded && route._componentsPromise === undefined) {\n const loadComponents = () => {\n const preloads = []\n for (const type of componentTypes) {\n const preload = (route.options[type] as any)?.preload\n if (preload) preloads.push(preload())\n }\n if (preloads.length)\n return Promise.all(preloads).then(() => {\n route._componentsLoaded = true\n route._componentsPromise = undefined // gc promise, we won't need it anymore\n })\n route._componentsLoaded = true\n route._componentsPromise = undefined // gc promise, we won't need it anymore\n return\n }\n route._componentsPromise = route._lazyPromise\n ? route._lazyPromise.then(loadComponents)\n : loadComponents()\n }\n return route._componentsPromise\n}\n\nfunction makeMaybe<TValue, TError>(\n value: TValue,\n error: TError,\n): { status: 'success'; value: TValue } | { status: 'error'; error: TError } {\n if (error) {\n return { status: 'error' as const, error }\n }\n return { status: 'success' as const, value }\n}\n\nexport function routeNeedsPreload(route: AnyRoute) {\n for (const componentType of componentTypes) {\n if ((route.options[componentType] as any)?.preload) {\n return true\n }\n }\n return false\n}\n\nexport const componentTypes = [\n 'component',\n 'errorComponent',\n 'pendingComponent',\n 'notFoundComponent',\n] as const\n"],"names":["_a","_b","tempSsr","beforeLoadContext","match"],"mappings":";;;;;;AAuCA,MAAM,iBAAiB,CAAC,UAAkD;;AACpE,MAAA,CAAC,MAAM,UAAU;AACnB,UAAM,WAAW;AACjB,YAAO,WAAM,YAAN;AAAA,EAAgB;AAE3B;AAEA,MAAM,iBAAiB,CAAC,OAAyB,YAA6B;AAC5E,SAAO,CAAC,EACN,MAAM,WAAW,CAAC,MAAM,OAAO,MAAM,QAAQ,KAAK,CAAC,MAAM,EAAE,OAAO,OAAO;AAE7E;AAEA,MAAM,kBAAkB,CAAC,OAAyB,QAAuB;;AAGjE,QAAA,cACJ,MAAM,OAAO,WAAW,IAAI,WAAW,EAAE,KAAK,MAAM,OAAO;AAG7D,MACE,CAAC,YAAY,QAAQ,uBACpB,WAAM,OAAO,YAAb,mBAA8B,2BAC/B;AACA,gBAAY,QAAQ,oBAClB,MAAM,OAAO,QACb;AAAA,EAAA;AAIJ;AAAA,IACE,YAAY,QAAQ;AAAA,IACpB;AAAA,EACF;AAGM,QAAA,gBAAgB,MAAM,QAAQ,KAAK,CAAC,MAAM,EAAE,YAAY,YAAY,EAAE;AAElE,YAAA,eAAe,qCAAqC,YAAY,EAAE;AAG5E,QAAM,YAAY,cAAc,IAAI,CAAC,UAAU;AAAA,IAC7C,GAAG;AAAA,IACH,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,YAAY;AAAA,EAAA,EACZ;AAEF,MAAK,IAAY,eAAe,iBAAiB,YAAY,aAAa;AACpE,QAAA,UAAU,YAAY,YAAY;AACtC,oBAAgB,OAAO,GAA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ACF;"}
package/dist/esm/qss.d.ts CHANGED
@@ -6,11 +6,14 @@
6
6
  * This reimplementation uses modern browser APIs
7
7
  * (namely URLSearchParams) and TypeScript while still
8
8
  * maintaining the original functionality and interface.
9
+ *
10
+ * Update: this implementation has also been mangled to
11
+ * fit exactly our use-case (single value per key in encoding).
9
12
  */
10
13
  /**
11
14
  * Encodes an object into a query string.
12
15
  * @param obj - The object to encode into a query string.
13
- * @param [pfx] - An optional prefix to add before the query string.
16
+ * @param stringify - An optional custom stringify function.
14
17
  * @returns The encoded query string.
15
18
  * @example
16
19
  * ```
@@ -18,14 +21,13 @@
18
21
  * // Expected output: "token=foo&key=value"
19
22
  * ```
20
23
  */
21
- export declare function encode(obj: any, pfx?: string): string;
24
+ export declare function encode(obj: Record<string, any>, stringify?: (value: any) => string): string;
22
25
  /**
23
26
  * Decodes a query string into an object.
24
27
  * @param str - The query string to decode.
25
- * @param [pfx] - An optional prefix to filter out from the query string.
26
28
  * @returns The decoded key-value pairs in an object format.
27
29
  * @example
28
30
  * // Example input: decode("token=foo&key=value")
29
31
  * // Expected output: { "token": "foo", "key": "value" }
30
32
  */
31
- export declare function decode(str: any, pfx?: string): any;
33
+ export declare function decode(str: any): any;
package/dist/esm/qss.js CHANGED
@@ -1,13 +1,12 @@
1
- function encode(obj, pfx) {
2
- const normalizedObject = Object.entries(obj).flatMap(([key, value]) => {
3
- if (Array.isArray(value)) {
4
- return value.map((v) => [key, String(v)]);
5
- } else {
6
- return [[key, String(value)]];
1
+ function encode(obj, stringify = String) {
2
+ const result = new URLSearchParams();
3
+ for (const key in obj) {
4
+ const val = obj[key];
5
+ if (val !== void 0) {
6
+ result.set(key, stringify(val));
7
7
  }
8
- });
9
- const searchParams = new URLSearchParams(normalizedObject);
10
- return (pfx || "") + searchParams.toString();
8
+ }
9
+ return result.toString();
11
10
  }
12
11
  function toValue(str) {
13
12
  if (!str) return "";
@@ -15,19 +14,20 @@ function toValue(str) {
15
14
  if (str === "true") return true;
16
15
  return +str * 0 === 0 && +str + "" === str ? +str : str;
17
16
  }
18
- function decode(str, pfx) {
19
- const searchParamsPart = pfx ? str.slice(pfx.length) : str;
20
- const searchParams = new URLSearchParams(searchParamsPart);
21
- const entries = [...searchParams.entries()];
22
- return entries.reduce((acc, [key, value]) => {
23
- const previousValue = acc[key];
17
+ function decode(str) {
18
+ const searchParams = new URLSearchParams(str);
19
+ const result = {};
20
+ for (const [key, value] of searchParams.entries()) {
21
+ const previousValue = result[key];
24
22
  if (previousValue == null) {
25
- acc[key] = toValue(value);
23
+ result[key] = toValue(value);
24
+ } else if (Array.isArray(previousValue)) {
25
+ previousValue.push(toValue(value));
26
26
  } else {
27
- acc[key] = Array.isArray(previousValue) ? [...previousValue, toValue(value)] : [previousValue, toValue(value)];
27
+ result[key] = [previousValue, toValue(value)];
28
28
  }
29
- return acc;
30
- }, {});
29
+ }
30
+ return result;
31
31
  }
32
32
  export {
33
33
  decode,