@tanstack/query-persist-client-core 4.24.6 → 4.24.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.
@@ -1,6 +1,7 @@
1
1
  /// <reference types="jest" />
2
2
  import type { QueryClientConfig } from '@tanstack/query-core';
3
3
  import { QueryClient } from '@tanstack/query-core';
4
+ import type { Persister } from '@tanstack/query-persist-client-core';
4
5
  export declare function createQueryClient(config?: QueryClientConfig): QueryClient;
5
6
  export declare const mockLogger: {
6
7
  log: jest.Mock<any, any>;
@@ -8,3 +9,5 @@ export declare const mockLogger: {
8
9
  error: jest.Mock<any, any>;
9
10
  };
10
11
  export declare function sleep(timeout: number): Promise<void>;
12
+ export declare const createMockPersister: () => Persister;
13
+ export declare const createSpyablePersister: () => Persister;
@@ -1,11 +1,22 @@
1
1
  import { hydrate, dehydrate } from '@tanstack/query-core';
2
2
 
3
+ /**
4
+ * Checks if emitted event is about cache change and not about observers.
5
+ * Useful for persist, where we only want to trigger save when cache is changed.
6
+ */
7
+ const cacheableEventTypes = ['added', 'removed', 'updated'];
8
+
9
+ function isCacheableEventType(eventType) {
10
+ return cacheableEventTypes.includes(eventType);
11
+ }
3
12
  /**
4
13
  * Restores persisted data to the QueryCache
5
14
  * - data obtained from persister.restoreClient
6
15
  * - data is hydrated using hydrateOptions
7
16
  * If data is expired, busted, empty, or throws, it runs persister.removeClient
8
17
  */
18
+
19
+
9
20
  async function persistQueryClientRestore({
10
21
  queryClient,
11
22
  persister,
@@ -64,11 +75,15 @@ async function persistQueryClientSave({
64
75
  */
65
76
 
66
77
  function persistQueryClientSubscribe(props) {
67
- const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe(() => {
68
- persistQueryClientSave(props);
78
+ const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe(event => {
79
+ if (isCacheableEventType(event.type)) {
80
+ persistQueryClientSave(props);
81
+ }
69
82
  });
70
- const unusbscribeMutationCache = props.queryClient.getMutationCache().subscribe(() => {
71
- persistQueryClientSave(props);
83
+ const unusbscribeMutationCache = props.queryClient.getMutationCache().subscribe(event => {
84
+ if (isCacheableEventType(event.type)) {
85
+ persistQueryClientSave(props);
86
+ }
72
87
  });
73
88
  return () => {
74
89
  unsubscribeQueryCache();
@@ -1 +1 @@
1
- {"version":3,"file":"persist.esm.js","sources":["../../src/persist.ts"],"sourcesContent":["import type {\n QueryClient,\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from '@tanstack/query-core'\nimport { dehydrate, hydrate } from '@tanstack/query-core'\n\nexport type Promisable<T> = T | PromiseLike<T>\n\nexport interface Persister {\n persistClient(persistClient: PersistedClient): Promisable<void>\n restoreClient(): Promisable<PersistedClient | undefined>\n removeClient(): Promisable<void>\n}\n\nexport interface PersistedClient {\n timestamp: number\n buster: string\n clientState: DehydratedState\n}\n\nexport interface PersistQueryClienRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /** The Persister interface for storing and restoring the cache\n * to/from a persisted location */\n persister: Persister\n /** A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string */\n buster?: string\n}\n\nexport interface PersistedQueryClientRestoreOptions\n extends PersistQueryClienRootOptions {\n /** The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\nexport interface PersistedQueryClientSaveOptions\n extends PersistQueryClienRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\nexport interface PersistQueryClientOptions\n extends PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClienRootOptions {}\n\n/**\n * Restores persisted data to the QueryCache\n * - data obtained from persister.restoreClient\n * - data is hydrated using hydrateOptions\n * If data is expired, busted, empty, or throws, it runs persister.removeClient\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 1000 * 60 * 60 * 24,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n queryClient.getLogger().error(err)\n queryClient\n .getLogger()\n .warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n persister.removeClient()\n }\n}\n\n/**\n * Persists data from the QueryCache\n * - data dehydrated using dehydrateOptions\n * - data is persisted using persister.persistClient\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting)\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe(() => {\n persistQueryClientSave(props)\n })\n\n const unusbscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe(() => {\n persistQueryClientSave(props)\n })\n\n return () => {\n unsubscribeQueryCache()\n unusbscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n"],"names":["persistQueryClientRestore","queryClient","persister","maxAge","buster","hydrateOptions","persistedClient","restoreClient","timestamp","expired","Date","now","busted","removeClient","hydrate","clientState","err","process","env","NODE_ENV","getLogger","error","warn","persistQueryClientSave","dehydrateOptions","persistClient","dehydrate","persistQueryClientSubscribe","props","unsubscribeQueryCache","getQueryCache","subscribe","unusbscribeMutationCache","getMutationCache","persistQueryClient","hasUnsubscribed","persistQueryClientUnsubscribe","unsubscribe","restorePromise","then"],"mappings":";;AAsDA;AACA;AACA;AACA;AACA;AACA;AACO,eAAeA,yBAAf,CAAyC;EAC9CC,WAD8C;EAE9CC,SAF8C;AAG9CC,EAAAA,MAAM,GAAG,IAAO,GAAA,EAAP,GAAY,EAAZ,GAAiB,EAHoB;AAI9CC,EAAAA,MAAM,GAAG,EAJqC;AAK9CC,EAAAA,cAAAA;AAL8C,CAAzC,EAMgC;EACrC,IAAI;AACF,IAAA,MAAMC,eAAe,GAAG,MAAMJ,SAAS,CAACK,aAAV,EAA9B,CAAA;;AAEA,IAAA,IAAID,eAAJ,EAAqB;MACnB,IAAIA,eAAe,CAACE,SAApB,EAA+B;QAC7B,MAAMC,OAAO,GAAGC,IAAI,CAACC,GAAL,KAAaL,eAAe,CAACE,SAA7B,GAAyCL,MAAzD,CAAA;AACA,QAAA,MAAMS,MAAM,GAAGN,eAAe,CAACF,MAAhB,KAA2BA,MAA1C,CAAA;;QACA,IAAIK,OAAO,IAAIG,MAAf,EAAuB;AACrBV,UAAAA,SAAS,CAACW,YAAV,EAAA,CAAA;AACD,SAFD,MAEO;UACLC,OAAO,CAACb,WAAD,EAAcK,eAAe,CAACS,WAA9B,EAA2CV,cAA3C,CAAP,CAAA;AACD,SAAA;AACF,OARD,MAQO;AACLH,QAAAA,SAAS,CAACW,YAAV,EAAA,CAAA;AACD,OAAA;A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BG,wBAAwB,EAAA,CAAA;GAF1B,CAAA;AAID,CAAA;AAED;AACA;AACA;;AACO,SAASE,kBAAT,CACLN,KADK,EAEwB;EAC7B,IAAIO,eAAe,GAAG,KAAtB,CAAA;AACA,EAAA,IAAIC,6BAAJ,CAAA;;EACA,MAAMC,WAAW,GAAG,MAAM;AACxBF,IAAAA,eAAe,GAAG,IAAlB,CAAA;IACAC,6BAA6B,IAAA,IAA7B,YAAAA,6BAA6B,EAAA,CAAA;AAC9B,GAHD,CAH6B;;;EAS7B,MAAME,cAAc,GAAGtC,yBAAyB,CAAC4B,KAAD,CAAzB,CAAiCW,IAAjC,CAAsC,MAAM;IACjE,IAAI,CAACJ,eAAL,EAAsB;AACpB;AACAC,MAAAA,6BAA6B,GAAGT,2BAA2B,CAACC,KAAD,CAA3D,CAAA;AACD,KAAA;AACF,GALsB,CAAvB,CAAA;AAOA,EAAA,OAAO,CAACS,WAAD,EAAcC,cAAd,CAAP,CAAA;AACD;;;;"}
1
+ {"version":3,"file":"persist.esm.js","sources":["../../src/persist.ts"],"sourcesContent":["import type {\n QueryClient,\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from '@tanstack/query-core'\nimport { dehydrate, hydrate } from '@tanstack/query-core'\nimport type { NotifyEventType } from '@tanstack/query-core'\n\nexport type Promisable<T> = T | PromiseLike<T>\n\nexport interface Persister {\n persistClient(persistClient: PersistedClient): Promisable<void>\n restoreClient(): Promisable<PersistedClient | undefined>\n removeClient(): Promisable<void>\n}\n\nexport interface PersistedClient {\n timestamp: number\n buster: string\n clientState: DehydratedState\n}\n\nexport interface PersistQueryClienRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /** The Persister interface for storing and restoring the cache\n * to/from a persisted location */\n persister: Persister\n /** A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string */\n buster?: string\n}\n\nexport interface PersistedQueryClientRestoreOptions\n extends PersistQueryClienRootOptions {\n /** The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\nexport interface PersistedQueryClientSaveOptions\n extends PersistQueryClienRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\nexport interface PersistQueryClientOptions\n extends PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClienRootOptions {}\n\n/**\n * Checks if emitted event is about cache change and not about observers.\n * Useful for persist, where we only want to trigger save when cache is changed.\n */\nconst cacheableEventTypes: Array<NotifyEventType> = [\n 'added',\n 'removed',\n 'updated',\n]\n\nfunction isCacheableEventType(eventType: NotifyEventType) {\n return cacheableEventTypes.includes(eventType)\n}\n\n/**\n * Restores persisted data to the QueryCache\n * - data obtained from persister.restoreClient\n * - data is hydrated using hydrateOptions\n * If data is expired, busted, empty, or throws, it runs persister.removeClient\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 1000 * 60 * 60 * 24,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n queryClient.getLogger().error(err)\n queryClient\n .getLogger()\n .warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n persister.removeClient()\n }\n}\n\n/**\n * Persists data from the QueryCache\n * - data dehydrated using dehydrateOptions\n * - data is persisted using persister.persistClient\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting)\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (isCacheableEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n const unusbscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheableEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unusbscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n"],"names":["cacheableEventTypes","isCacheableEventType","eventType","includes","persistQueryClientRestore","queryClient","persister","maxAge","buster","hydrateOptions","persistedClient","restoreClient","timestamp","expired","Date","now","busted","removeClient","hydrate","clientState","err","process","env","NODE_ENV","getLogger","error","warn","persistQueryClientSave","dehydrateOptions","persistClient","dehydrate","persistQueryClientSubscribe","props","unsubscribeQueryCache","getQueryCache","subscribe","event","type","unusbscribeMutationCache","getMutationCache","persistQueryClient","hasUnsubscribed","persistQueryClientUnsubscribe","unsubscribe","restorePromise","then"],"mappings":";;AAuDA;AACA;AACA;AACA;AACA,MAAMA,mBAA2C,GAAG,CAClD,OADkD,EAElD,SAFkD,EAGlD,S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wB;EAC7B,IAAIS,eAAe,GAAG,KAAtB,CAAA;AACA,EAAA,IAAIC,6BAAJ,CAAA;;EACA,MAAMC,WAAW,GAAG,MAAM;AACxBF,IAAAA,eAAe,GAAG,IAAlB,CAAA;IACAC,6BAA6B,IAAA,IAA7B,YAAAA,6BAA6B,EAAA,CAAA;AAC9B,GAHD,CAH6B;;;EAS7B,MAAME,cAAc,GAAGxC,yBAAyB,CAAC4B,KAAD,CAAzB,CAAiCa,IAAjC,CAAsC,MAAM;IACjE,IAAI,CAACJ,eAAL,EAAsB;AACpB;AACAC,MAAAA,6BAA6B,GAAGX,2BAA2B,CAACC,KAAD,CAA3D,CAAA;AACD,KAAA;AACF,GALsB,CAAvB,CAAA;AAOA,EAAA,OAAO,CAACW,WAAD,EAAcC,cAAd,CAAP,CAAA;AACD;;;;"}
@@ -4,12 +4,23 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var queryCore = require('@tanstack/query-core');
6
6
 
7
+ /**
8
+ * Checks if emitted event is about cache change and not about observers.
9
+ * Useful for persist, where we only want to trigger save when cache is changed.
10
+ */
11
+ const cacheableEventTypes = ['added', 'removed', 'updated'];
12
+
13
+ function isCacheableEventType(eventType) {
14
+ return cacheableEventTypes.includes(eventType);
15
+ }
7
16
  /**
8
17
  * Restores persisted data to the QueryCache
9
18
  * - data obtained from persister.restoreClient
10
19
  * - data is hydrated using hydrateOptions
11
20
  * If data is expired, busted, empty, or throws, it runs persister.removeClient
12
21
  */
22
+
23
+
13
24
  async function persistQueryClientRestore({
14
25
  queryClient,
15
26
  persister,
@@ -68,11 +79,15 @@ async function persistQueryClientSave({
68
79
  */
69
80
 
70
81
  function persistQueryClientSubscribe(props) {
71
- const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe(() => {
72
- persistQueryClientSave(props);
82
+ const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe(event => {
83
+ if (isCacheableEventType(event.type)) {
84
+ persistQueryClientSave(props);
85
+ }
73
86
  });
74
- const unusbscribeMutationCache = props.queryClient.getMutationCache().subscribe(() => {
75
- persistQueryClientSave(props);
87
+ const unusbscribeMutationCache = props.queryClient.getMutationCache().subscribe(event => {
88
+ if (isCacheableEventType(event.type)) {
89
+ persistQueryClientSave(props);
90
+ }
76
91
  });
77
92
  return () => {
78
93
  unsubscribeQueryCache();
@@ -1 +1 @@
1
- {"version":3,"file":"persist.js","sources":["../../src/persist.ts"],"sourcesContent":["import type {\n QueryClient,\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from '@tanstack/query-core'\nimport { dehydrate, hydrate } from '@tanstack/query-core'\n\nexport type Promisable<T> = T | PromiseLike<T>\n\nexport interface Persister {\n persistClient(persistClient: PersistedClient): Promisable<void>\n restoreClient(): Promisable<PersistedClient | undefined>\n removeClient(): Promisable<void>\n}\n\nexport interface PersistedClient {\n timestamp: number\n buster: string\n clientState: DehydratedState\n}\n\nexport interface PersistQueryClienRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /** The Persister interface for storing and restoring the cache\n * to/from a persisted location */\n persister: Persister\n /** A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string */\n buster?: string\n}\n\nexport interface PersistedQueryClientRestoreOptions\n extends PersistQueryClienRootOptions {\n /** The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\nexport interface PersistedQueryClientSaveOptions\n extends PersistQueryClienRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\nexport interface PersistQueryClientOptions\n extends PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClienRootOptions {}\n\n/**\n * Restores persisted data to the QueryCache\n * - data obtained from persister.restoreClient\n * - data is hydrated using hydrateOptions\n * If data is expired, busted, empty, or throws, it runs persister.removeClient\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 1000 * 60 * 60 * 24,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n queryClient.getLogger().error(err)\n queryClient\n .getLogger()\n .warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n persister.removeClient()\n }\n}\n\n/**\n * Persists data from the QueryCache\n * - data dehydrated using dehydrateOptions\n * - data is persisted using persister.persistClient\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting)\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe(() => {\n persistQueryClientSave(props)\n })\n\n const unusbscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe(() => {\n persistQueryClientSave(props)\n })\n\n return () => {\n unsubscribeQueryCache()\n unusbscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n"],"names":["persistQueryClientRestore","queryClient","persister","maxAge","buster","hydrateOptions","persistedClient","restoreClient","timestamp","expired","Date","now","busted","removeClient","hydrate","clientState","err","process","env","NODE_ENV","getLogger","error","warn","persistQueryClientSave","dehydrateOptions","persistClient","dehydrate","persistQueryClientSubscribe","props","unsubscribeQueryCache","getQueryCache","subscribe","unusbscribeMutationCache","getMutationCache","persistQueryClient","hasUnsubscribed","persistQueryClientUnsubscribe","unsubscribe","restorePromise","then"],"mappings":";;;;;;AAsDA;AACA;AACA;AACA;AACA;AACA;AACO,eAAeA,yBAAf,CAAyC;EAC9CC,WAD8C;EAE9CC,SAF8C;AAG9CC,EAAAA,MAAM,GAAG,IAAO,GAAA,EAAP,GAAY,EAAZ,GAAiB,EAHoB;AAI9CC,EAAAA,MAAM,GAAG,EAJqC;AAK9CC,EAAAA,cAAAA;AAL8C,CAAzC,EAMgC;EACrC,IAAI;AACF,IAAA,MAAMC,eAAe,GAAG,MAAMJ,SAAS,CAACK,aAAV,EAA9B,CAAA;;AAEA,IAAA,IAAID,eAAJ,EAAqB;MACnB,IAAIA,eAAe,CAACE,SAApB,EAA+B;QAC7B,MAAMC,OAAO,GAAGC,IAAI,CAACC,GAAL,KAAaL,eAAe,CAACE,SAA7B,GAAyCL,MAAzD,CAAA;AACA,QAAA,MAAMS,MAAM,GAAGN,eAAe,CAACF,MAAhB,KAA2BA,MAA1C,CAAA;;QACA,IAAIK,OAAO,IAAIG,MAAf,EAAuB;AACrBV,UAAAA,SAAS,CAACW,YAAV,EAAA,CAAA;AACD,SAFD,MAEO;UACLC,iBAAO,CAACb,WAAD,EAAcK,eAAe,CAACS,WAA9B,EAA2CV,cAA3C,CAAP,CAAA;AACD,SAAA;AACF,OARD,MAQO;AACLH,QAAA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AA,OAAO,MAAM;IACXC,qBAAqB,EAAA,CAAA;IACrBG,wBAAwB,EAAA,CAAA;GAF1B,CAAA;AAID,CAAA;AAED;AACA;AACA;;AACO,SAASE,kBAAT,CACLN,KADK,EAEwB;EAC7B,IAAIO,eAAe,GAAG,KAAtB,CAAA;AACA,EAAA,IAAIC,6BAAJ,CAAA;;EACA,MAAMC,WAAW,GAAG,MAAM;AACxBF,IAAAA,eAAe,GAAG,IAAlB,CAAA;IACAC,6BAA6B,IAAA,IAA7B,YAAAA,6BAA6B,EAAA,CAAA;AAC9B,GAHD,CAH6B;;;EAS7B,MAAME,cAAc,GAAGtC,yBAAyB,CAAC4B,KAAD,CAAzB,CAAiCW,IAAjC,CAAsC,MAAM;IACjE,IAAI,CAACJ,eAAL,EAAsB;AACpB;AACAC,MAAAA,6BAA6B,GAAGT,2BAA2B,CAACC,KAAD,CAA3D,CAAA;AACD,KAAA;AACF,GALsB,CAAvB,CAAA;AAOA,EAAA,OAAO,CAACS,WAAD,EAAcC,cAAd,CAAP,CAAA;AACD;;;;;;;"}
1
+ {"version":3,"file":"persist.js","sources":["../../src/persist.ts"],"sourcesContent":["import type {\n QueryClient,\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from '@tanstack/query-core'\nimport { dehydrate, hydrate } from '@tanstack/query-core'\nimport type { NotifyEventType } from '@tanstack/query-core'\n\nexport type Promisable<T> = T | PromiseLike<T>\n\nexport interface Persister {\n persistClient(persistClient: PersistedClient): Promisable<void>\n restoreClient(): Promisable<PersistedClient | undefined>\n removeClient(): Promisable<void>\n}\n\nexport interface PersistedClient {\n timestamp: number\n buster: string\n clientState: DehydratedState\n}\n\nexport interface PersistQueryClienRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /** The Persister interface for storing and restoring the cache\n * to/from a persisted location */\n persister: Persister\n /** A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string */\n buster?: string\n}\n\nexport interface PersistedQueryClientRestoreOptions\n extends PersistQueryClienRootOptions {\n /** The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\nexport interface PersistedQueryClientSaveOptions\n extends PersistQueryClienRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\nexport interface PersistQueryClientOptions\n extends PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClienRootOptions {}\n\n/**\n * Checks if emitted event is about cache change and not about observers.\n * Useful for persist, where we only want to trigger save when cache is changed.\n */\nconst cacheableEventTypes: Array<NotifyEventType> = [\n 'added',\n 'removed',\n 'updated',\n]\n\nfunction isCacheableEventType(eventType: NotifyEventType) {\n return cacheableEventTypes.includes(eventType)\n}\n\n/**\n * Restores persisted data to the QueryCache\n * - data obtained from persister.restoreClient\n * - data is hydrated using hydrateOptions\n * If data is expired, busted, empty, or throws, it runs persister.removeClient\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 1000 * 60 * 60 * 24,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n queryClient.getLogger().error(err)\n queryClient\n .getLogger()\n .warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n persister.removeClient()\n }\n}\n\n/**\n * Persists data from the QueryCache\n * - data dehydrated using dehydrateOptions\n * - data is persisted using persister.persistClient\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting)\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (isCacheableEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n const unusbscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheableEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unusbscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n"],"names":["cacheableEventTypes","isCacheableEventType","eventType","includes","persistQueryClientRestore","queryClient","persister","maxAge","buster","hydrateOptions","persistedClient","restoreClient","timestamp","expired","Date","now","busted","removeClient","hydrate","clientState","err","process","env","NODE_ENV","getLogger","error","warn","persistQueryClientSave","dehydrateOptions","persistClient","dehydrate","persistQueryClientSubscribe","props","unsubscribeQueryCache","getQueryCache","subscribe","event","type","unusbscribeMutationCache","getMutationCache","persistQueryClient","hasUnsubscribed","persistQueryClientUnsubscribe","unsubscribe","restorePromise","then"],"mappings":";;;;;;AAuDA;AACA;AACA;AACA;AACA,MAAM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AAA;AAED;AACA;AACA;;AACO,SAASE,kBAAT,CACLR,KADK,EAEwB;EAC7B,IAAIS,eAAe,GAAG,KAAtB,CAAA;AACA,EAAA,IAAIC,6BAAJ,CAAA;;EACA,MAAMC,WAAW,GAAG,MAAM;AACxBF,IAAAA,eAAe,GAAG,IAAlB,CAAA;IACAC,6BAA6B,IAAA,IAA7B,YAAAA,6BAA6B,EAAA,CAAA;AAC9B,GAHD,CAH6B;;;EAS7B,MAAME,cAAc,GAAGxC,yBAAyB,CAAC4B,KAAD,CAAzB,CAAiCa,IAAjC,CAAsC,MAAM;IACjE,IAAI,CAACJ,eAAL,EAAsB;AACpB;AACAC,MAAAA,6BAA6B,GAAGX,2BAA2B,CAACC,KAAD,CAA3D,CAAA;AACD,KAAA;AACF,GALsB,CAAvB,CAAA;AAOA,EAAA,OAAO,CAACW,WAAD,EAAcC,cAAd,CAAP,CAAA;AACD;;;;;;;"}
@@ -1,11 +1,22 @@
1
1
  import { hydrate, dehydrate } from '@tanstack/query-core';
2
2
 
3
+ /**
4
+ * Checks if emitted event is about cache change and not about observers.
5
+ * Useful for persist, where we only want to trigger save when cache is changed.
6
+ */
7
+ const cacheableEventTypes = ['added', 'removed', 'updated'];
8
+
9
+ function isCacheableEventType(eventType) {
10
+ return cacheableEventTypes.includes(eventType);
11
+ }
3
12
  /**
4
13
  * Restores persisted data to the QueryCache
5
14
  * - data obtained from persister.restoreClient
6
15
  * - data is hydrated using hydrateOptions
7
16
  * If data is expired, busted, empty, or throws, it runs persister.removeClient
8
17
  */
18
+
19
+
9
20
  async function persistQueryClientRestore({
10
21
  queryClient,
11
22
  persister,
@@ -64,11 +75,15 @@ async function persistQueryClientSave({
64
75
  */
65
76
 
66
77
  function persistQueryClientSubscribe(props) {
67
- const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe(() => {
68
- persistQueryClientSave(props);
78
+ const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe(event => {
79
+ if (isCacheableEventType(event.type)) {
80
+ persistQueryClientSave(props);
81
+ }
69
82
  });
70
- const unusbscribeMutationCache = props.queryClient.getMutationCache().subscribe(() => {
71
- persistQueryClientSave(props);
83
+ const unusbscribeMutationCache = props.queryClient.getMutationCache().subscribe(event => {
84
+ if (isCacheableEventType(event.type)) {
85
+ persistQueryClientSave(props);
86
+ }
72
87
  });
73
88
  return () => {
74
89
  unsubscribeQueryCache();
@@ -1 +1 @@
1
- {"version":3,"file":"persist.mjs","sources":["../../src/persist.ts"],"sourcesContent":["import type {\n QueryClient,\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from '@tanstack/query-core'\nimport { dehydrate, hydrate } from '@tanstack/query-core'\n\nexport type Promisable<T> = T | PromiseLike<T>\n\nexport interface Persister {\n persistClient(persistClient: PersistedClient): Promisable<void>\n restoreClient(): Promisable<PersistedClient | undefined>\n removeClient(): Promisable<void>\n}\n\nexport interface PersistedClient {\n timestamp: number\n buster: string\n clientState: DehydratedState\n}\n\nexport interface PersistQueryClienRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /** The Persister interface for storing and restoring the cache\n * to/from a persisted location */\n persister: Persister\n /** A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string */\n buster?: string\n}\n\nexport interface PersistedQueryClientRestoreOptions\n extends PersistQueryClienRootOptions {\n /** The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\nexport interface PersistedQueryClientSaveOptions\n extends PersistQueryClienRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\nexport interface PersistQueryClientOptions\n extends PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClienRootOptions {}\n\n/**\n * Restores persisted data to the QueryCache\n * - data obtained from persister.restoreClient\n * - data is hydrated using hydrateOptions\n * If data is expired, busted, empty, or throws, it runs persister.removeClient\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 1000 * 60 * 60 * 24,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n queryClient.getLogger().error(err)\n queryClient\n .getLogger()\n .warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n persister.removeClient()\n }\n}\n\n/**\n * Persists data from the QueryCache\n * - data dehydrated using dehydrateOptions\n * - data is persisted using persister.persistClient\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting)\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe(() => {\n persistQueryClientSave(props)\n })\n\n const unusbscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe(() => {\n persistQueryClientSave(props)\n })\n\n return () => {\n unsubscribeQueryCache()\n unusbscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n"],"names":["persistQueryClientRestore","queryClient","persister","maxAge","buster","hydrateOptions","persistedClient","restoreClient","timestamp","expired","Date","now","busted","removeClient","hydrate","clientState","err","process","env","NODE_ENV","getLogger","error","warn","persistQueryClientSave","dehydrateOptions","persistClient","dehydrate","persistQueryClientSubscribe","props","unsubscribeQueryCache","getQueryCache","subscribe","unusbscribeMutationCache","getMutationCache","persistQueryClient","hasUnsubscribed","persistQueryClientUnsubscribe","unsubscribe","restorePromise","then"],"mappings":";;AAsDA;AACA;AACA;AACA;AACA;AACA;AACO,eAAeA,yBAAf,CAAyC;EAC9CC,WAD8C;EAE9CC,SAF8C;AAG9CC,EAAAA,MAAM,GAAG,IAAO,GAAA,EAAP,GAAY,EAAZ,GAAiB,EAHoB;AAI9CC,EAAAA,MAAM,GAAG,EAJqC;AAK9CC,EAAAA,cAAAA;AAL8C,CAAzC,EAMgC;EACrC,IAAI;AACF,IAAA,MAAMC,eAAe,GAAG,MAAMJ,SAAS,CAACK,aAAV,EAA9B,CAAA;;AAEA,IAAA,IAAID,eAAJ,EAAqB;MACnB,IAAIA,eAAe,CAACE,SAApB,EAA+B;QAC7B,MAAMC,OAAO,GAAGC,IAAI,CAACC,GAAL,KAAaL,eAAe,CAACE,SAA7B,GAAyCL,MAAzD,CAAA;AACA,QAAA,MAAMS,MAAM,GAAGN,eAAe,CAACF,MAAhB,KAA2BA,MAA1C,CAAA;;QACA,IAAIK,OAAO,IAAIG,MAAf,EAAuB;AACrBV,UAAAA,SAAS,CAACW,YAAV,EAAA,CAAA;AACD,SAFD,MAEO;UACLC,OAAO,CAACb,WAAD,EAAcK,eAAe,CAACS,WAA9B,EAA2CV,cAA3C,CAAP,CAAA;AACD,SAAA;A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B,CAAjC,CAAA;AAMA,EAAA,OAAO,MAAM;IACXC,qBAAqB,EAAA,CAAA;IACrBG,wBAAwB,EAAA,CAAA;GAF1B,CAAA;AAID,CAAA;AAED;AACA;AACA;;AACO,SAASE,kBAAT,CACLN,KADK,EAEwB;EAC7B,IAAIO,eAAe,GAAG,KAAtB,CAAA;AACA,EAAA,IAAIC,6BAAJ,CAAA;;EACA,MAAMC,WAAW,GAAG,MAAM;AACxBF,IAAAA,eAAe,GAAG,IAAlB,CAAA;IACAC,6BAA6B,IAAA,IAA7B,YAAAA,6BAA6B,EAAA,CAAA;AAC9B,GAHD,CAH6B;;;EAS7B,MAAME,cAAc,GAAGtC,yBAAyB,CAAC4B,KAAD,CAAzB,CAAiCW,IAAjC,CAAsC,MAAM;IACjE,IAAI,CAACJ,eAAL,EAAsB;AACpB;AACAC,MAAAA,6BAA6B,GAAGT,2BAA2B,CAACC,KAAD,CAA3D,CAAA;AACD,KAAA;AACF,GALsB,CAAvB,CAAA;AAOA,EAAA,OAAO,CAACS,WAAD,EAAcC,cAAd,CAAP,CAAA;AACD;;;;"}
1
+ {"version":3,"file":"persist.mjs","sources":["../../src/persist.ts"],"sourcesContent":["import type {\n QueryClient,\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from '@tanstack/query-core'\nimport { dehydrate, hydrate } from '@tanstack/query-core'\nimport type { NotifyEventType } from '@tanstack/query-core'\n\nexport type Promisable<T> = T | PromiseLike<T>\n\nexport interface Persister {\n persistClient(persistClient: PersistedClient): Promisable<void>\n restoreClient(): Promisable<PersistedClient | undefined>\n removeClient(): Promisable<void>\n}\n\nexport interface PersistedClient {\n timestamp: number\n buster: string\n clientState: DehydratedState\n}\n\nexport interface PersistQueryClienRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /** The Persister interface for storing and restoring the cache\n * to/from a persisted location */\n persister: Persister\n /** A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string */\n buster?: string\n}\n\nexport interface PersistedQueryClientRestoreOptions\n extends PersistQueryClienRootOptions {\n /** The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\nexport interface PersistedQueryClientSaveOptions\n extends PersistQueryClienRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\nexport interface PersistQueryClientOptions\n extends PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClienRootOptions {}\n\n/**\n * Checks if emitted event is about cache change and not about observers.\n * Useful for persist, where we only want to trigger save when cache is changed.\n */\nconst cacheableEventTypes: Array<NotifyEventType> = [\n 'added',\n 'removed',\n 'updated',\n]\n\nfunction isCacheableEventType(eventType: NotifyEventType) {\n return cacheableEventTypes.includes(eventType)\n}\n\n/**\n * Restores persisted data to the QueryCache\n * - data obtained from persister.restoreClient\n * - data is hydrated using hydrateOptions\n * If data is expired, busted, empty, or throws, it runs persister.removeClient\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 1000 * 60 * 60 * 24,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n queryClient.getLogger().error(err)\n queryClient\n .getLogger()\n .warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n persister.removeClient()\n }\n}\n\n/**\n * Persists data from the QueryCache\n * - data dehydrated using dehydrateOptions\n * - data is persisted using persister.persistClient\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting)\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (isCacheableEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n const unusbscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheableEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unusbscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n"],"names":["cacheableEventTypes","isCacheableEventType","eventType","includes","persistQueryClientRestore","queryClient","persister","maxAge","buster","hydrateOptions","persistedClient","restoreClient","timestamp","expired","Date","now","busted","removeClient","hydrate","clientState","err","process","env","NODE_ENV","getLogger","error","warn","persistQueryClientSave","dehydrateOptions","persistClient","dehydrate","persistQueryClientSubscribe","props","unsubscribeQueryCache","getQueryCache","subscribe","event","type","unusbscribeMutationCache","getMutationCache","persistQueryClient","hasUnsubscribed","persistQueryClientUnsubscribe","unsubscribe","restorePromise","then"],"mappings":";;AAuDA;AACA;A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1B,CAAA;AAID,CAAA;AAED;AACA;AACA;;AACO,SAASE,kBAAT,CACLR,KADK,EAEwB;EAC7B,IAAIS,eAAe,GAAG,KAAtB,CAAA;AACA,EAAA,IAAIC,6BAAJ,CAAA;;EACA,MAAMC,WAAW,GAAG,MAAM;AACxBF,IAAAA,eAAe,GAAG,IAAlB,CAAA;IACAC,6BAA6B,IAAA,IAA7B,YAAAA,6BAA6B,EAAA,CAAA;AAC9B,GAHD,CAH6B;;;EAS7B,MAAME,cAAc,GAAGxC,yBAAyB,CAAC4B,KAAD,CAAzB,CAAiCa,IAAjC,CAAsC,MAAM;IACjE,IAAI,CAACJ,eAAL,EAAsB;AACpB;AACAC,MAAAA,6BAA6B,GAAGX,2BAA2B,CAACC,KAAD,CAA3D,CAAA;AACD,KAAA;AACF,GALsB,CAAvB,CAAA;AAOA,EAAA,OAAO,CAACW,WAAD,EAAcC,cAAd,CAAP,CAAA;AACD;;;;"}
@@ -4,12 +4,23 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.QueryPersistClientCore = {}, global.QueryCore));
5
5
  })(this, (function (exports, queryCore) { 'use strict';
6
6
 
7
+ /**
8
+ * Checks if emitted event is about cache change and not about observers.
9
+ * Useful for persist, where we only want to trigger save when cache is changed.
10
+ */
11
+ const cacheableEventTypes = ['added', 'removed', 'updated'];
12
+
13
+ function isCacheableEventType(eventType) {
14
+ return cacheableEventTypes.includes(eventType);
15
+ }
7
16
  /**
8
17
  * Restores persisted data to the QueryCache
9
18
  * - data obtained from persister.restoreClient
10
19
  * - data is hydrated using hydrateOptions
11
20
  * If data is expired, busted, empty, or throws, it runs persister.removeClient
12
21
  */
22
+
23
+
13
24
  async function persistQueryClientRestore({
14
25
  queryClient,
15
26
  persister,
@@ -68,11 +79,15 @@
68
79
  */
69
80
 
70
81
  function persistQueryClientSubscribe(props) {
71
- const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe(() => {
72
- persistQueryClientSave(props);
82
+ const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe(event => {
83
+ if (isCacheableEventType(event.type)) {
84
+ persistQueryClientSave(props);
85
+ }
73
86
  });
74
- const unusbscribeMutationCache = props.queryClient.getMutationCache().subscribe(() => {
75
- persistQueryClientSave(props);
87
+ const unusbscribeMutationCache = props.queryClient.getMutationCache().subscribe(event => {
88
+ if (isCacheableEventType(event.type)) {
89
+ persistQueryClientSave(props);
90
+ }
76
91
  });
77
92
  return () => {
78
93
  unsubscribeQueryCache();
@@ -1 +1 @@
1
- {"version":3,"file":"index.development.js","sources":["../../src/persist.ts","../../src/retryStrategies.ts"],"sourcesContent":["import type {\n QueryClient,\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from '@tanstack/query-core'\nimport { dehydrate, hydrate } from '@tanstack/query-core'\n\nexport type Promisable<T> = T | PromiseLike<T>\n\nexport interface Persister {\n persistClient(persistClient: PersistedClient): Promisable<void>\n restoreClient(): Promisable<PersistedClient | undefined>\n removeClient(): Promisable<void>\n}\n\nexport interface PersistedClient {\n timestamp: number\n buster: string\n clientState: DehydratedState\n}\n\nexport interface PersistQueryClienRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /** The Persister interface for storing and restoring the cache\n * to/from a persisted location */\n persister: Persister\n /** A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string */\n buster?: string\n}\n\nexport interface PersistedQueryClientRestoreOptions\n extends PersistQueryClienRootOptions {\n /** The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\nexport interface PersistedQueryClientSaveOptions\n extends PersistQueryClienRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\nexport interface PersistQueryClientOptions\n extends PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClienRootOptions {}\n\n/**\n * Restores persisted data to the QueryCache\n * - data obtained from persister.restoreClient\n * - data is hydrated using hydrateOptions\n * If data is expired, busted, empty, or throws, it runs persister.removeClient\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 1000 * 60 * 60 * 24,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n queryClient.getLogger().error(err)\n queryClient\n .getLogger()\n .warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n persister.removeClient()\n }\n}\n\n/**\n * Persists data from the QueryCache\n * - data dehydrated using dehydrateOptions\n * - data is persisted using persister.persistClient\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting)\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe(() => {\n persistQueryClientSave(props)\n })\n\n const unusbscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe(() => {\n persistQueryClientSave(props)\n })\n\n return () => {\n unsubscribeQueryCache()\n unusbscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n","import type { PersistedClient } from '@tanstack/query-persist-client-core'\n\nexport type PersistRetryer = (props: {\n persistedClient: PersistedClient\n error: Error\n errorCount: number\n}) => PersistedClient | undefined\n\nexport const removeOldestQuery: PersistRetryer = ({ persistedClient }) => {\n const mutations = [...persistedClient.clientState.mutations]\n const queries = [...persistedClient.clientState.queries]\n const client: PersistedClient = {\n ...persistedClient,\n clientState: { mutations, queries },\n }\n\n // sort queries by dataUpdatedAt (oldest first)\n const sortedQueries = [...queries].sort(\n (a, b) => a.state.dataUpdatedAt - b.state.dataUpdatedAt,\n )\n\n // clean oldest query\n if (sortedQueries.length > 0) {\n const oldestData = sortedQueries.shift()\n client.clientState.queries = queries.filter((q) => q !== oldestData)\n return client\n }\n\n return undefined\n}\n"],"names":["persistQueryClientRestore","queryClient","persister","maxAge","buster","hydrateOptions","persistedClient","restoreClient","timestamp","expired","Date","now","busted","removeClient","hydrate","clientState","err","getLogger","error","warn","persistQueryClientSave","dehydrateOptions","persistClient","dehydrate","persistQueryClientSubscribe","props","unsubscribeQueryCache","getQueryCache","subscribe","unusbscribeMutationCache","getMutationCache","persistQueryClient","hasUnsubscribed","persistQueryClientUnsubscribe","unsubscribe","restorePromise","then","removeOldestQuery","mutations","queries","client","sortedQueries","sort","a","b","state","dataUpdatedAt","length","oldestData","shift","filter","q","undefined"],"mappings":";;;;;;EAsDA;EACA;EACA;EACA;EACA;EACA;EACO,eAAeA,yBAAf,CAAyC;IAC9CC,WAD8C;IAE9CC,SAF8C;EAG9CC,EAAAA,MAAM,GAAG,IAAO,GAAA,EAAP,GAAY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M,QAAME,iBAAiC,GAAG,CAAC;EAAE/B,EAAAA,eAAAA;EAAF,CAAD,KAAyB;IACxE,MAAMgC,SAAS,GAAG,CAAC,GAAGhC,eAAe,CAACS,WAAhB,CAA4BuB,SAAhC,CAAlB,CAAA;IACA,MAAMC,OAAO,GAAG,CAAC,GAAGjC,eAAe,CAACS,WAAhB,CAA4BwB,OAAhC,CAAhB,CAAA;EACA,EAAA,MAAMC,MAAuB,GAAG,EAC9B,GAAGlC,eAD2B;EAE9BS,IAAAA,WAAW,EAAE;QAAEuB,SAAF;EAAaC,MAAAA,OAAAA;EAAb,KAAA;EAFiB,GAAhC,CAHwE;;IASxE,MAAME,aAAa,GAAG,CAAC,GAAGF,OAAJ,CAAaG,CAAAA,IAAb,CACpB,CAACC,CAAD,EAAIC,CAAJ,KAAUD,CAAC,CAACE,KAAF,CAAQC,aAAR,GAAwBF,CAAC,CAACC,KAAF,CAAQC,aADtB,CAAtB,CATwE;;EAcxE,EAAA,IAAIL,aAAa,CAACM,MAAd,GAAuB,CAA3B,EAA8B;EAC5B,IAAA,MAAMC,UAAU,GAAGP,aAAa,CAACQ,KAAd,EAAnB,CAAA;EACAT,IAAAA,MAAM,CAACzB,WAAP,CAAmBwB,OAAnB,GAA6BA,OAAO,CAACW,MAAR,CAAgBC,CAAD,IAAOA,CAAC,KAAKH,UAA5B,CAA7B,CAAA;EACA,IAAA,OAAOR,MAAP,CAAA;EACD,GAAA;;EAED,EAAA,OAAOY,SAAP,CAAA;EACD;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.development.js","sources":["../../src/persist.ts","../../src/retryStrategies.ts"],"sourcesContent":["import type {\n QueryClient,\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from '@tanstack/query-core'\nimport { dehydrate, hydrate } from '@tanstack/query-core'\nimport type { NotifyEventType } from '@tanstack/query-core'\n\nexport type Promisable<T> = T | PromiseLike<T>\n\nexport interface Persister {\n persistClient(persistClient: PersistedClient): Promisable<void>\n restoreClient(): Promisable<PersistedClient | undefined>\n removeClient(): Promisable<void>\n}\n\nexport interface PersistedClient {\n timestamp: number\n buster: string\n clientState: DehydratedState\n}\n\nexport interface PersistQueryClienRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /** The Persister interface for storing and restoring the cache\n * to/from a persisted location */\n persister: Persister\n /** A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string */\n buster?: string\n}\n\nexport interface PersistedQueryClientRestoreOptions\n extends PersistQueryClienRootOptions {\n /** The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\nexport interface PersistedQueryClientSaveOptions\n extends PersistQueryClienRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\nexport interface PersistQueryClientOptions\n extends PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClienRootOptions {}\n\n/**\n * Checks if emitted event is about cache change and not about observers.\n * Useful for persist, where we only want to trigger save when cache is changed.\n */\nconst cacheableEventTypes: Array<NotifyEventType> = [\n 'added',\n 'removed',\n 'updated',\n]\n\nfunction isCacheableEventType(eventType: NotifyEventType) {\n return cacheableEventTypes.includes(eventType)\n}\n\n/**\n * Restores persisted data to the QueryCache\n * - data obtained from persister.restoreClient\n * - data is hydrated using hydrateOptions\n * If data is expired, busted, empty, or throws, it runs persister.removeClient\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 1000 * 60 * 60 * 24,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n queryClient.getLogger().error(err)\n queryClient\n .getLogger()\n .warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n persister.removeClient()\n }\n}\n\n/**\n * Persists data from the QueryCache\n * - data dehydrated using dehydrateOptions\n * - data is persisted using persister.persistClient\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting)\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (isCacheableEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n const unusbscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheableEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unusbscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n","import type { PersistedClient } from '@tanstack/query-persist-client-core'\n\nexport type PersistRetryer = (props: {\n persistedClient: PersistedClient\n error: Error\n errorCount: number\n}) => PersistedClient | undefined\n\nexport const removeOldestQuery: PersistRetryer = ({ persistedClient }) => {\n const mutations = [...persistedClient.clientState.mutations]\n const queries = [...persistedClient.clientState.queries]\n const client: PersistedClient = {\n ...persistedClient,\n clientState: { mutations, queries },\n }\n\n // sort queries by dataUpdatedAt (oldest first)\n const sortedQueries = [...queries].sort(\n (a, b) => a.state.dataUpdatedAt - b.state.dataUpdatedAt,\n )\n\n // clean oldest query\n if (sortedQueries.length > 0) {\n const oldestData = sortedQueries.shift()\n client.clientState.queries = queries.filter((q) => q !== oldestData)\n return client\n }\n\n return undefined\n}\n"],"names":["cacheableEventTypes","isCacheableEventType","eventType","includes","persistQueryClientRestore","queryClient","persister","maxAge","buster","hydrateOptions","persistedClient","restoreClient","timestamp","expired","Date","now","busted","removeClient","hydrate","clientState","err","getLogger","error","warn","persistQueryClientSave","dehydrateOptions","persistClient","dehydrate","persistQueryClientSubscribe","props","unsubscribeQueryCache","getQueryCache","subscribe","event","type","unusbscribeMutationCache","getMutationCache","persistQueryClient","hasUnsubscribed","persistQueryClientUnsubscribe","unsubscribe","restorePromise","then","removeOldestQuery","mutations","queries","client","sortedQueries","sort","a","b","state","dataUpdatedAt","length","oldestData","shift","filter","q","undefined"],"mappings":";;;;;;EAuDA;EACA;EACA;EACA;EACA,MAAMA,mBAA2C,GAAG,CAClD,OADkD,EAElD,SAFkD,EAGlD,SAHkD,CAApD,CAAA;;EAMA,SAASC,oBAAT,CAA8BC,SAA9B,EAA0D;EACxD,EAAA,OAAOF,mBAAmB,CAACG,QAApB,CAA6BD,SAA7B,CAAP,CAAA;EACD,CAAA;EAED;EACA;EACA;EACA;EACA;EACA;;;EACO,eAAeE,yBAAf,CAAyC;IAC9CC,WAD8C;IAE9CC,SAF8C;EAG9CC,EAAAA,MAAM,GAAG,IAAO,GAAA,EAAP,GAAY,EAAZ,GAAiB,EAHoB;EAI9CC,EAAAA,MAAM,GAAG,EAJqC;EAK9CC,EAAAA,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;EACD,KAAA;EACF,GALsB,CAAvB,CAAA;EAOA,EAAA,OAAO,CAACW,WAAD,EAAcC,cAAd,CAAP,CAAA;EACD;;AC9KM,QAAME,iBAAiC,GAAG,CAAC;EAAEjC,EAAAA,eAAAA;EAAF,CAAD,KAAyB;IACxE,MAAMkC,SAAS,GAAG,CAAC,GAAGlC,eAAe,CAACS,WAAhB,CAA4ByB,SAAhC,CAAlB,CAAA;IACA,MAAMC,OAAO,GAAG,CAAC,GAAGnC,eAAe,CAACS,WAAhB,CAA4B0B,OAAhC,CAAhB,CAAA;EACA,EAAA,MAAMC,MAAuB,GAAG,EAC9B,GAAGpC,eAD2B;EAE9BS,IAAAA,WAAW,EAAE;QAAEyB,SAAF;EAAaC,MAAAA,OAAAA;EAAb,KAAA;EAFiB,GAAhC,CAHwE;;IASxE,MAAME,aAAa,GAAG,CAAC,GAAGF,OAAJ,CAAaG,CAAAA,IAAb,CACpB,CAACC,CAAD,EAAIC,CAAJ,KAAUD,CAAC,CAACE,KAAF,CAAQC,aAAR,GAAwBF,CAAC,CAACC,KAAF,CAAQC,aADtB,CAAtB,CATwE;;EAcxE,EAAA,IAAIL,aAAa,CAACM,MAAd,GAAuB,CAA3B,EAA8B;EAC5B,IAAA,MAAMC,UAAU,GAAGP,aAAa,CAACQ,KAAd,EAAnB,CAAA;EACAT,IAAAA,MAAM,CAAC3B,WAAP,CAAmB0B,OAAnB,GAA6BA,OAAO,CAACW,MAAR,CAAgBC,CAAD,IAAOA,CAAC,KAAKH,UAA5B,CAA7B,CAAA;EACA,IAAA,OAAOR,MAAP,CAAA;EACD,GAAA;;EAED,EAAA,OAAOY,SAAP,CAAA;EACD;;;;;;;;;;;;;;"}
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@tanstack/query-core")):"function"==typeof define&&define.amd?define(["exports","@tanstack/query-core"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).QueryPersistClientCore={},e.QueryCore)}(this,(function(e,t){"use strict";async function i({queryClient:e,persister:i,maxAge:r=864e5,buster:n="",hydrateOptions:s}){try{const a=await i.restoreClient();if(a)if(a.timestamp){const u=Date.now()-a.timestamp>r,o=a.buster!==n;u||o?i.removeClient():t.hydrate(e,a.clientState,s)}else i.removeClient()}catch(e){i.removeClient()}}async function r({queryClient:e,persister:i,buster:r="",dehydrateOptions:n}){const s={buster:r,timestamp:Date.now(),clientState:t.dehydrate(e,n)};await i.persistClient(s)}function n(e){const t=e.queryClient.getQueryCache().subscribe((()=>{r(e)})),i=e.queryClient.getMutationCache().subscribe((()=>{r(e)}));return()=>{t(),i()}}e.persistQueryClient=function(e){let t,r=!1;return[()=>{r=!0,null==t||t()},i(e).then((()=>{r||(t=n(e))}))]},e.persistQueryClientRestore=i,e.persistQueryClientSave=r,e.persistQueryClientSubscribe=n,e.removeOldestQuery=({persistedClient:e})=>{const t=[...e.clientState.mutations],i=[...e.clientState.queries],r={...e,clientState:{mutations:t,queries:i}},n=[...i].sort(((e,t)=>e.state.dataUpdatedAt-t.state.dataUpdatedAt));if(n.length>0){const e=n.shift();return r.clientState.queries=i.filter((t=>t!==e)),r}},Object.defineProperty(e,"__esModule",{value:!0})}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@tanstack/query-core")):"function"==typeof define&&define.amd?define(["exports","@tanstack/query-core"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).QueryPersistClientCore={},e.QueryCore)}(this,(function(e,t){"use strict";const i=["added","removed","updated"];function n(e){return i.includes(e)}async function r({queryClient:e,persister:i,maxAge:n=864e5,buster:r="",hydrateOptions:s}){try{const u=await i.restoreClient();if(u)if(u.timestamp){const a=Date.now()-u.timestamp>n,o=u.buster!==r;a||o?i.removeClient():t.hydrate(e,u.clientState,s)}else i.removeClient()}catch(e){i.removeClient()}}async function s({queryClient:e,persister:i,buster:n="",dehydrateOptions:r}){const s={buster:n,timestamp:Date.now(),clientState:t.dehydrate(e,r)};await i.persistClient(s)}function u(e){const t=e.queryClient.getQueryCache().subscribe((t=>{n(t.type)&&s(e)})),i=e.queryClient.getMutationCache().subscribe((t=>{n(t.type)&&s(e)}));return()=>{t(),i()}}e.persistQueryClient=function(e){let t,i=!1;return[()=>{i=!0,null==t||t()},r(e).then((()=>{i||(t=u(e))}))]},e.persistQueryClientRestore=r,e.persistQueryClientSave=s,e.persistQueryClientSubscribe=u,e.removeOldestQuery=({persistedClient:e})=>{const t=[...e.clientState.mutations],i=[...e.clientState.queries],n={...e,clientState:{mutations:t,queries:i}},r=[...i].sort(((e,t)=>e.state.dataUpdatedAt-t.state.dataUpdatedAt));if(r.length>0){const e=r.shift();return n.clientState.queries=i.filter((t=>t!==e)),n}},Object.defineProperty(e,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=index.production.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.production.js","sources":["../../src/persist.ts","../../src/retryStrategies.ts"],"sourcesContent":["import type {\n QueryClient,\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from '@tanstack/query-core'\nimport { dehydrate, hydrate } from '@tanstack/query-core'\n\nexport type Promisable<T> = T | PromiseLike<T>\n\nexport interface Persister {\n persistClient(persistClient: PersistedClient): Promisable<void>\n restoreClient(): Promisable<PersistedClient | undefined>\n removeClient(): Promisable<void>\n}\n\nexport interface PersistedClient {\n timestamp: number\n buster: string\n clientState: DehydratedState\n}\n\nexport interface PersistQueryClienRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /** The Persister interface for storing and restoring the cache\n * to/from a persisted location */\n persister: Persister\n /** A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string */\n buster?: string\n}\n\nexport interface PersistedQueryClientRestoreOptions\n extends PersistQueryClienRootOptions {\n /** The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\nexport interface PersistedQueryClientSaveOptions\n extends PersistQueryClienRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\nexport interface PersistQueryClientOptions\n extends PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClienRootOptions {}\n\n/**\n * Restores persisted data to the QueryCache\n * - data obtained from persister.restoreClient\n * - data is hydrated using hydrateOptions\n * If data is expired, busted, empty, or throws, it runs persister.removeClient\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 1000 * 60 * 60 * 24,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n queryClient.getLogger().error(err)\n queryClient\n .getLogger()\n .warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n persister.removeClient()\n }\n}\n\n/**\n * Persists data from the QueryCache\n * - data dehydrated using dehydrateOptions\n * - data is persisted using persister.persistClient\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting)\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe(() => {\n persistQueryClientSave(props)\n })\n\n const unusbscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe(() => {\n persistQueryClientSave(props)\n })\n\n return () => {\n unsubscribeQueryCache()\n unusbscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n","import type { PersistedClient } from '@tanstack/query-persist-client-core'\n\nexport type PersistRetryer = (props: {\n persistedClient: PersistedClient\n error: Error\n errorCount: number\n}) => PersistedClient | undefined\n\nexport const removeOldestQuery: PersistRetryer = ({ persistedClient }) => {\n const mutations = [...persistedClient.clientState.mutations]\n const queries = [...persistedClient.clientState.queries]\n const client: PersistedClient = {\n ...persistedClient,\n clientState: { mutations, queries },\n }\n\n // sort queries by dataUpdatedAt (oldest first)\n const sortedQueries = [...queries].sort(\n (a, b) => a.state.dataUpdatedAt - b.state.dataUpdatedAt,\n )\n\n // clean oldest query\n if (sortedQueries.length > 0) {\n const oldestData = sortedQueries.shift()\n client.clientState.queries = queries.filter((q) => q !== oldestData)\n return client\n }\n\n return undefined\n}\n"],"names":["async","persistQueryClientRestore","queryClient","persister","maxAge","buster","hydrateOptions","persistedClient","restoreClient","timestamp","expired","Date","now","busted","removeClient","hydrate","clientState","err","persistQueryClientSave","dehydrateOptions","persistClient","dehydrate","persistQueryClientSubscribe","props","unsubscribeQueryCache","getQueryCache","subscribe","unusbscribeMutationCache","getMutationCache","persistQueryClientUnsubscribe","hasUnsubscribed","then","mutations","queries","client","sortedQueries","sort","a","b","state","dataUpdatedAt","length","oldestData","shift","filter","q"],"mappings":"mU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OADAT,EAAOlB,YAAYiB,QAAUA,EAAQW,QAAQC,GAAMA,IAAMH,IAClDR"}
1
+ {"version":3,"file":"index.production.js","sources":["../../src/persist.ts","../../src/retryStrategies.ts"],"sourcesContent":["import type {\n QueryClient,\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n} from '@tanstack/query-core'\nimport { dehydrate, hydrate } from '@tanstack/query-core'\nimport type { NotifyEventType } from '@tanstack/query-core'\n\nexport type Promisable<T> = T | PromiseLike<T>\n\nexport interface Persister {\n persistClient(persistClient: PersistedClient): Promisable<void>\n restoreClient(): Promisable<PersistedClient | undefined>\n removeClient(): Promisable<void>\n}\n\nexport interface PersistedClient {\n timestamp: number\n buster: string\n clientState: DehydratedState\n}\n\nexport interface PersistQueryClienRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /** The Persister interface for storing and restoring the cache\n * to/from a persisted location */\n persister: Persister\n /** A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string */\n buster?: string\n}\n\nexport interface PersistedQueryClientRestoreOptions\n extends PersistQueryClienRootOptions {\n /** The max-allowed age of the cache in milliseconds.\n * If a persisted cache is found that is older than this\n * time, it will be discarded */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\nexport interface PersistedQueryClientSaveOptions\n extends PersistQueryClienRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\nexport interface PersistQueryClientOptions\n extends PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClienRootOptions {}\n\n/**\n * Checks if emitted event is about cache change and not about observers.\n * Useful for persist, where we only want to trigger save when cache is changed.\n */\nconst cacheableEventTypes: Array<NotifyEventType> = [\n 'added',\n 'removed',\n 'updated',\n]\n\nfunction isCacheableEventType(eventType: NotifyEventType) {\n return cacheableEventTypes.includes(eventType)\n}\n\n/**\n * Restores persisted data to the QueryCache\n * - data obtained from persister.restoreClient\n * - data is hydrated using hydrateOptions\n * If data is expired, busted, empty, or throws, it runs persister.removeClient\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 1000 * 60 * 60 * 24,\n buster = '',\n hydrateOptions,\n}: PersistedQueryClientRestoreOptions) {\n try {\n const persistedClient = await persister.restoreClient()\n\n if (persistedClient) {\n if (persistedClient.timestamp) {\n const expired = Date.now() - persistedClient.timestamp > maxAge\n const busted = persistedClient.buster !== buster\n if (expired || busted) {\n persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n queryClient.getLogger().error(err)\n queryClient\n .getLogger()\n .warn(\n 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',\n )\n }\n persister.removeClient()\n }\n}\n\n/**\n * Persists data from the QueryCache\n * - data dehydrated using dehydrateOptions\n * - data is persisted using persister.persistClient\n */\nexport async function persistQueryClientSave({\n queryClient,\n persister,\n buster = '',\n dehydrateOptions,\n}: PersistedQueryClientSaveOptions) {\n const persistClient: PersistedClient = {\n buster,\n timestamp: Date.now(),\n clientState: dehydrate(queryClient, dehydrateOptions),\n }\n\n await persister.persistClient(persistClient)\n}\n\n/**\n * Subscribe to QueryCache and MutationCache updates (for persisting)\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (isCacheableEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n const unusbscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheableEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unusbscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n */\nexport function persistQueryClient(\n props: PersistQueryClientOptions,\n): [() => void, Promise<void>] {\n let hasUnsubscribed = false\n let persistQueryClientUnsubscribe: (() => void) | undefined\n const unsubscribe = () => {\n hasUnsubscribed = true\n persistQueryClientUnsubscribe?.()\n }\n\n // Attempt restore\n const restorePromise = persistQueryClientRestore(props).then(() => {\n if (!hasUnsubscribed) {\n // Subscribe to changes in the query cache to trigger the save\n persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)\n }\n })\n\n return [unsubscribe, restorePromise]\n}\n","import type { PersistedClient } from '@tanstack/query-persist-client-core'\n\nexport type PersistRetryer = (props: {\n persistedClient: PersistedClient\n error: Error\n errorCount: number\n}) => PersistedClient | undefined\n\nexport const removeOldestQuery: PersistRetryer = ({ persistedClient }) => {\n const mutations = [...persistedClient.clientState.mutations]\n const queries = [...persistedClient.clientState.queries]\n const client: PersistedClient = {\n ...persistedClient,\n clientState: { mutations, queries },\n }\n\n // sort queries by dataUpdatedAt (oldest first)\n const sortedQueries = [...queries].sort(\n (a, b) => a.state.dataUpdatedAt - b.state.dataUpdatedAt,\n )\n\n // clean oldest query\n if (sortedQueries.length > 0) {\n const oldestData = sortedQueries.shift()\n client.clientState.queries = queries.filter((q) => q !== oldestData)\n return client\n }\n\n return undefined\n}\n"],"names":["cacheableEventTypes","isCacheableEventType","eventType","includes","async","persistQueryClientRestore","queryClient","persister","maxAge","buster","hydrateOptions","persistedClient","restoreClient","timestamp","expired","Date","now","busted","removeClient","hydrate","clientState","err","persistQueryClientSave","dehydrateOptions","persistClient","dehydrate","persistQueryClientSubscribe","props","unsubscribeQueryCache","getQueryCache","subscribe","event","type","unusbscribeMutationCache","getMutationCache","persistQueryClientUnsubscribe","hasUnsubscribed","then","mutations","queries","client","sortedQueries","sort","a","b","state","dataUpdatedAt","length","oldestData","shift","filter","q"],"mappings":"mUA2DA,MAAMA,EAA8C,CAClD,QACA,UACA,WAGF,SAASC,EAAqBC,GAC5B,OAAOF,EAAoBG,SAASD,GAS/BE,eAAeC,GAA0BC,YAC9CA,EAD8CC,UAE9CA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QAEjC,OADAT,EAAOpB,YAAYmB,QAAUA,EAAQW,QAAQC,GAAMA,IAAMH,IAClDR"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/query-persist-client-core",
3
- "version": "4.24.6",
3
+ "version": "4.24.9",
4
4
  "description": "Set of utilities for interacting with persisters, which can save your queryClient for later use",
5
5
  "author": "tannerlinsley",
6
6
  "license": "MIT",
@@ -28,7 +28,7 @@
28
28
  "src"
29
29
  ],
30
30
  "dependencies": {
31
- "@tanstack/query-core": "4.24.6"
31
+ "@tanstack/query-core": "4.24.9"
32
32
  },
33
33
  "scripts": {
34
34
  "clean": "rimraf ./build",
@@ -1,23 +1,10 @@
1
- import { createQueryClient, sleep } from './utils'
2
- import type { PersistedClient, Persister } from '../persist'
1
+ import {
2
+ createQueryClient,
3
+ createSpyablePersister,
4
+ createMockPersister,
5
+ } from './utils'
3
6
  import { persistQueryClientSubscribe } from '../persist'
4
-
5
- const createMockPersister = (): Persister => {
6
- let storedState: PersistedClient | undefined
7
-
8
- return {
9
- async persistClient(persistClient: PersistedClient) {
10
- storedState = persistClient
11
- },
12
- async restoreClient() {
13
- await sleep(10)
14
- return storedState
15
- },
16
- removeClient() {
17
- storedState = undefined
18
- },
19
- }
20
- }
7
+ import { QueriesObserver } from '@tanstack/query-core'
21
8
 
22
9
  describe('persistQueryClientSubscribe', () => {
23
10
  test('should persist mutations', async () => {
@@ -43,3 +30,34 @@ describe('persistQueryClientSubscribe', () => {
43
30
  unsubscribe()
44
31
  })
45
32
  })
33
+
34
+ describe('persistQueryClientSave', () => {
35
+ test('should not be triggered on observer type events', async () => {
36
+ const queryClient = createQueryClient()
37
+
38
+ const persister = createSpyablePersister()
39
+
40
+ const unsubscribe = persistQueryClientSubscribe({
41
+ queryClient,
42
+ persister,
43
+ })
44
+
45
+ const queryKey = ['test']
46
+ const queryFn = jest.fn().mockReturnValue(1)
47
+ const observer = new QueriesObserver(queryClient, [{ queryKey, queryFn }])
48
+ const unsubscribeObserver = observer.subscribe(jest.fn())
49
+ observer.getObservers()[0]?.setOptions({ refetchOnWindowFocus: false })
50
+ unsubscribeObserver()
51
+
52
+ queryClient.setQueryData(queryKey, 2)
53
+
54
+ // persistClient should be called 3 times:
55
+ // 1. When query is added
56
+ // 2. When queryFn is resolved
57
+ // 3. When setQueryData is called
58
+ // All events fired by manipulating observers are ignored
59
+ expect(persister.persistClient).toHaveBeenCalledTimes(3)
60
+
61
+ unsubscribe()
62
+ })
63
+ })
@@ -1,5 +1,9 @@
1
1
  import type { QueryClientConfig } from '@tanstack/query-core'
2
2
  import { QueryClient } from '@tanstack/query-core'
3
+ import type {
4
+ Persister,
5
+ PersistedClient,
6
+ } from '@tanstack/query-persist-client-core'
3
7
 
4
8
  export function createQueryClient(config?: QueryClientConfig): QueryClient {
5
9
  jest.spyOn(console, 'error').mockImplementation(() => undefined)
@@ -17,3 +21,28 @@ export function sleep(timeout: number): Promise<void> {
17
21
  setTimeout(resolve, timeout)
18
22
  })
19
23
  }
24
+
25
+ export const createMockPersister = (): Persister => {
26
+ let storedState: PersistedClient | undefined
27
+
28
+ return {
29
+ async persistClient(persistClient: PersistedClient) {
30
+ storedState = persistClient
31
+ },
32
+ async restoreClient() {
33
+ await sleep(10)
34
+ return storedState
35
+ },
36
+ removeClient() {
37
+ storedState = undefined
38
+ },
39
+ }
40
+ }
41
+
42
+ export const createSpyablePersister = (): Persister => {
43
+ return {
44
+ persistClient: jest.fn(),
45
+ restoreClient: jest.fn(),
46
+ removeClient: jest.fn(),
47
+ }
48
+ }
package/src/persist.ts CHANGED
@@ -5,6 +5,7 @@ import type {
5
5
  HydrateOptions,
6
6
  } from '@tanstack/query-core'
7
7
  import { dehydrate, hydrate } from '@tanstack/query-core'
8
+ import type { NotifyEventType } from '@tanstack/query-core'
8
9
 
9
10
  export type Promisable<T> = T | PromiseLike<T>
10
11
 
@@ -52,6 +53,20 @@ export interface PersistQueryClientOptions
52
53
  PersistedQueryClientSaveOptions,
53
54
  PersistQueryClienRootOptions {}
54
55
 
56
+ /**
57
+ * Checks if emitted event is about cache change and not about observers.
58
+ * Useful for persist, where we only want to trigger save when cache is changed.
59
+ */
60
+ const cacheableEventTypes: Array<NotifyEventType> = [
61
+ 'added',
62
+ 'removed',
63
+ 'updated',
64
+ ]
65
+
66
+ function isCacheableEventType(eventType: NotifyEventType) {
67
+ return cacheableEventTypes.includes(eventType)
68
+ }
69
+
55
70
  /**
56
71
  * Restores persisted data to the QueryCache
57
72
  * - data obtained from persister.restoreClient
@@ -123,14 +138,18 @@ export function persistQueryClientSubscribe(
123
138
  ) {
124
139
  const unsubscribeQueryCache = props.queryClient
125
140
  .getQueryCache()
126
- .subscribe(() => {
127
- persistQueryClientSave(props)
141
+ .subscribe((event) => {
142
+ if (isCacheableEventType(event.type)) {
143
+ persistQueryClientSave(props)
144
+ }
128
145
  })
129
146
 
130
147
  const unusbscribeMutationCache = props.queryClient
131
148
  .getMutationCache()
132
- .subscribe(() => {
133
- persistQueryClientSave(props)
149
+ .subscribe((event) => {
150
+ if (isCacheableEventType(event.type)) {
151
+ persistQueryClientSave(props)
152
+ }
134
153
  })
135
154
 
136
155
  return () => {