clear-react-router 2.4.8 → 2.4.9

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.
package/README.md CHANGED
@@ -33,6 +33,7 @@ It provides first-class support for:
33
33
  - **Programmatic Redirects** - Redirect from beforeLoad hook
34
34
  - **Cache invalidation** - Manual route invalidation
35
35
  - **Bounded Cache** - Automatically evicts least recently used entries once `maxCacheSize` is reached, keeping memory usage predictable in long sessions
36
+ - **Cache inspection** - Opt into a live, read-only snapshot of cached loader entries with `logged` and `useCacheSnapshot()`
36
37
  - **Prefetching** - Preload data on hover for instant navigation
37
38
  - **Lazy Loading** - Code-split your routes with dynamic imports for optimal performance
38
39
  - **Scroll Restoration** — Automatically saves and restores scroll position when navigating back to a page (preserves user's scroll position)
@@ -65,6 +66,7 @@ Netlify (`public/_redirects`):
65
66
  |------|------|---------|-------------|
66
67
  | `routes` | `RouteItem[]` | required | Array of route configurations |
67
68
  | `maxCacheSize` | `number \| undefined` | 60 for mobile, 150 for desktop | Maximum number of cached loader entries. Once the limit is reached, the least recently used entries are evicted |
69
+ | `logged` | `boolean` | `false` | Enables cache snapshot tracking for [`useCacheSnapshot()`](#usecachesnapshot). Off by default: no snapshot is built and the hook returns an empty list |
68
70
  | `isAnimated` | `boolean \| undefined` | `false` | Enable smooth page fade transitions |
69
71
  | `animationDuration` | `number \| undefined` | `optional` | Animation duration in milliseconds (browser default is used if not set) |
70
72
  | `context` | `object` | `{}` | Initial context (user, theme, etc.) |
@@ -858,6 +860,55 @@ const UserProfile = () => {
858
860
  ```
859
861
 
860
862
 
863
+ ### `useCacheSnapshot()`
864
+
865
+ Returns a read-only snapshot of the loader cache — intended for devtools panels, debugging, and cache
866
+ monitoring. Requires `<Router logged>`; while the flag is off the snapshot is empty and nothing is built.
867
+
868
+ ```tsx
869
+ import { useCacheSnapshot } from 'clear-react-router';
870
+
871
+ const CachePanel = () => {
872
+ const entries = useCacheSnapshot();
873
+
874
+ return (
875
+ <ul>
876
+ {entries.map(entry => (
877
+ <li key={entry.path}>
878
+ {entry.path} — {entry.reason ?? 'unknown'} — {entry.isLoading ? 'loading' : 'cached'}
879
+ </li>
880
+ ))}
881
+ </ul>
882
+ );
883
+ };
884
+
885
+ <Router routes={routes} logged />
886
+ ```
887
+
888
+ ```ts
889
+ type CacheReason = 'navigation' | 'prefetch' | 'invalidate' | 'polling';
890
+
891
+ type CacheSnapshotEntry = {
892
+ path: string; // pathname + search
893
+ data: unknown; // loader result; undefined while the first load is in flight
894
+ timestamp: number; // when the entry was written (ms since epoch)
895
+ staleTime: number | undefined; // copy of the route's staleTime
896
+ reason?: CacheReason; // what wrote the entry last
897
+ gcExpiresAt: number | undefined; // GC deadline, if a GC timer is pending
898
+ gcDuration: number | undefined; // the route's gcTime, for progress display
899
+ isLoading: boolean; // a loader for this path is currently running
900
+ };
901
+
902
+ type CacheSnapshot = CacheSnapshotEntry[];
903
+ ```
904
+
905
+ Notes:
906
+
907
+ - The snapshot is a projection, not a second cache — changing it does nothing.
908
+ - Entries appear for in-flight first loads too (`data: undefined`, `isLoading: true`), so a devtool never misses a request.
909
+ - Mounting the hook refreshes the snapshot, so a panel opened after navigation still sees existing entries.
910
+ - `logged` is process-wide (the router is a singleton): if several `<Router>`s render with different values, the last rendered one wins. Enable it only when a consumer is actually mounted.
911
+
861
912
  ### `useInvalidate()`
862
913
 
863
914
  Returns a function that revalidates **cached** route data. Calling `invalidate()` clears cached route data and immediately runs the corresponding route `loader` again.
@@ -1276,8 +1327,9 @@ Try it live — no setup: **[clear-router playground](https://clear-react-router
1276
1327
 
1277
1328
  Scroll restoration (window + named containers), retry with attempt counts, live polling,
1278
1329
  actions with invalidation, navigation blocking, hover prefetch, optimistic navigation,
1279
- LRU eviction with a tiny cache, gcTime cleanup, an invalidation lab, search params,
1280
- and a context-based auth guard — all running against a fake in-browser server.
1330
+ LRU eviction with a tiny cache, gcTime cleanup, an invalidation lab, a live cache visualizer
1331
+ (toggle it in settings), search params, and a context-based auth guard — all running against a fake
1332
+ in-browser server.
1281
1333
  Open devtools and click around.
1282
1334
 
1283
1335
  ## License
@@ -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, }: 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, context: initialContext, isAnimated, defaultMinLoaderDuration, revalidateOnFocus, revalidateOnReconnect, maxCacheSize, defaultPrefetch, defaultHoverPrefetchDelay, defaultScrollRestorationBehavior, errorBoundary: ErrorBoundary, logged, }: 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;
@@ -13,6 +13,7 @@ declare class RouterConfig {
13
13
  defaultStaleTime?: RouterProps['defaultStaleTime'];
14
14
  defaultMinLoaderDuration?: RouterProps['defaultMinLoaderDuration'];
15
15
  defaultScrollRestorationBehavior: RouterProps['defaultScrollRestorationBehavior'];
16
+ logged: boolean;
16
17
  configure(config: Partial<RouterConfig>): void;
17
18
  }
18
19
  export declare const routerConfig: RouterConfig;
@@ -0,0 +1,3 @@
1
+ import type { CacheSnapshot } from '../types';
2
+ /** Requires `<Router logged>` — otherwise the snapshot stays empty. */
3
+ export declare const useCacheSnapshot: () => CacheSnapshot;
package/dist/index.d.ts CHANGED
@@ -12,7 +12,8 @@ export { useRouterContext } from './hooks/useRouterContext';
12
12
  export { useSearchParams } from './hooks/useSearchParams';
13
13
  export { useSubmitAction } from './hooks/useSubmitAction';
14
14
  export { useRestoreScroll } from './hooks/useRestoreScroll';
15
+ export { useCacheSnapshot } from './hooks/useCacheSnapshot';
15
16
  export { createRouter } from './creators/createRouter';
16
17
  export { lazy } from './utils/lazy';
17
- export type { RouteItem, ClientRouteItem, BlockerState, Location, RouterProps, NavigationLocation, NavigatePathArg, PathParams, ParamsFor, Status, } from './types';
18
+ export type { RouteItem, ClientRouteItem, BlockerState, Location, RouterProps, NavigationLocation, NavigatePathArg, PathParams, ParamsFor, Status, CacheSnapshot, CacheSnapshotEntry, CacheReason, } from './types';
18
19
  export type { ElementProps, LinkProps } from './components/Link';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Suspense, lazy as lazy$1, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
2
2
  import { jsx } from "react/jsx-runtime";
3
- //#region create.ts
3
+ // create.ts
4
4
  var create = (initialState) => {
5
5
  let state = initialState;
6
6
  const subscribers = /* @__PURE__ */ new Set();
@@ -26,8 +26,7 @@ var create = (initialState) => {
26
26
  var useGlobalState = ({ subscribe, getState, setState }, synchronizer) => {
27
27
  return [synchronizer(subscribe, getState), setState];
28
28
  };
29
- //#endregion
30
- //#region utils/commitState.ts
29
+ // utils/commitState.ts
31
30
  var createCommitState = ({ routeDataState, blockerState }) => ({ routeItem, loaderStateValue, location }) => {
32
31
  const isError = loaderStateValue.loaderError || loaderStateValue.beforeLoadError;
33
32
  routeDataState.setState({
@@ -40,13 +39,11 @@ var createCommitState = ({ routeDataState, blockerState }) => ({ routeItem, load
40
39
  if ((location.search ? `${location.pathname}${location.search}` : location.pathname) === window.location.pathname + window.location.search) return;
41
40
  history.pushState(location.state ?? null, "", `${location.pathname}${location.search}`);
42
41
  };
43
- //#endregion
44
- //#region constants.ts
42
+ // constants.ts
45
43
  var EMPTY_LOADER_STATE = {};
46
44
  var WINDOW_TOP = "__window_top__";
47
45
  var WINDOW_LEFT = "__window_left__";
48
- //#endregion
49
- //#region \0@oxc-project+runtime@0.132.0/helpers/typeof.js
46
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/typeof.js
50
47
  function _typeof(o) {
51
48
  "@babel/helpers - typeof";
52
49
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -55,8 +52,7 @@ function _typeof(o) {
55
52
  return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
56
53
  }, _typeof(o);
57
54
  }
58
- //#endregion
59
- //#region \0@oxc-project+runtime@0.132.0/helpers/toPrimitive.js
55
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/toPrimitive.js
60
56
  function toPrimitive(t, r) {
61
57
  if ("object" != _typeof(t) || !t) return t;
62
58
  var e = t[Symbol.toPrimitive];
@@ -67,14 +63,12 @@ function toPrimitive(t, r) {
67
63
  }
68
64
  return ("string" === r ? String : Number)(t);
69
65
  }
70
- //#endregion
71
- //#region \0@oxc-project+runtime@0.132.0/helpers/toPropertyKey.js
66
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/toPropertyKey.js
72
67
  function toPropertyKey(t) {
73
68
  var i = toPrimitive(t, "string");
74
69
  return "symbol" == _typeof(i) ? i : i + "";
75
70
  }
76
- //#endregion
77
- //#region \0@oxc-project+runtime@0.132.0/helpers/defineProperty.js
71
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/defineProperty.js
78
72
  function _defineProperty(e, r, t) {
79
73
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
80
74
  value: t,
@@ -83,8 +77,7 @@ function _defineProperty(e, r, t) {
83
77
  writable: !0
84
78
  }) : e[r] = t, e;
85
79
  }
86
- //#endregion
87
- //#region config/routerConfig.ts
80
+ // config/routerConfig.ts
88
81
  var RouterConfig = class {
89
82
  constructor() {
90
83
  _defineProperty(this, "routes", []);
@@ -100,14 +93,14 @@ var RouterConfig = class {
100
93
  _defineProperty(this, "defaultStaleTime", void 0);
101
94
  _defineProperty(this, "defaultMinLoaderDuration", void 0);
102
95
  _defineProperty(this, "defaultScrollRestorationBehavior", void 0);
96
+ _defineProperty(this, "logged", false);
103
97
  }
104
98
  configure(config) {
105
99
  Object.assign(this, config);
106
100
  }
107
101
  };
108
102
  var routerConfig = new RouterConfig();
109
- //#endregion
110
- //#region utils/commitNavigation.ts
103
+ // utils/commitNavigation.ts
111
104
  var commitNavigation = (callback, isCommited) => {
112
105
  if (!routerConfig.isAnimated || isCommited) return callback();
113
106
  try {
@@ -118,8 +111,7 @@ var commitNavigation = (callback, isCommited) => {
118
111
  callback();
119
112
  }
120
113
  };
121
- //#endregion
122
- //#region utils/isCacheItemFresh.ts
114
+ // utils/isCacheItemFresh.ts
123
115
  var createIsCacheItemFresh = (loaderMap) => (path) => {
124
116
  const item = loaderMap.get(path);
125
117
  if (item === void 0) return false;
@@ -127,8 +119,7 @@ var createIsCacheItemFresh = (loaderMap) => (path) => {
127
119
  if (resolvedStaleTime === void 0) return true;
128
120
  return Date.now() - item.timestamp <= resolvedStaleTime;
129
121
  };
130
- //#endregion
131
- //#region utils/utils.ts
122
+ // utils/utils.ts
132
123
  var getParams = (location, routeItem) => {
133
124
  if (!routeItem) return {};
134
125
  const pathnameSegments = location.pathname.split("/");
@@ -205,9 +196,8 @@ var findRoute = (pathname, includeAll) => {
205
196
  if (includeAll) return routerConfig.routes.find((el) => el.path === "*" || comparePaths(el, pathname));
206
197
  return routerConfig.routes.find((el) => comparePaths(el, pathname));
207
198
  };
208
- //#endregion
209
- //#region runtime/navigate.ts
210
- var createNavigate = (routerState, revalidateCache) => {
199
+ // runtime/navigate.ts
200
+ var createNavigate = (routerState, revalidateCache, syncCacheSnapshot) => {
211
201
  let navigationSeq = 0;
212
202
  let interval = 0;
213
203
  let abortController = null;
@@ -273,11 +263,18 @@ var createNavigate = (routerState, revalidateCache) => {
273
263
  const currentLoaderEntry = loaderMap.get(path);
274
264
  if (!currentLoaderEntry) return;
275
265
  if (currentLoaderEntry.gcTimeout) window.clearTimeout(currentLoaderEntry?.gcTimeout);
276
- const gcTimeout = window.setTimeout(() => loaderMap.delete(path), routeItem.gcTime);
266
+ const gcExpiresAt = Date.now() + routeItem.gcTime;
267
+ const gcTimeout = window.setTimeout(() => {
268
+ loaderMap.delete(path);
269
+ syncCacheSnapshot();
270
+ }, routeItem.gcTime);
277
271
  loaderMap.set(path, {
278
272
  ...currentLoaderEntry,
279
- gcTimeout
273
+ gcTimeout,
274
+ gcExpiresAt,
275
+ gcDuration: routeItem.gcTime
280
276
  });
277
+ syncCacheSnapshot();
281
278
  };
282
279
  const commitOptimisticState = (routeItem, location, path) => {
283
280
  const currentLoaderState = loaderMap.get(path)?.state;
@@ -317,7 +314,8 @@ var createNavigate = (routerState, revalidateCache) => {
317
314
  routeItem,
318
315
  location: nextLocation,
319
316
  signal,
320
- force: true
317
+ force: true,
318
+ reason: "polling"
321
319
  });
322
320
  if (!result || signal.aborted) return;
323
321
  const { location: currentLocation } = routeDataState.getState();
@@ -342,7 +340,8 @@ var createNavigate = (routerState, revalidateCache) => {
342
340
  const [result] = await Promise.all([revalidateCache({
343
341
  routeItem,
344
342
  location: nextLocation,
345
- signal
343
+ signal,
344
+ reason: "navigation"
346
345
  }), getLoaderDurationPromise(routeItem, nextLocation)]);
347
346
  if (seq !== navigationSeq) return;
348
347
  polling(routeItem, nextLocation);
@@ -375,7 +374,9 @@ var createNavigate = (routerState, revalidateCache) => {
375
374
  window.clearTimeout(currentLoaderEntry.gcTimeout);
376
375
  loaderMap.set(path, {
377
376
  ...currentLoaderEntry,
378
- gcTimeout: void 0
377
+ gcTimeout: void 0,
378
+ gcExpiresAt: void 0,
379
+ gcDuration: void 0
379
380
  });
380
381
  };
381
382
  const navigate = async (rawLocation) => {
@@ -412,20 +413,23 @@ var createNavigate = (routerState, revalidateCache) => {
412
413
  };
413
414
  return navigate;
414
415
  };
415
- //#endregion
416
- //#region runtime/invalidate.ts
416
+ // runtime/invalidate.ts
417
417
  var separatePathname = (text) => text.split("?")[0];
418
- var createInvalidate = ({ routeDataState, loaderMap }, revalidateCache) => {
418
+ var createInvalidate = ({ routeDataState, loaderMap }, revalidateCache, syncCacheSnapshot) => {
419
419
  const invalidatePath = async (routeItem, pathname, options) => {
420
420
  const routePathname = routeDataState.getState().location.pathname;
421
- if (!options?.staleOnly) loaderMap.delete(pathname);
421
+ if (!options?.staleOnly) {
422
+ loaderMap.delete(pathname);
423
+ syncCacheSnapshot();
424
+ }
422
425
  const [path, search = ""] = pathname.split("?");
423
426
  const result = await revalidateCache({
424
427
  routeItem,
425
428
  location: {
426
429
  pathname: path,
427
430
  search
428
- }
431
+ },
432
+ reason: "invalidate"
429
433
  });
430
434
  if (result && path === routePathname) routeDataState.setState((prevState) => ({
431
435
  ...prevState,
@@ -462,8 +466,7 @@ var createInvalidate = ({ routeDataState, loaderMap }, revalidateCache) => {
462
466
  return (await Promise.all(pathnameList.map((pathname) => invalidateItem(pathname, options)))).flat();
463
467
  };
464
468
  };
465
- //#endregion
466
- //#region runtime/prefetch.ts
469
+ // runtime/prefetch.ts
467
470
  var MOBILE_PREFETCH_CONCURRENCY = 2;
468
471
  var DESKTOP_PREFETCH_CONCURRENCY = 4;
469
472
  var createPrefetch = ({ routeDataState }, revalidateCache) => {
@@ -478,7 +481,8 @@ var createPrefetch = ({ routeDataState }, revalidateCache) => {
478
481
  await item.preloadElement?.();
479
482
  await revalidateCache({
480
483
  routeItem: item,
481
- location
484
+ location,
485
+ reason: "prefetch"
482
486
  });
483
487
  };
484
488
  const drain = () => {
@@ -500,8 +504,7 @@ var createPrefetch = ({ routeDataState }, revalidateCache) => {
500
504
  drain();
501
505
  });
502
506
  };
503
- //#endregion
504
- //#region runtime/revalidateCache.ts
507
+ // runtime/revalidateCache.ts
505
508
  var isObjectRetry = (arg) => typeof arg === "object";
506
509
  var createRetry = (arg) => {
507
510
  if (arg === void 0) return null;
@@ -519,23 +522,27 @@ var getRetry = (routeItem) => {
519
522
  delay: routeRetry ? routeRetry.delay : globalRetry?.delay || 0
520
523
  };
521
524
  };
522
- var createRevalidateCache = (routerState) => {
525
+ var createRevalidateCache = (routerState, syncCacheSnapshot) => {
523
526
  const { loaderMap, loadingPromises, contextState } = routerState;
524
527
  const flightOwners = /* @__PURE__ */ new Map();
525
528
  const evict = () => {
526
529
  if (loaderMap.size <= routerConfig.maxCacheSize) return;
527
530
  const oldestKey = loaderMap.keys().next().value;
528
- if (oldestKey) loaderMap.delete(oldestKey);
531
+ if (oldestKey) {
532
+ loaderMap.delete(oldestKey);
533
+ syncCacheSnapshot();
534
+ }
529
535
  };
530
536
  const moveItemToLastPosition = (path) => {
531
537
  const item = loaderMap.get(path);
532
538
  if (item) {
533
539
  loaderMap.delete(path);
534
540
  loaderMap.set(path, item);
541
+ syncCacheSnapshot();
535
542
  }
536
543
  return item;
537
544
  };
538
- const revalidateCache = async ({ routeItem, location, signal, force }, retried = 0) => {
545
+ const revalidateCache = async ({ routeItem, location, signal, force, reason }, retried = 0) => {
539
546
  if (!routeItem?.loader) return;
540
547
  const isCacheItemFresh = createIsCacheItemFresh(loaderMap);
541
548
  const { pathname, search = "" } = location;
@@ -546,6 +553,7 @@ var createRevalidateCache = (routerState) => {
546
553
  owner.abort();
547
554
  loadingPromises.delete(path);
548
555
  flightOwners.delete(path);
556
+ syncCacheSnapshot();
549
557
  } else {
550
558
  moveItemToLastPosition(path);
551
559
  return loadingPromises.get(path);
@@ -582,9 +590,11 @@ var createRevalidateCache = (routerState) => {
582
590
  loaderError: null
583
591
  },
584
592
  timestamp: Date.now(),
585
- staleTime: routeItem.staleTime
593
+ staleTime: routeItem.staleTime,
594
+ reason
586
595
  });
587
596
  evict();
597
+ syncCacheSnapshot();
588
598
  return {
589
599
  data: result,
590
600
  error: null
@@ -605,7 +615,8 @@ var createRevalidateCache = (routerState) => {
605
615
  routeItem,
606
616
  location,
607
617
  signal,
608
- force
618
+ force,
619
+ reason
609
620
  }, retried + 1);
610
621
  } else return {
611
622
  data: null,
@@ -615,17 +626,48 @@ var createRevalidateCache = (routerState) => {
615
626
  if (isOwner()) {
616
627
  loadingPromises.delete(path);
617
628
  flightOwners.delete(path);
629
+ syncCacheSnapshot();
618
630
  }
619
631
  }
620
632
  })();
621
633
  loadingPromises.set(path, promise);
634
+ syncCacheSnapshot();
622
635
  return promise;
623
636
  };
624
637
  return revalidateCache;
625
638
  };
626
- //#endregion
627
- //#region creators/createRouterInstance.ts
639
+ // runtime/syncCacheSnapshot.ts
640
+ var createCacheSnapshot = (loaderMap, loadingPromises) => {
641
+ const entries = [];
642
+ for (const [path, item] of loaderMap) entries.push({
643
+ path,
644
+ data: item.state?.data,
645
+ timestamp: item.timestamp,
646
+ staleTime: item.staleTime,
647
+ reason: item.reason,
648
+ gcExpiresAt: item.gcExpiresAt,
649
+ gcDuration: item.gcDuration,
650
+ isLoading: loadingPromises.has(path)
651
+ });
652
+ for (const path of loadingPromises.keys()) {
653
+ if (loaderMap.has(path)) continue;
654
+ entries.push({
655
+ path,
656
+ data: void 0,
657
+ timestamp: Date.now(),
658
+ staleTime: void 0,
659
+ gcExpiresAt: void 0,
660
+ gcDuration: void 0,
661
+ isLoading: true
662
+ });
663
+ }
664
+ return entries;
665
+ };
666
+ // creators/createRouterInstance.ts
628
667
  var createRouterInstance = (synchronizer) => {
668
+ const loaderMap = /* @__PURE__ */ new Map();
669
+ const loadingPromises = /* @__PURE__ */ new Map();
670
+ const cacheSnapshotState = create([]);
629
671
  const routerState = {
630
672
  routeDataState: create({
631
673
  routeItem: void 0,
@@ -637,12 +679,16 @@ var createRouterInstance = (synchronizer) => {
637
679
  contextState: create({}),
638
680
  blockerState: create("unblocked"),
639
681
  blockedTargetState: create(null),
640
- loaderMap: /* @__PURE__ */ new Map(),
641
- loadingPromises: /* @__PURE__ */ new Map()
682
+ cacheSnapshotState,
683
+ loaderMap,
684
+ loadingPromises
685
+ };
686
+ const syncCacheSnapshot = () => {
687
+ if (routerConfig.logged) cacheSnapshotState.setState(createCacheSnapshot(loaderMap, loadingPromises));
642
688
  };
643
- const revalidateCache = createRevalidateCache(routerState);
644
- const navigate = createNavigate(routerState, revalidateCache);
645
- const invalidate = createInvalidate(routerState, revalidateCache);
689
+ const revalidateCache = createRevalidateCache(routerState, syncCacheSnapshot);
690
+ const navigate = createNavigate(routerState, revalidateCache, syncCacheSnapshot);
691
+ const invalidate = createInvalidate(routerState, revalidateCache, syncCacheSnapshot);
646
692
  const prefetch = createPrefetch(routerState, revalidateCache);
647
693
  const getCurrentAction = (actionKey) => {
648
694
  const { routeItem, location } = routerState.routeDataState.getState();
@@ -666,7 +712,8 @@ var createRouterInstance = (synchronizer) => {
666
712
  runtime: {
667
713
  navigate,
668
714
  invalidate,
669
- prefetch
715
+ prefetch,
716
+ syncCacheSnapshot
670
717
  },
671
718
  hooks: {
672
719
  useBlockerState: () => useGlobalState(routerState.blockerState, synchronizer),
@@ -762,6 +809,7 @@ var createRouterInstance = (synchronizer) => {
762
809
  const state = routerState.routeDataState;
763
810
  return synchronizer(state.subscribe, () => callback(state.getState()));
764
811
  },
812
+ useCacheSnapshot: () => useGlobalState(routerState.cacheSnapshotState, synchronizer)[0],
765
813
  useSetLocation: () => (location) => routerState.routeDataState.setState((prevState) => ({
766
814
  ...prevState,
767
815
  location
@@ -769,11 +817,9 @@ var createRouterInstance = (synchronizer) => {
769
817
  }
770
818
  };
771
819
  };
772
- //#endregion
773
- //#region instance.ts
820
+ // instance.ts
774
821
  var router = createRouterInstance(useSyncExternalStore);
775
- //#endregion
776
- //#region hooks/useNavigation.ts
822
+ // hooks/useNavigation.ts
777
823
  var useNavigation = () => {
778
824
  const { navigate } = router.runtime;
779
825
  const { useRouteDataSelector, useBlockerState } = router.hooks;
@@ -805,8 +851,7 @@ var useNavigation = () => {
805
851
  navigate(parseWindowLocation(window.location));
806
852
  }, [navigate]);
807
853
  };
808
- //#endregion
809
- //#region hooks/useApplyCustomAnimation.ts
854
+ // hooks/useApplyCustomAnimation.ts
810
855
  var useApplyCustomAnimation = (animationDuration) => {
811
856
  useEffect(() => {
812
857
  if (!animationDuration) return;
@@ -817,34 +862,29 @@ var useApplyCustomAnimation = (animationDuration) => {
817
862
  return () => style.remove();
818
863
  }, [animationDuration]);
819
864
  };
820
- //#endregion
821
- //#region hooks/useRestoreScroll.ts
865
+ // hooks/useRestoreScroll.ts
822
866
  var useRestoreScroll = (behavior) => {
823
867
  const { useScrollRestoration } = router.hooks;
824
868
  const { defaultScrollRestorationBehavior = "auto" } = routerConfig;
825
869
  return useScrollRestoration(behavior ?? defaultScrollRestorationBehavior);
826
870
  };
827
- //#endregion
828
- //#region hooks/useRestoreRouteScroll.ts
871
+ // hooks/useRestoreRouteScroll.ts
829
872
  var useRestoreRouteScroll = (behavior) => {
830
873
  const restoreScroll = useRestoreScroll(behavior);
831
874
  useEffect(restoreScroll, [restoreScroll]);
832
875
  };
833
- //#endregion
834
- //#region hooks/useSetRouterConfig.ts
876
+ // hooks/useSetRouterConfig.ts
835
877
  var useSetRouterConfig = (routerProps) => {
836
878
  useLayoutEffect(() => routerConfig.configure(routerProps), [routerProps]);
837
879
  };
838
- //#endregion
839
- //#region hooks/useSetInitialContext.ts
880
+ // hooks/useSetInitialContext.ts
840
881
  var useSetInitialContext = (initialContext) => {
841
882
  const [, setContext] = router.hooks.useContextState();
842
883
  useEffect(() => {
843
884
  if (initialContext) setContext(initialContext);
844
885
  }, [initialContext, setContext]);
845
886
  };
846
- //#endregion
847
- //#region hooks/useReload.ts
887
+ // hooks/useReload.ts
848
888
  var useReload = () => {
849
889
  const { invalidate } = router.runtime;
850
890
  useEffect(() => {
@@ -862,20 +902,18 @@ var useReload = () => {
862
902
  return () => window.removeEventListener("online", handler);
863
903
  }, [invalidate]);
864
904
  };
865
- //#endregion
866
- //#region utils/renderElement.tsx
905
+ // utils/renderElement.tsx
867
906
  var renderElement = (Component) => {
868
907
  if (!Component) return null;
869
908
  if (typeof Component !== "function") return Component;
870
909
  return /* @__PURE__ */ jsx(Component, {});
871
910
  };
872
- //#endregion
873
- //#region components/Router.tsx
911
+ // components/Router.tsx
874
912
  var EmptyBoundary = ({ children }) => children;
875
913
  var IS_MOBILE = isMobile();
876
914
  var MOBILE_CACHE_SIZE = 60;
877
915
  var DESKTOP_CACHE_SIZE = 150;
878
- var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, defaultMinLoaderDuration = 0, revalidateOnFocus = false, revalidateOnReconnect = false, maxCacheSize = IS_MOBILE ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE, defaultPrefetch = IS_MOBILE ? "viewport" : "hover", defaultHoverPrefetchDelay = 150, defaultScrollRestorationBehavior = "auto", errorBoundary: ErrorBoundary = EmptyBoundary }) => {
916
+ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration, defaultLoaderFallback, defaultErrorElement, defaultRetry, defaultStaleTime, context: initialContext, isAnimated = false, defaultMinLoaderDuration = 0, revalidateOnFocus = false, revalidateOnReconnect = false, maxCacheSize = IS_MOBILE ? MOBILE_CACHE_SIZE : DESKTOP_CACHE_SIZE, defaultPrefetch = IS_MOBILE ? "viewport" : "hover", defaultHoverPrefetchDelay = 150, defaultScrollRestorationBehavior = "auto", errorBoundary: ErrorBoundary = EmptyBoundary, logged = false }) => {
879
917
  const { useRouteDataSelector } = router.hooks;
880
918
  const routeItem = useRouteDataSelector((state) => state.routeItem);
881
919
  const location = useRouteDataSelector((state) => state.location);
@@ -896,7 +934,8 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
896
934
  maxCacheSize,
897
935
  revalidateOnFocus,
898
936
  revalidateOnReconnect,
899
- defaultScrollRestorationBehavior
937
+ defaultScrollRestorationBehavior,
938
+ logged
900
939
  });
901
940
  useApplyCustomAnimation(animationDuration);
902
941
  useSetInitialContext(initialContext);
@@ -912,11 +951,9 @@ var Router = ({ routes, defaultBeforeLoad, defaultAfterLoad, animationDuration,
912
951
  children: content
913
952
  }));
914
953
  };
915
- //#endregion
916
- //#region hooks/useNavigate.ts
954
+ // hooks/useNavigate.ts
917
955
  var useNavigate = router.hooks.useNavigate;
918
- //#endregion
919
- //#region components/Link.tsx
956
+ // components/Link.tsx
920
957
  var VIEWPORT_DWELL_MS = 250;
921
958
  var defaultAs = (props) => /* @__PURE__ */ jsx("a", { ...props });
922
959
  var comparator = (to, pathname, exact) => to === "/" ? pathname === "/" : exact ? pathname === to : pathname === to || pathname?.startsWith(`${to}/`);
@@ -1043,8 +1080,7 @@ var Link = ({ children, to, path, params, search = "", state, as = defaultAs, pr
1043
1080
  isPending
1044
1081
  });
1045
1082
  };
1046
- //#endregion
1047
- //#region hooks/useParams.ts
1083
+ // hooks/useParams.ts
1048
1084
  /**
1049
1085
  * Route params of the current location.
1050
1086
  *
@@ -1053,20 +1089,16 @@ var Link = ({ children, to, path, params, search = "", state, as = defaultAs, pr
1053
1089
  * - `useParams<{ ... }>()` — legacy manual shape, kept for compatibility.
1054
1090
  */
1055
1091
  var useParams = () => router.hooks.useParams();
1056
- //#endregion
1057
- //#region hooks/useLocation.ts
1092
+ // hooks/useLocation.ts
1058
1093
  var useLocation = () => router.hooks.useRouteDataSelector((state) => state.location);
1059
- //#endregion
1060
- //#region hooks/useLoaderState.ts
1094
+ // hooks/useLoaderState.ts
1061
1095
  var useLoaderState = () => {
1062
1096
  const { useRouteDataSelector } = router.hooks;
1063
1097
  return useRouteDataSelector((state) => state.loaderState);
1064
1098
  };
1065
- //#endregion
1066
- //#region hooks/useInvalidate.ts
1099
+ // hooks/useInvalidate.ts
1067
1100
  var useInvalidate = () => router.runtime.invalidate;
1068
- //#endregion
1069
- //#region hooks/useBlocker.ts
1101
+ // hooks/useBlocker.ts
1070
1102
  var useBlocker = (blockerFn) => {
1071
1103
  const { hooks: { useBlockerState, useContextState, useBlockedTargetState }, runtime: { navigate } } = router;
1072
1104
  const [blockerState, setBlockerState] = useBlockerState();
@@ -1099,17 +1131,14 @@ var useBlocker = (blockerFn) => {
1099
1131
  }, [setBlockerState, setNextLocation])
1100
1132
  };
1101
1133
  };
1102
- //#endregion
1103
- //#region hooks/useAction.ts
1134
+ // hooks/useAction.ts
1104
1135
  var useAction = router.hooks.useAction;
1105
- //#endregion
1106
- //#region hooks/useRouteStatus.ts
1136
+ // hooks/useRouteStatus.ts
1107
1137
  function useRouteStatus(predicate) {
1108
1138
  const { useRouteDataSelector } = router.hooks;
1109
1139
  return useRouteDataSelector(({ status }) => predicate ? predicate(status) : status);
1110
1140
  }
1111
- //#endregion
1112
- //#region hooks/useRouterContext.ts
1141
+ // hooks/useRouterContext.ts
1113
1142
  var useRouterContext = () => {
1114
1143
  const [context, setContext] = router.hooks.useContextState();
1115
1144
  return {
@@ -1117,8 +1146,7 @@ var useRouterContext = () => {
1117
1146
  setContext
1118
1147
  };
1119
1148
  };
1120
- //#endregion
1121
- //#region hooks/useSearchParams.ts
1149
+ // hooks/useSearchParams.ts
1122
1150
  var useLatest = (value) => {
1123
1151
  const ref = useRef(value);
1124
1152
  useEffect(() => {
@@ -1155,13 +1183,14 @@ var useSearchParams = () => {
1155
1183
  currentParams.delete(param);
1156
1184
  (Array.isArray(value) ? value : [value]).forEach((v) => currentParams.append(param, v));
1157
1185
  navigateWithSearchParams(currentParams);
1158
- } else if (typeof param === "function") navigateWithSearchParams(param(currentParams));
1159
- else throw new Error("useSearchParams first argument must be either function or string");
1186
+ } else if (typeof param === "function") {
1187
+ const newParams = param(currentParams);
1188
+ navigateWithSearchParams(newParams);
1189
+ } else throw new Error("useSearchParams first argument must be either function or string");
1160
1190
  }, [navigateWithSearchParams, searchRef])
1161
1191
  };
1162
1192
  };
1163
- //#endregion
1164
- //#region hooks/useSubmitAction.ts
1193
+ // hooks/useSubmitAction.ts
1165
1194
  var useSubmitAction = (action, options) => {
1166
1195
  const currentAction = router.hooks.useAction(action, options);
1167
1196
  const [data, setData] = useState();
@@ -1188,8 +1217,14 @@ var useSubmitAction = (action, options) => {
1188
1217
  isSubmitting
1189
1218
  };
1190
1219
  };
1191
- //#endregion
1192
- //#region utils/createLazyComponent.tsx
1220
+ // hooks/useCacheSnapshot.ts
1221
+ /** Requires `<Router logged>` — otherwise the snapshot stays empty. */
1222
+ var useCacheSnapshot = () => {
1223
+ const snapshot = router.hooks.useCacheSnapshot();
1224
+ useEffect(() => router.runtime.syncCacheSnapshot(), []);
1225
+ return snapshot;
1226
+ };
1227
+ // utils/createLazyComponent.tsx
1193
1228
  var createLazyComponent = (importFn, fallback) => {
1194
1229
  const load = () => importFn().then((module) => ({ default: module.default || module }));
1195
1230
  const LazyComp = lazy$1(load);
@@ -1202,11 +1237,9 @@ var createLazyComponent = (importFn, fallback) => {
1202
1237
  preloadElement: load
1203
1238
  };
1204
1239
  };
1205
- //#endregion
1206
- //#region types.ts
1240
+ // types.ts
1207
1241
  var LAZY_MARKER = Symbol("clear-router-lazy");
1208
- //#endregion
1209
- //#region creators/createRouter.ts
1242
+ // creators/createRouter.ts
1210
1243
  var isLazy = (component) => typeof component === "object" && component !== null && LAZY_MARKER in component;
1211
1244
  var resolve = (component, fallback) => isLazy(component) ? createLazyComponent(component.importFn, fallback).Component : component;
1212
1245
  var parseClientRouteItem = (el, parentPattern = "", inheritedLayouts = []) => {
@@ -1223,11 +1256,9 @@ var parseClientRouteItem = (el, parentPattern = "", inheritedLayouts = []) => {
1223
1256
  }, ...el.children?.flatMap((child) => parseClientRouteItem(child, pattern, layouts)) ?? []];
1224
1257
  };
1225
1258
  var createRouter = (clientList) => clientList.flatMap((el) => parseClientRouteItem(el));
1226
- //#endregion
1227
- //#region utils/lazy.ts
1259
+ // utils/lazy.ts
1228
1260
  var lazy = (importFn) => ({
1229
1261
  [LAZY_MARKER]: true,
1230
1262
  importFn
1231
1263
  });
1232
- //#endregion
1233
- export { Link, Router, createRouter, lazy, useAction, useBlocker, useInvalidate, useLoaderState, useLocation, useNavigate, useParams, useRestoreScroll, useRouteStatus, useRouterContext, useSearchParams, useSubmitAction };
1264
+ export { Link, Router, createRouter, lazy, useAction, useBlocker, useCacheSnapshot, useInvalidate, useLoaderState, useLocation, useNavigate, useParams, useRestoreScroll, useRouteStatus, useRouterContext, useSearchParams, useSubmitAction };
@@ -1,2 +1,2 @@
1
1
  import { type InvalidateOptions, InvalidateResult, RevalidateCache, RouterState } from '../types';
2
- export declare const createInvalidate: ({ routeDataState, loaderMap }: RouterState, revalidateCache: RevalidateCache) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
2
+ export declare const createInvalidate: ({ routeDataState, loaderMap }: RouterState, revalidateCache: RevalidateCache, syncCacheSnapshot: () => void) => (pathList?: string | string[], options?: InvalidateOptions) => Promise<InvalidateResult[]>;
@@ -1,2 +1,2 @@
1
1
  import { Location, RevalidateCache, RouterState } from '../types';
2
- export declare const createNavigate: (routerState: RouterState, revalidateCache: RevalidateCache) => (rawLocation: Location) => Promise<void>;
2
+ export declare const createNavigate: (routerState: RouterState, revalidateCache: RevalidateCache, syncCacheSnapshot: () => void) => (rawLocation: Location) => Promise<void>;
@@ -1,2 +1,2 @@
1
1
  import { LoadingPromise, RevalidateCacheArgs, RouterState } from '../types';
2
- export declare const createRevalidateCache: (routerState: RouterState) => ({ routeItem, location, signal, force }: RevalidateCacheArgs, retried?: number) => LoadingPromise;
2
+ export declare const createRevalidateCache: (routerState: RouterState, syncCacheSnapshot: () => void) => ({ routeItem, location, signal, force, reason }: RevalidateCacheArgs, retried?: number) => LoadingPromise;
@@ -0,0 +1,2 @@
1
+ import { CacheSnapshot, LoaderStateItem, LoadingPromise } from '../types';
2
+ export declare const createCacheSnapshot: (loaderMap: Map<string, LoaderStateItem>, loadingPromises: Map<string, LoadingPromise>) => CacheSnapshot;
package/dist/types.d.ts CHANGED
@@ -63,11 +63,13 @@ export type Location = {
63
63
  prevLocation?: Omit<Location, 'state' | 'prevLocation'>;
64
64
  };
65
65
  export type BlockerState = 'blocked' | 'unblocked' | 'charged';
66
+ export type CacheReason = 'navigation' | 'prefetch' | 'invalidate' | 'polling';
66
67
  export type RevalidateCacheArgs = {
67
68
  location: Location;
68
69
  routeItem?: RouteItem;
69
70
  signal?: AbortSignal;
70
71
  force?: boolean;
72
+ reason?: CacheReason;
71
73
  };
72
74
  export type LoaderState<T = unknown> = {
73
75
  data: T;
@@ -105,13 +107,29 @@ export type RouterProps = {
105
107
  revalidateOnFocus?: boolean;
106
108
  revalidateOnReconnect?: boolean;
107
109
  context?: Record<string, unknown>;
110
+ /** Enables cache snapshot tracking for devtools. `useCacheSnapshot` returns an empty list without it. */
111
+ logged?: boolean;
108
112
  };
109
113
  export type LoaderStateItem = {
110
114
  state: LoaderState;
111
115
  timestamp: number;
112
116
  staleTime: number | undefined;
117
+ reason?: CacheReason;
113
118
  gcTimeout?: number;
119
+ gcExpiresAt?: number;
120
+ gcDuration?: number;
114
121
  };
122
+ export type CacheSnapshotEntry = {
123
+ path: string;
124
+ data: unknown;
125
+ timestamp: number;
126
+ staleTime: number | undefined;
127
+ reason?: CacheReason;
128
+ gcExpiresAt: number | undefined;
129
+ gcDuration: number | undefined;
130
+ isLoading: boolean;
131
+ };
132
+ export type CacheSnapshot = CacheSnapshotEntry[];
115
133
  export type LoadingPromise = Promise<{
116
134
  data: unknown;
117
135
  error: null;
@@ -126,6 +144,7 @@ export type RouterState = {
126
144
  contextState: Store<Record<string, unknown>>;
127
145
  blockerState: Store<BlockerState>;
128
146
  blockedTargetState: Store<Location | null>;
147
+ cacheSnapshotState: Store<CacheSnapshot>;
129
148
  loaderMap: Map<string, LoaderStateItem>;
130
149
  loadingPromises: Map<string, LoadingPromise>;
131
150
  };
@@ -134,6 +153,7 @@ export type RouterType = {
134
153
  navigate(arg: Location): Promise<void>;
135
154
  invalidate(pathList?: string | string[], options?: InvalidateOptions): Promise<InvalidateResult[]>;
136
155
  prefetch(location: Location, signal?: AbortSignal): Promise<void>;
156
+ syncCacheSnapshot(): void;
137
157
  };
138
158
  hooks: {
139
159
  useBlockerState(): ReturnType<typeof useGlobalState<BlockerState>>;
@@ -151,6 +171,7 @@ export type RouterType = {
151
171
  }>;
152
172
  useScrollRestoration(restorationBehavior: ScrollRestorationBehavior): () => void;
153
173
  useRouteDataSelector<T>(callback: (arg: RouteData) => T): T;
174
+ useCacheSnapshot(): CacheSnapshot;
154
175
  useSetLocation(): (location: Location) => void;
155
176
  };
156
177
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clear-react-router",
3
- "version": "2.4.8",
3
+ "version": "2.4.9",
4
4
  "description": "A lightweight routing library for React applications",
5
5
  "author": "Andrew Bubnov",
6
6
  "scripts": {