clear-react-router 2.5.4 → 2.5.6

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.
@@ -1,3 +1,3 @@
1
1
  import { type ReactNode } from 'react';
2
2
  import { RouterProps } from '../types';
3
- export declare const Router: ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated, defaultMinLoaderDuration, revalidateOnFocus, revalidateOnReconnect, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, enableCacheSnapshot, }: RouterProps) => string | number | bigint | boolean | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | null | undefined;
3
+ export declare const Router: ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, defaultExternalCache, context: initialContext, isAnimated, defaultMinLoaderDuration, revalidateOnFocus, revalidateOnReconnect, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, enableCacheSnapshot, }: RouterProps) => string | number | bigint | boolean | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | null | undefined;
@@ -11,6 +11,7 @@ declare class RouterConfig {
11
11
  defaultAfterLoad?: ClientRouteItem['afterLoad'];
12
12
  defaultRetry?: RouterProps['defaultRetry'];
13
13
  defaultStaleTime?: RouterProps['defaultStaleTime'];
14
+ defaultExternalCache?: RouterProps['defaultExternalCache'];
14
15
  defaultMinLoaderDuration?: RouterProps['defaultMinLoaderDuration'];
15
16
  defaultScrollRestorationBehavior: RouterProps['defaultScrollRestorationBehavior'];
16
17
  enableCacheSnapshot: boolean;
package/dist/index.js CHANGED
@@ -98,6 +98,7 @@ var RouterConfig = class {
98
98
  _defineProperty(this, "defaultAfterLoad", void 0);
99
99
  _defineProperty(this, "defaultRetry", void 0);
100
100
  _defineProperty(this, "defaultStaleTime", void 0);
101
+ _defineProperty(this, "defaultExternalCache", void 0);
101
102
  _defineProperty(this, "defaultMinLoaderDuration", void 0);
102
103
  _defineProperty(this, "defaultScrollRestorationBehavior", void 0);
103
104
  _defineProperty(this, "enableCacheSnapshot", false);
@@ -130,11 +131,18 @@ var createIsCacheItemFresh = (loaderMap) => (path) => {
130
131
  };
131
132
  //#endregion
132
133
  //#region utils/utils.ts
134
+ var decodeSegment = (value) => {
135
+ try {
136
+ return decodeURIComponent(value);
137
+ } catch {
138
+ return value;
139
+ }
140
+ };
133
141
  var getParams = (location, routeItem) => {
134
142
  if (!routeItem) return {};
135
- const pathnameSegments = location.pathname.split("/");
136
- return routeItem.pattern.split("/").reduce((acc, segment, index) => {
137
- if (segment.startsWith(":")) acc[segment.slice(1)] = pathnameSegments[index];
143
+ const pathnameSegments = location.pathname.split("/").filter(Boolean);
144
+ return routeItem.pattern.split("/").filter(Boolean).reduce((acc, segment, index) => {
145
+ if (segment.startsWith(":")) acc[segment.slice(1)] = decodeSegment(pathnameSegments[index]);
138
146
  return acc;
139
147
  }, {});
140
148
  };
@@ -149,6 +157,22 @@ var matchPathPattern = (pattern, pathname) => {
149
157
  const pathSegments = pathname.split("/").filter(Boolean);
150
158
  return patternSegments.length === pathSegments.length ? patternSegments.every((segment, index) => isParamSegment(segment) || segment === pathSegments[index]) : false;
151
159
  };
160
+ /** Splits a path-with-query string; the search part keeps its leading '?' (or is ''). */
161
+ var splitPathAndSearch = (value) => {
162
+ const question = value.indexOf("?");
163
+ return question === -1 ? [value, ""] : [value.slice(0, question), value.slice(question)];
164
+ };
165
+ /**
166
+ * Canonical cache key: trailing slashes collapse and search params are sorted
167
+ * and re-encoded, so URL variants of one fact share one entry. The URL itself
168
+ * (history, address bar) is never rewritten — only the cache identity is.
169
+ */
170
+ var toCacheKey = (path) => {
171
+ const [base, query = ""] = splitPathAndSearch(path);
172
+ const entries = [...new URLSearchParams(query).entries()].sort(([aKey, aValue], [bKey, bValue]) => aKey < bKey ? -1 : aKey > bKey ? 1 : aValue < bValue ? -1 : aValue > bValue ? 1 : 0);
173
+ const canonical = new URLSearchParams(entries).toString();
174
+ return `${base.replace(/\/{2,}/g, "/").replace(/\/+$/, "") || "/"}${canonical ? `?${canonical}` : ""}`;
175
+ };
152
176
  var comparePaths = (route, pathname) => {
153
177
  const pattern = route.pattern.split("/").filter(Boolean);
154
178
  const current = pathname.split("/").filter(Boolean);
@@ -234,7 +258,7 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
234
258
  abortController = new AbortController();
235
259
  return abortController.signal;
236
260
  };
237
- const getPath = (nextLocation) => `${nextLocation.pathname}${nextLocation.search}`;
261
+ const getPath = (nextLocation) => toCacheKey(`${nextLocation.pathname}${nextLocation.search}`);
238
262
  const routeResolve = (location) => {
239
263
  const nextItem = findRoute(location.pathname, true);
240
264
  return {
@@ -244,6 +268,7 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
244
268
  };
245
269
  const beforeLoad = async (routeItem, nextLocation) => {
246
270
  const { defaultBeforeLoad } = routerConfig;
271
+ const signal = createSignal();
247
272
  const runBeforeLoad = async (loaderFn) => {
248
273
  const redirect = async (redirected) => {
249
274
  const { location } = routeDataState.getState();
@@ -251,10 +276,15 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
251
276
  pathname: location.pathname,
252
277
  search: location.search
253
278
  };
254
- return await navigate(typeof redirected === "string" ? {
255
- pathname: redirected,
256
- prevLocation
257
- } : {
279
+ if (typeof redirected === "string") {
280
+ const [pathname, search] = splitPathAndSearch(redirected);
281
+ return await navigate({
282
+ pathname,
283
+ search,
284
+ prevLocation
285
+ });
286
+ }
287
+ return await navigate({
258
288
  ...redirected,
259
289
  prevLocation
260
290
  });
@@ -262,7 +292,8 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
262
292
  try {
263
293
  await loaderFn({
264
294
  redirect,
265
- ...getPartialLoaderArgs(contextState, nextLocation, routeItem)
295
+ ...getPartialLoaderArgs(contextState, nextLocation, routeItem),
296
+ signal
266
297
  });
267
298
  return null;
268
299
  } catch (error) {
@@ -277,12 +308,13 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
277
308
  const createGcTimeout = () => {
278
309
  const { routeItem, location } = routeDataState.getState();
279
310
  if (!routeItem?.gcTime) return;
280
- const path = `${location.pathname}${location.search}`;
311
+ const path = toCacheKey(`${location.pathname}${location.search}`);
281
312
  const currentLoaderEntry = loaderMap.get(path);
282
313
  if (!currentLoaderEntry) return;
283
314
  if (currentLoaderEntry.gcTimeout) window.clearTimeout(currentLoaderEntry?.gcTimeout);
284
315
  const gcExpiresAt = Date.now() + routeItem.gcTime;
285
316
  const gcTimeout = window.setTimeout(() => {
317
+ if (loaderMap.get(path)?.gcTimeout !== gcTimeout) return;
286
318
  loaderMap.delete(path);
287
319
  syncCacheSnapshot();
288
320
  }, routeItem.gcTime);
@@ -337,7 +369,7 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
337
369
  });
338
370
  if (!result || signal.aborted) return;
339
371
  const { location: currentLocation } = routeDataState.getState();
340
- if (`${currentLocation.pathname}${currentLocation.search ?? ""}` !== getPath(nextLocation)) return;
372
+ if (toCacheKey(`${currentLocation.pathname}${currentLocation.search ?? ""}`) !== getPath(nextLocation)) return;
341
373
  routeDataState.setState((prevState) => ({
342
374
  ...prevState,
343
375
  loaderState: {
@@ -394,7 +426,7 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
394
426
  return currentState === "blocked";
395
427
  };
396
428
  const clearCurrentGcTimeout = (routeItem, location) => {
397
- const path = `${location.pathname}${location.search}`;
429
+ const path = toCacheKey(`${location.pathname}${location.search}`);
398
430
  if (!routeItem?.gcTime) return;
399
431
  const currentLoaderEntry = loaderMap.get(path);
400
432
  if (!currentLoaderEntry?.gcTimeout) return;
@@ -443,10 +475,7 @@ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
443
475
  //#endregion
444
476
  //#region runtime/invalidate.ts
445
477
  var separatePathname = (text) => text.split("?")[0].replace(/\/+$/, "") || "/";
446
- var normalizePath = (text) => {
447
- const [pathname, search = ""] = text.split("?");
448
- return `${separatePathname(pathname)}${search ? `?${search}` : ""}`;
449
- };
478
+ var normalizePath = (text) => toCacheKey(text);
450
479
  var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalidateCache, syncCacheSnapshot) => {
451
480
  const invalidatePath = async (routeItem, pathname, options) => {
452
481
  if (!options?.staleOnly) {
@@ -454,7 +483,7 @@ var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalida
454
483
  syncCacheSnapshot();
455
484
  await loadingPromises.get(pathname);
456
485
  }
457
- const [path, search = ""] = pathname.split("?");
486
+ const [path, search] = splitPathAndSearch(pathname);
458
487
  const result = await revalidateCache({
459
488
  routeItem,
460
489
  location: {
@@ -479,7 +508,8 @@ var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalida
479
508
  ...result
480
509
  };
481
510
  };
482
- const invalidateItem = async (pathname, options) => {
511
+ const invalidateItem = async (rawPathname, options) => {
512
+ const pathname = toCacheKey(rawPathname);
483
513
  const routeItem = findRoute(separatePathname(pathname));
484
514
  if (!routeItem) return [];
485
515
  const targetPathname = separatePathname(pathname);
@@ -494,12 +524,12 @@ var createInvalidate = ({ routeDataState, loaderMap, loadingPromises }, revalida
494
524
  const currentResults = await Promise.all([...pathnameSet].map((pathname) => invalidatePath(routeItem, pathname, options)));
495
525
  if (!options?.withChildren || !routeItem.children?.length) return currentResults;
496
526
  const [parentPath] = pathname.split("?");
497
- const childResults = await Promise.all(routeItem.children.map((child) => invalidateItem(`${parentPath}${child.path}`, options)));
527
+ const childResults = await Promise.all(routeItem.children.map((child) => invalidateItem(`${parentPath}/${child.path}`.replace(/\/{2,}/g, "/"), options)));
498
528
  return [...currentResults, ...childResults.flat()];
499
529
  };
500
530
  return async (pathList, options) => {
501
531
  const { pathname, search } = routeDataState.getState().location;
502
- const routePathname = `${pathname}${search}`;
532
+ const routePathname = toCacheKey(`${pathname}${search}`);
503
533
  const pathnameList = Array.isArray(pathList) ? pathList : pathList ? [pathList] : [routePathname];
504
534
  return (await Promise.all(pathnameList.map((pathname) => invalidateItem(pathname, options)))).flat();
505
535
  };
@@ -511,7 +541,7 @@ var DESKTOP_PREFETCH_CONCURRENCY = 4;
511
541
  var createPrefetch = ({ routeDataState }, revalidateCache) => {
512
542
  const queue = [];
513
543
  let active = 0;
514
- const run = async (location) => {
544
+ const run = async (location, signal) => {
515
545
  const item = findRoute(location.pathname);
516
546
  if (!item) return;
517
547
  const currentLocation = routeDataState.getState().location;
@@ -520,7 +550,8 @@ var createPrefetch = ({ routeDataState }, revalidateCache) => {
520
550
  await revalidateCache({
521
551
  routeItem: item,
522
552
  location,
523
- reason: "prefetch"
553
+ reason: "prefetch",
554
+ signal
524
555
  });
525
556
  };
526
557
  const drain = () => {
@@ -533,7 +564,7 @@ var createPrefetch = ({ routeDataState }, revalidateCache) => {
533
564
  return (location, signal) => new Promise((resolve) => {
534
565
  queue.push(async () => {
535
566
  try {
536
- if (!signal?.aborted) await run(location);
567
+ if (!signal?.aborted) await run(location, signal);
537
568
  } catch {} finally {
538
569
  active--;
539
570
  resolve();
@@ -566,12 +597,15 @@ var getRetry = (routeItem) => {
566
597
  var createRevalidateCache = (routerState, syncCacheSnapshot) => {
567
598
  const { loaderMap, loadingPromises, contextState, routeDataState } = routerState;
568
599
  const flightOwners = /* @__PURE__ */ new Map();
600
+ const flightReasons = /* @__PURE__ */ new Map();
569
601
  const evict = () => {
570
602
  if (loaderMap.size <= routerConfig.maxCacheSize) return;
571
603
  const { pathname, search = "" } = routeDataState.getState().location;
572
- const currentPath = `${pathname}${search}`;
604
+ const currentPath = toCacheKey(`${pathname}${search}`);
573
605
  const oldestKey = [...loaderMap.keys()].find((key) => key !== currentPath);
574
606
  if (oldestKey) {
607
+ const item = loaderMap.get(oldestKey);
608
+ if (item?.gcTimeout) window.clearTimeout(item.gcTimeout);
575
609
  loaderMap.delete(oldestKey);
576
610
  syncCacheSnapshot();
577
611
  }
@@ -587,16 +621,23 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
587
621
  };
588
622
  const revalidateCache = async ({ routeItem, location, signal, force, reason }, retried = 0) => {
589
623
  if (!routeItem?.loader) return;
624
+ if (signal?.aborted) return {
625
+ data: null,
626
+ error: null
627
+ };
628
+ const externalCache = routeItem.externalCache ?? routerConfig.defaultExternalCache;
590
629
  const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
591
630
  const { pathname, search = "" } = location;
592
- const path = `${pathname}${search}`;
631
+ const path = toCacheKey(`${pathname}${search}`);
593
632
  if (loadingPromises.has(path)) {
594
633
  const owner = flightOwners.get(path);
595
634
  const ownerWasAborted = owner instanceof AbortController ? owner.signal.aborted : owner?.aborted;
596
- if (signal && owner instanceof AbortController || ownerWasAborted) {
635
+ const canRide = reason === "prefetch" || flightReasons.get(path) !== "prefetch";
636
+ if (reason !== "prefetch" && !!signal && owner instanceof AbortController || ownerWasAborted || !canRide) {
597
637
  if (owner instanceof AbortController) owner.abort();
598
638
  loadingPromises.delete(path);
599
639
  flightOwners.delete(path);
640
+ flightReasons.delete(path);
600
641
  syncCacheSnapshot();
601
642
  } else {
602
643
  moveItemToLastPosition(path);
@@ -607,7 +648,7 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
607
648
  const item = loaderMap.get(path);
608
649
  if (reason === "navigation" && item?.reason === "prefetch") {
609
650
  item.reason = "navigation";
610
- item.staleTime = routeItem.staleTime;
651
+ item.staleTime = externalCache ? 0 : routeItem.staleTime;
611
652
  }
612
653
  moveItemToLastPosition(path);
613
654
  if (!item?.state) return void 0;
@@ -625,6 +666,7 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
625
666
  const effectiveSignal = signal ?? prefetchController.signal;
626
667
  const ownerToken = prefetchController ?? signal;
627
668
  flightOwners.set(path, ownerToken);
669
+ flightReasons.set(path, reason);
628
670
  const isOwner = () => flightOwners.get(path) === ownerToken;
629
671
  try {
630
672
  const result = await routeItem?.loader({
@@ -644,7 +686,7 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
644
686
  loaderError: null
645
687
  },
646
688
  timestamp: Date.now(),
647
- staleTime: reason === "prefetch" ? Math.max(resolvedStaleTime, PRELOAD_STALE_TIME) : routeItem.staleTime,
689
+ staleTime: externalCache ? 0 : reason === "prefetch" ? Math.max(resolvedStaleTime, PRELOAD_STALE_TIME) : routeItem.staleTime,
648
690
  reason
649
691
  });
650
692
  evict();
@@ -663,6 +705,7 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
663
705
  if (isOwner()) {
664
706
  loadingPromises.delete(path);
665
707
  flightOwners.delete(path);
708
+ flightReasons.delete(path);
666
709
  }
667
710
  if (retry.delay) await sleep(retry.delay);
668
711
  return revalidateCache({
@@ -680,6 +723,7 @@ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
680
723
  if (isOwner()) {
681
724
  loadingPromises.delete(path);
682
725
  flightOwners.delete(path);
726
+ flightReasons.delete(path);
683
727
  syncCacheSnapshot();
684
728
  }
685
729
  }
@@ -790,7 +834,7 @@ var createRouterInstance = (synchronizer) => {
790
834
  };
791
835
  if (arg === -1) return history.go(arg);
792
836
  if (typeof arg === "string") {
793
- const [pathname, search = ""] = arg.split("?");
837
+ const [pathname, search] = splitPathAndSearch(arg);
794
838
  if (pathname !== location.pathname || search !== location.search) await navigate({
795
839
  pathname,
796
840
  search,
@@ -823,7 +867,7 @@ var createRouterInstance = (synchronizer) => {
823
867
  try {
824
868
  const currentAction = getCurrentAction(action);
825
869
  const { location } = routerState.routeDataState.getState();
826
- const path = `${location.pathname}${location.search ?? ""}`;
870
+ const path = toCacheKey(`${location.pathname}${location.search ?? ""}`);
827
871
  const data = await currentAction(input);
828
872
  await invalidate(path);
829
873
  options.onSuccess?.(data);
@@ -962,7 +1006,10 @@ var useSetRouterConfig = (routerProps) => {
962
1006
  var useSetInitialContext = (initialContext) => {
963
1007
  const [, setContext] = router.hooks.useContextState();
964
1008
  useEffect(() => {
965
- if (initialContext) setContext(initialContext);
1009
+ if (initialContext) setContext((prev) => ({
1010
+ ...prev,
1011
+ ...initialContext
1012
+ }));
966
1013
  }, [initialContext, setContext]);
967
1014
  };
968
1015
  //#endregion
@@ -996,7 +1043,7 @@ var renderElement = (Component) => {
996
1043
  var EmptyBoundary = ({ children }) => children;
997
1044
  var MOBILE_CACHE_SIZE = 60;
998
1045
  var DESKTOP_CACHE_SIZE = 150;
999
- var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, defaultMinLoaderDuration = 0, revalidateOnFocus = false, revalidateOnReconnect = false, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay = 150, defaultScrollRestorationBehavior = "auto", errorBoundary: ErrorBoundary = EmptyBoundary, enableCacheSnapshot = false }) => {
1046
+ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, defaultExternalCache, context: initialContext, isAnimated = false, defaultMinLoaderDuration = 0, revalidateOnFocus = false, revalidateOnReconnect = false, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay = 150, defaultScrollRestorationBehavior = "auto", errorBoundary: ErrorBoundary = EmptyBoundary, enableCacheSnapshot = false }) => {
1000
1047
  const isMobileDevice = isMobile();
1001
1048
  const resolvedMaxCacheSize = maxCacheSize ?? (isMobileDevice ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE);
1002
1049
  const resolvedDefaultPrefetch = defaultPrefetch ?? (isMobileDevice ? "viewport" : "hover");
@@ -1015,6 +1062,7 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
1015
1062
  defaultAfterLoad,
1016
1063
  defaultRetry,
1017
1064
  defaultStaleTime,
1065
+ defaultExternalCache,
1018
1066
  defaultMinLoaderDuration,
1019
1067
  maxCacheSize: resolvedMaxCacheSize,
1020
1068
  revalidateOnFocus,
@@ -1045,9 +1093,10 @@ var useNavigate = router.hooks.useNavigate;
1045
1093
  var VIEWPORT_DWELL_MS = 250;
1046
1094
  var defaultAs = (props) => /* @__PURE__ */ jsx("a", { ...props });
1047
1095
  var comparator = (to, pathname, exact) => to === "/" ? pathname === "/" : exact ? pathname === to : pathname === to || pathname?.startsWith(`${to}/`);
1048
- var Link = ({ children, to, path, params, search = "", state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link", ...rest }) => {
1049
- const pathname = path !== void 0 ? interpolatePath(path, params ?? {}) : to ?? "";
1050
- const searchString = typeof search === "object" ? formatSearchObject(search) : search;
1096
+ var Link = ({ children, to, path, params, search, state, as = defaultAs, prefetch: linkPrefetch, hoverPrefetchDelay, className, style, beforeNavigate, exact = false, activeClassName = "active-link", pendingClassName = "pending-link", ...rest }) => {
1097
+ const [toPathname, toSearch] = splitPathAndSearch(to ?? "");
1098
+ const pathname = path !== void 0 ? interpolatePath(path, params ?? {}) : toPathname;
1099
+ const searchString = search === void 0 ? toSearch : typeof search === "object" ? formatSearchObject(search) : search;
1051
1100
  const { useRouteDataSelector } = router.hooks;
1052
1101
  const isPending = useRouteDataSelector(({ location: { pathname: currentPathname, search: currentSearch = "" }, status }) => currentPathname === pathname && currentSearch === searchString && status === "pending");
1053
1102
  const navigate = useNavigate();
@@ -1345,20 +1394,24 @@ var LAZY_MARKER = Symbol("clear-router-lazy");
1345
1394
  //#region creators/createRouter.ts
1346
1395
  var isLazy = (component) => typeof component === "object" && component !== null && LAZY_MARKER in component;
1347
1396
  var resolve = (component, fallback) => isLazy(component) ? createLazyComponent(component.importFn, fallback).Component : component;
1348
- var parseClientRouteItem = (el, parentPattern = "", inheritedLayouts = []) => {
1397
+ var parseClientRouteItem = (el, parentPattern = "", inheritedLayouts = [], inheritedExternalCache) => {
1349
1398
  const pattern = `${parentPattern}/${el.path}`.replace(/\/+/g, "/");
1350
1399
  const preloadElement = isLazy(el.element) ? createLazyComponent(el.element.importFn, el.fallback).preloadElement : void 0;
1351
1400
  const layouts = el.layout ? [...inheritedLayouts, el.layout] : inheritedLayouts;
1401
+ const externalCache = el.externalCache ?? inheritedExternalCache;
1352
1402
  return [{
1353
1403
  ...el,
1404
+ externalCache,
1354
1405
  pattern,
1355
1406
  element: resolve(el.element, el.fallback),
1356
1407
  errorElement: resolve(el.errorElement, el.fallback),
1357
1408
  preloadElement,
1358
1409
  layouts
1359
- }, ...el.children?.flatMap((child) => parseClientRouteItem(child, pattern, layouts)) ?? []];
1410
+ }, ...el.children?.flatMap((child) => parseClientRouteItem(child, pattern, layouts, externalCache)) ?? []];
1411
+ };
1412
+ var createRouter = (clientList) => {
1413
+ return clientList.flatMap((el) => parseClientRouteItem(el));
1360
1414
  };
1361
- var createRouter = (clientList) => clientList.flatMap((el) => parseClientRouteItem(el));
1362
1415
  //#endregion
1363
1416
  //#region utils/lazy.ts
1364
1417
  var lazy = (importFn) => ({
package/dist/types.d.ts CHANGED
@@ -16,6 +16,7 @@ type LoaderArgs = {
16
16
  location: Location;
17
17
  };
18
18
  export type BeforeLoad = (arg: LoaderArgs & {
19
+ signal: AbortSignal;
19
20
  redirect: (arg: Location | string) => Promise<void>;
20
21
  }) => Promise<unknown> | undefined | void;
21
22
  export type ScrollRestorationBehavior = 'auto' | 'smooth' | 'instant';
@@ -32,6 +33,13 @@ export type ClientRouteItem = {
32
33
  layout?: RenderElement;
33
34
  children?: ClientRouteItem[];
34
35
  staleTime?: number;
36
+ /**
37
+ * The route's data freshness is owned by the loader's source (e.g. an external
38
+ * cache like TanStack Query): the router cache stores values but never claims
39
+ * freshness — every navigation re-runs the loader. Inherited by children;
40
+ * a child can opt out with `false`.
41
+ */
42
+ externalCache?: boolean;
35
43
  gcTime?: number;
36
44
  optimistic?: boolean;
37
45
  pollingInterval?: number;
@@ -94,6 +102,8 @@ export type RouterProps = {
94
102
  animationDuration?: number;
95
103
  defaultRetry?: Retry;
96
104
  defaultStaleTime?: number;
105
+ /** `externalCache` fallback for routes that don't declare it. */
106
+ defaultExternalCache?: boolean;
97
107
  defaultLoaderFallback?: RenderElement;
98
108
  defaultErrorElement?: RenderElement;
99
109
  defaultPrefetch?: 'hover' | 'render' | 'viewport' | 'none';
@@ -4,6 +4,14 @@ export declare const getParams: (location: Location, routeItem?: RouteItem) => R
4
4
  export declare const parseWindowLocation: (location: typeof window.location) => Location;
5
5
  export declare const isParamSegment: (segment: string) => boolean;
6
6
  export declare const matchPathPattern: (pattern: string, pathname: string) => boolean;
7
+ /** Splits a path-with-query string; the search part keeps its leading '?' (or is ''). */
8
+ export declare const splitPathAndSearch: (value: string) => [string, string];
9
+ /**
10
+ * Canonical cache key: trailing slashes collapse and search params are sorted
11
+ * and re-encoded, so URL variants of one fact share one entry. The URL itself
12
+ * (history, address bar) is never rewritten — only the cache identity is.
13
+ */
14
+ export declare const toCacheKey: (path: string) => string;
7
15
  export declare const comparePaths: (route: RouteItem, pathname: string) => boolean;
8
16
  export declare const isMobile: () => boolean;
9
17
  export declare const sleep: (ms: number) => Promise<unknown>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.5.4",
3
+ "version": "2.5.6",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {