@tanstack/query-persist-client-core 4.7.0

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.
@@ -0,0 +1,58 @@
1
+ import type { QueryClient, DehydratedState, DehydrateOptions, HydrateOptions } from '@tanstack/query-core';
2
+ export declare type Promisable<T> = T | PromiseLike<T>;
3
+ export interface Persister {
4
+ persistClient(persistClient: PersistedClient): Promisable<void>;
5
+ restoreClient(): Promisable<PersistedClient | undefined>;
6
+ removeClient(): Promisable<void>;
7
+ }
8
+ export interface PersistedClient {
9
+ timestamp: number;
10
+ buster: string;
11
+ clientState: DehydratedState;
12
+ }
13
+ export interface PersistQueryClienRootOptions {
14
+ /** The QueryClient to persist */
15
+ queryClient: QueryClient;
16
+ /** The Persister interface for storing and restoring the cache
17
+ * to/from a persisted location */
18
+ persister: Persister;
19
+ /** A unique string that can be used to forcefully
20
+ * invalidate existing caches if they do not share the same buster string */
21
+ buster?: string;
22
+ }
23
+ export interface PersistedQueryClientRestoreOptions extends PersistQueryClienRootOptions {
24
+ /** The max-allowed age of the cache in milliseconds.
25
+ * If a persisted cache is found that is older than this
26
+ * time, it will be discarded */
27
+ maxAge?: number;
28
+ /** The options passed to the hydrate function */
29
+ hydrateOptions?: HydrateOptions;
30
+ }
31
+ export interface PersistedQueryClientSaveOptions extends PersistQueryClienRootOptions {
32
+ /** The options passed to the dehydrate function */
33
+ dehydrateOptions?: DehydrateOptions;
34
+ }
35
+ export interface PersistQueryClientOptions extends PersistedQueryClientRestoreOptions, PersistedQueryClientSaveOptions, PersistQueryClienRootOptions {
36
+ }
37
+ /**
38
+ * Restores persisted data to the QueryCache
39
+ * - data obtained from persister.restoreClient
40
+ * - data is hydrated using hydrateOptions
41
+ * If data is expired, busted, empty, or throws, it runs persister.removeClient
42
+ */
43
+ export declare function persistQueryClientRestore({ queryClient, persister, maxAge, buster, hydrateOptions, }: PersistedQueryClientRestoreOptions): Promise<void>;
44
+ /**
45
+ * Persists data from the QueryCache
46
+ * - data dehydrated using dehydrateOptions
47
+ * - data is persisted using persister.persistClient
48
+ */
49
+ export declare function persistQueryClientSave({ queryClient, persister, buster, dehydrateOptions, }: PersistedQueryClientSaveOptions): Promise<void>;
50
+ /**
51
+ * Subscribe to QueryCache and MutationCache updates (for persisting)
52
+ * @returns an unsubscribe function (to discontinue monitoring)
53
+ */
54
+ export declare function persistQueryClientSubscribe(props: PersistedQueryClientSaveOptions): () => void;
55
+ /**
56
+ * Restores persisted data to QueryCache and persists further changes.
57
+ */
58
+ export declare function persistQueryClient(props: PersistQueryClientOptions): [() => void, Promise<void>];
@@ -0,0 +1,102 @@
1
+ import { hydrate, dehydrate } from '@tanstack/query-core';
2
+
3
+ /**
4
+ * Restores persisted data to the QueryCache
5
+ * - data obtained from persister.restoreClient
6
+ * - data is hydrated using hydrateOptions
7
+ * If data is expired, busted, empty, or throws, it runs persister.removeClient
8
+ */
9
+ async function persistQueryClientRestore({
10
+ queryClient,
11
+ persister,
12
+ maxAge = 1000 * 60 * 60 * 24,
13
+ buster = '',
14
+ hydrateOptions
15
+ }) {
16
+ try {
17
+ const persistedClient = await persister.restoreClient();
18
+
19
+ if (persistedClient) {
20
+ if (persistedClient.timestamp) {
21
+ const expired = Date.now() - persistedClient.timestamp > maxAge;
22
+ const busted = persistedClient.buster !== buster;
23
+
24
+ if (expired || busted) {
25
+ persister.removeClient();
26
+ } else {
27
+ hydrate(queryClient, persistedClient.clientState, hydrateOptions);
28
+ }
29
+ } else {
30
+ persister.removeClient();
31
+ }
32
+ }
33
+ } catch (err) {
34
+ if (process.env.NODE_ENV !== 'production') {
35
+ queryClient.getLogger().error(err);
36
+ queryClient.getLogger().warn('Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.');
37
+ }
38
+
39
+ persister.removeClient();
40
+ }
41
+ }
42
+ /**
43
+ * Persists data from the QueryCache
44
+ * - data dehydrated using dehydrateOptions
45
+ * - data is persisted using persister.persistClient
46
+ */
47
+
48
+ async function persistQueryClientSave({
49
+ queryClient,
50
+ persister,
51
+ buster = '',
52
+ dehydrateOptions
53
+ }) {
54
+ const persistClient = {
55
+ buster,
56
+ timestamp: Date.now(),
57
+ clientState: dehydrate(queryClient, dehydrateOptions)
58
+ };
59
+ await persister.persistClient(persistClient);
60
+ }
61
+ /**
62
+ * Subscribe to QueryCache and MutationCache updates (for persisting)
63
+ * @returns an unsubscribe function (to discontinue monitoring)
64
+ */
65
+
66
+ function persistQueryClientSubscribe(props) {
67
+ const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe(() => {
68
+ persistQueryClientSave(props);
69
+ });
70
+ const unusbscribeMutationCache = props.queryClient.getMutationCache().subscribe(() => {
71
+ persistQueryClientSave(props);
72
+ });
73
+ return () => {
74
+ unsubscribeQueryCache();
75
+ unusbscribeMutationCache();
76
+ };
77
+ }
78
+ /**
79
+ * Restores persisted data to QueryCache and persists further changes.
80
+ */
81
+
82
+ function persistQueryClient(props) {
83
+ let hasUnsubscribed = false;
84
+ let persistQueryClientUnsubscribe;
85
+
86
+ const unsubscribe = () => {
87
+ hasUnsubscribed = true;
88
+ persistQueryClientUnsubscribe == null ? void 0 : persistQueryClientUnsubscribe();
89
+ }; // Attempt restore
90
+
91
+
92
+ const restorePromise = persistQueryClientRestore(props).then(() => {
93
+ if (!hasUnsubscribed) {
94
+ // Subscribe to changes in the query cache to trigger the save
95
+ persistQueryClientUnsubscribe = persistQueryClientSubscribe(props);
96
+ }
97
+ });
98
+ return [unsubscribe, restorePromise];
99
+ }
100
+
101
+ export { persistQueryClient, persistQueryClientRestore, persistQueryClientSave, persistQueryClientSubscribe };
102
+ //# sourceMappingURL=index.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.esm.js","sources":["../../src/index.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","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B,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;;;;"}
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var queryCore = require('@tanstack/query-core');
6
+
7
+ /**
8
+ * Restores persisted data to the QueryCache
9
+ * - data obtained from persister.restoreClient
10
+ * - data is hydrated using hydrateOptions
11
+ * If data is expired, busted, empty, or throws, it runs persister.removeClient
12
+ */
13
+ async function persistQueryClientRestore({
14
+ queryClient,
15
+ persister,
16
+ maxAge = 1000 * 60 * 60 * 24,
17
+ buster = '',
18
+ hydrateOptions
19
+ }) {
20
+ try {
21
+ const persistedClient = await persister.restoreClient();
22
+
23
+ if (persistedClient) {
24
+ if (persistedClient.timestamp) {
25
+ const expired = Date.now() - persistedClient.timestamp > maxAge;
26
+ const busted = persistedClient.buster !== buster;
27
+
28
+ if (expired || busted) {
29
+ persister.removeClient();
30
+ } else {
31
+ queryCore.hydrate(queryClient, persistedClient.clientState, hydrateOptions);
32
+ }
33
+ } else {
34
+ persister.removeClient();
35
+ }
36
+ }
37
+ } catch (err) {
38
+ if (process.env.NODE_ENV !== 'production') {
39
+ queryClient.getLogger().error(err);
40
+ queryClient.getLogger().warn('Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.');
41
+ }
42
+
43
+ persister.removeClient();
44
+ }
45
+ }
46
+ /**
47
+ * Persists data from the QueryCache
48
+ * - data dehydrated using dehydrateOptions
49
+ * - data is persisted using persister.persistClient
50
+ */
51
+
52
+ async function persistQueryClientSave({
53
+ queryClient,
54
+ persister,
55
+ buster = '',
56
+ dehydrateOptions
57
+ }) {
58
+ const persistClient = {
59
+ buster,
60
+ timestamp: Date.now(),
61
+ clientState: queryCore.dehydrate(queryClient, dehydrateOptions)
62
+ };
63
+ await persister.persistClient(persistClient);
64
+ }
65
+ /**
66
+ * Subscribe to QueryCache and MutationCache updates (for persisting)
67
+ * @returns an unsubscribe function (to discontinue monitoring)
68
+ */
69
+
70
+ function persistQueryClientSubscribe(props) {
71
+ const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe(() => {
72
+ persistQueryClientSave(props);
73
+ });
74
+ const unusbscribeMutationCache = props.queryClient.getMutationCache().subscribe(() => {
75
+ persistQueryClientSave(props);
76
+ });
77
+ return () => {
78
+ unsubscribeQueryCache();
79
+ unusbscribeMutationCache();
80
+ };
81
+ }
82
+ /**
83
+ * Restores persisted data to QueryCache and persists further changes.
84
+ */
85
+
86
+ function persistQueryClient(props) {
87
+ let hasUnsubscribed = false;
88
+ let persistQueryClientUnsubscribe;
89
+
90
+ const unsubscribe = () => {
91
+ hasUnsubscribed = true;
92
+ persistQueryClientUnsubscribe == null ? void 0 : persistQueryClientUnsubscribe();
93
+ }; // Attempt restore
94
+
95
+
96
+ const restorePromise = persistQueryClientRestore(props).then(() => {
97
+ if (!hasUnsubscribed) {
98
+ // Subscribe to changes in the query cache to trigger the save
99
+ persistQueryClientUnsubscribe = persistQueryClientSubscribe(props);
100
+ }
101
+ });
102
+ return [unsubscribe, restorePromise];
103
+ }
104
+
105
+ exports.persistQueryClient = persistQueryClient;
106
+ exports.persistQueryClientRestore = persistQueryClientRestore;
107
+ exports.persistQueryClientSave = persistQueryClientSave;
108
+ exports.persistQueryClientSubscribe = persistQueryClientSubscribe;
109
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../src/index.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","pers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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;;;;;;;"}
@@ -0,0 +1,102 @@
1
+ import { hydrate, dehydrate } from '@tanstack/query-core';
2
+
3
+ /**
4
+ * Restores persisted data to the QueryCache
5
+ * - data obtained from persister.restoreClient
6
+ * - data is hydrated using hydrateOptions
7
+ * If data is expired, busted, empty, or throws, it runs persister.removeClient
8
+ */
9
+ async function persistQueryClientRestore({
10
+ queryClient,
11
+ persister,
12
+ maxAge = 1000 * 60 * 60 * 24,
13
+ buster = '',
14
+ hydrateOptions
15
+ }) {
16
+ try {
17
+ const persistedClient = await persister.restoreClient();
18
+
19
+ if (persistedClient) {
20
+ if (persistedClient.timestamp) {
21
+ const expired = Date.now() - persistedClient.timestamp > maxAge;
22
+ const busted = persistedClient.buster !== buster;
23
+
24
+ if (expired || busted) {
25
+ persister.removeClient();
26
+ } else {
27
+ hydrate(queryClient, persistedClient.clientState, hydrateOptions);
28
+ }
29
+ } else {
30
+ persister.removeClient();
31
+ }
32
+ }
33
+ } catch (err) {
34
+ if (process.env.NODE_ENV !== 'production') {
35
+ queryClient.getLogger().error(err);
36
+ queryClient.getLogger().warn('Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.');
37
+ }
38
+
39
+ persister.removeClient();
40
+ }
41
+ }
42
+ /**
43
+ * Persists data from the QueryCache
44
+ * - data dehydrated using dehydrateOptions
45
+ * - data is persisted using persister.persistClient
46
+ */
47
+
48
+ async function persistQueryClientSave({
49
+ queryClient,
50
+ persister,
51
+ buster = '',
52
+ dehydrateOptions
53
+ }) {
54
+ const persistClient = {
55
+ buster,
56
+ timestamp: Date.now(),
57
+ clientState: dehydrate(queryClient, dehydrateOptions)
58
+ };
59
+ await persister.persistClient(persistClient);
60
+ }
61
+ /**
62
+ * Subscribe to QueryCache and MutationCache updates (for persisting)
63
+ * @returns an unsubscribe function (to discontinue monitoring)
64
+ */
65
+
66
+ function persistQueryClientSubscribe(props) {
67
+ const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe(() => {
68
+ persistQueryClientSave(props);
69
+ });
70
+ const unusbscribeMutationCache = props.queryClient.getMutationCache().subscribe(() => {
71
+ persistQueryClientSave(props);
72
+ });
73
+ return () => {
74
+ unsubscribeQueryCache();
75
+ unusbscribeMutationCache();
76
+ };
77
+ }
78
+ /**
79
+ * Restores persisted data to QueryCache and persists further changes.
80
+ */
81
+
82
+ function persistQueryClient(props) {
83
+ let hasUnsubscribed = false;
84
+ let persistQueryClientUnsubscribe;
85
+
86
+ const unsubscribe = () => {
87
+ hasUnsubscribed = true;
88
+ persistQueryClientUnsubscribe == null ? void 0 : persistQueryClientUnsubscribe();
89
+ }; // Attempt restore
90
+
91
+
92
+ const restorePromise = persistQueryClientRestore(props).then(() => {
93
+ if (!hasUnsubscribed) {
94
+ // Subscribe to changes in the query cache to trigger the save
95
+ persistQueryClientUnsubscribe = persistQueryClientSubscribe(props);
96
+ }
97
+ });
98
+ return [unsubscribe, restorePromise];
99
+ }
100
+
101
+ export { persistQueryClient, persistQueryClientRestore, persistQueryClientSave, persistQueryClientSubscribe };
102
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":["../../src/index.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,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AAD,CAA3D,CAAA;AACD,KAAA;AACF,GALsB,CAAvB,CAAA;AAOA,EAAA,OAAO,CAACS,WAAD,EAAcC,cAAd,CAAP,CAAA;AACD;;;;"}
@@ -0,0 +1,113 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@tanstack/query-core')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', '@tanstack/query-core'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.QueryPersistClientCore = {}, global.QueryCore));
5
+ })(this, (function (exports, queryCore) { 'use strict';
6
+
7
+ /**
8
+ * Restores persisted data to the QueryCache
9
+ * - data obtained from persister.restoreClient
10
+ * - data is hydrated using hydrateOptions
11
+ * If data is expired, busted, empty, or throws, it runs persister.removeClient
12
+ */
13
+ async function persistQueryClientRestore({
14
+ queryClient,
15
+ persister,
16
+ maxAge = 1000 * 60 * 60 * 24,
17
+ buster = '',
18
+ hydrateOptions
19
+ }) {
20
+ try {
21
+ const persistedClient = await persister.restoreClient();
22
+
23
+ if (persistedClient) {
24
+ if (persistedClient.timestamp) {
25
+ const expired = Date.now() - persistedClient.timestamp > maxAge;
26
+ const busted = persistedClient.buster !== buster;
27
+
28
+ if (expired || busted) {
29
+ persister.removeClient();
30
+ } else {
31
+ queryCore.hydrate(queryClient, persistedClient.clientState, hydrateOptions);
32
+ }
33
+ } else {
34
+ persister.removeClient();
35
+ }
36
+ }
37
+ } catch (err) {
38
+ {
39
+ queryClient.getLogger().error(err);
40
+ queryClient.getLogger().warn('Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.');
41
+ }
42
+
43
+ persister.removeClient();
44
+ }
45
+ }
46
+ /**
47
+ * Persists data from the QueryCache
48
+ * - data dehydrated using dehydrateOptions
49
+ * - data is persisted using persister.persistClient
50
+ */
51
+
52
+ async function persistQueryClientSave({
53
+ queryClient,
54
+ persister,
55
+ buster = '',
56
+ dehydrateOptions
57
+ }) {
58
+ const persistClient = {
59
+ buster,
60
+ timestamp: Date.now(),
61
+ clientState: queryCore.dehydrate(queryClient, dehydrateOptions)
62
+ };
63
+ await persister.persistClient(persistClient);
64
+ }
65
+ /**
66
+ * Subscribe to QueryCache and MutationCache updates (for persisting)
67
+ * @returns an unsubscribe function (to discontinue monitoring)
68
+ */
69
+
70
+ function persistQueryClientSubscribe(props) {
71
+ const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe(() => {
72
+ persistQueryClientSave(props);
73
+ });
74
+ const unusbscribeMutationCache = props.queryClient.getMutationCache().subscribe(() => {
75
+ persistQueryClientSave(props);
76
+ });
77
+ return () => {
78
+ unsubscribeQueryCache();
79
+ unusbscribeMutationCache();
80
+ };
81
+ }
82
+ /**
83
+ * Restores persisted data to QueryCache and persists further changes.
84
+ */
85
+
86
+ function persistQueryClient(props) {
87
+ let hasUnsubscribed = false;
88
+ let persistQueryClientUnsubscribe;
89
+
90
+ const unsubscribe = () => {
91
+ hasUnsubscribed = true;
92
+ persistQueryClientUnsubscribe == null ? void 0 : persistQueryClientUnsubscribe();
93
+ }; // Attempt restore
94
+
95
+
96
+ const restorePromise = persistQueryClientRestore(props).then(() => {
97
+ if (!hasUnsubscribed) {
98
+ // Subscribe to changes in the query cache to trigger the save
99
+ persistQueryClientUnsubscribe = persistQueryClientSubscribe(props);
100
+ }
101
+ });
102
+ return [unsubscribe, restorePromise];
103
+ }
104
+
105
+ exports.persistQueryClient = persistQueryClient;
106
+ exports.persistQueryClientRestore = persistQueryClientRestore;
107
+ exports.persistQueryClientSave = persistQueryClientSave;
108
+ exports.persistQueryClientSubscribe = persistQueryClientSubscribe;
109
+
110
+ Object.defineProperty(exports, '__esModule', { value: true });
111
+
112
+ }));
113
+ //# sourceMappingURL=index.development.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.development.js","sources":["../../src/index.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","getLogger","error","warn","persistQueryClientSave","dehydrateOptions","persistClient","dehydrate","persistQueryClientSubscribe","props","unsubscribeQueryCache","getQueryCache","subscribe","unusbscribeMutationCache","getMutationCache","persistQueryClient","hasUnsubscribed","persistQueryClientUnsubscribe","unsubscribe","restorePromise","then"],"mappings":";;;;;;EAsDA;EACA;EACA;EACA;EACA;EACA;EACO,eAAeA,yBAAf,CAAyC;IAC9CC,WAD8C;IAE9CC,SAF8C;EAG9CC,EAAAA,MAAM,GAAG,IAAO,GAAA,EAAP,GAAY,EAAZ,GAAiB,EAHoB;EAI9CC,EAAAA,MAAM,GAAG,EAJqC;EAK9CC,EAAAA,cAAAA;EAL8C,CAAzC,EAMgC;IACrC,IAAI;EACF,IAAA,MAAMC,eAAe,GAAG,MAAMJ,SAAS,CAACK,aAAV,EAA9B,CAAA;;EAEA,IAAA,IAAID,eAAJ,EAAqB;QACnB,IAAIA,eAAe,CAACE,SAApB,EAA+B;UAC7B,MAAMC,OAAO,GAAGC,IAAI,CAACC,GAAL,KAAaL,eAAe,CAACE,SAA7B,GAAyCL,MAAzD,CAAA;EACA,QAAA,MAAMS,MAAM,GAAGN,eAAe,CAACF,MAAhB,KAA2BA,MAA1C,CAAA;;UACA,IAAIK,OAAO,IAAIG,MAAf,EAAuB;EACrBV,UAAAA,SAAS,CAACW,YAAV,EAAA,CAAA;EACD,SAFD,MAEO;YACLC,iBAAO,CAACb,WAAD,EAAcK,eAAe,CAACS,WAA9B,EAA2CV,cAA3C,CAAP,CAAA;EACD,SAAA;EACF,OARD,MAQO;EACLH,QAAAA,SAAS,CAACW,YAAV,EAAA,CAAA;EACD,OAAA;EACF,KAAA;KAfH,CAgBE,OAAOG,GAAP,EAAY;EACZ,IAA2C;EACzCf,MAAAA,WAAW,CAACgB,SAAZ,EAAwBC,CAAAA,KAAxB,CAA8BF,GAA9B,CAAA,CAAA;EACAf,MAAAA,WAAW,CACRgB,SADH,EAEGE,CAAAA,IAFH,CAGI,0IAHJ,CAAA,CAAA;EAKD,KAAA;;EACDjB,IAAAA,SAAS,CAACW,YAAV,EAAA,CAAA;EACD,GAAA;EACF,CAAA;EAED;EACA;EACA;EACA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CAAiCW,IAAjC,CAAsC,MAAM;MACjE,IAAI,CAACJ,eAAL,EAAsB;EACpB;EACAC,MAAAA,6BAA6B,GAAGT,2BAA2B,CAACC,KAAD,CAA3D,CAAA;EACD,KAAA;EACF,GALsB,CAAvB,CAAA;EAOA,EAAA,OAAO,CAACS,WAAD,EAAcC,cAAd,CAAP,CAAA;EACD;;;;;;;;;;;;;"}
@@ -0,0 +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 r({queryClient:e,persister:r,maxAge:i=864e5,buster:n="",hydrateOptions:s}){try{const o=await r.restoreClient();if(o)if(o.timestamp){const u=Date.now()-o.timestamp>i,a=o.buster!==n;u||a?r.removeClient():t.hydrate(e,o.clientState,s)}else r.removeClient()}catch(e){r.removeClient()}}async function i({queryClient:e,persister:r,buster:i="",dehydrateOptions:n}){const s={buster:i,timestamp:Date.now(),clientState:t.dehydrate(e,n)};await r.persistClient(s)}function n(e){const t=e.queryClient.getQueryCache().subscribe((()=>{i(e)})),r=e.queryClient.getMutationCache().subscribe((()=>{i(e)}));return()=>{t(),r()}}e.persistQueryClient=function(e){let t,i=!1;return[()=>{i=!0,null==t||t()},r(e).then((()=>{i||(t=n(e))}))]},e.persistQueryClientRestore=r,e.persistQueryClientSave=i,e.persistQueryClientSubscribe=n,Object.defineProperty(e,"__esModule",{value:!0})}));
2
+ //# sourceMappingURL=index.production.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.production.js","sources":["../../src/index.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":["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"],"mappings":"mUA4DOA,eAAeC,GAA0BC,YAC9CA,EAD8CC,UAE9CA,EAF8CC,OAG9CA,EAAS,MAHqCC,OAI9CA,EAAS,GAJqCC,eAK9CA,IAEA,IACE,MAAMC,QAAwBJ,EAAUK,gBAExC,GAAID,EACF,GAAIA,EAAgBE,UAAW,CAC7B,MAAMC,EAAUC,KAAKC,MAAQL,EAAgBE,UAAYL,EACnDS,EAASN,EAAgBF,SAAWA,EACtCK,GAAWG,EACbV,EAAUW,eAEVC,EAAAA,QAAQb,EAAaK,EAAgBS,YAAaV,QAGpDH,EAAUW,eAGd,MAAOG,GASPd,EAAUW,gBASPd,eAAekB,GAAuBhB,YAC3CA,EAD2CC,UAE3CA,EAF2CE,OAG3CA,EAAS,GAHkCc,iBAI3CA,IAEA,MAAMC,EAAiC,CACrCf,SACAI,UAAWE,KAAKC,MAChBI,YAAaK,EAAAA,UAAUnB,EAAaiB,UAGhChB,EAAUiB,cAAcA,GAOzB,SAASE,EACdC,GAEA,MAAMC,EAAwBD,EAAMrB,YACjCuB,gBACAC,WAAU,KACTR,EAAuBK,MAGrBI,EAA2BJ,EAAMrB,YACpC0B,mBACAF,WAAU,KACTR,EAAuBK,MAG3B,MAAO,KACLC,IACAG,0BAOG,SACLJ,GAEA,IACIM,EADAC,GAAkB,EAetB,MAAO,CAba,KAClBA,GAAkB,EACW,MAA7BD,GAAAA,KAIqB5B,EAA0BsB,GAAOQ,MAAK,KACtDD,IAEHD,EAAgCP,EAA4BC"}
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@tanstack/query-persist-client-core",
3
+ "version": "4.7.0",
4
+ "description": "TODO",
5
+ "author": "tannerlinsley",
6
+ "license": "MIT",
7
+ "repository": "tanstack/query",
8
+ "homepage": "https://tanstack.com/query",
9
+ "funding": {
10
+ "type": "github",
11
+ "url": "https://github.com/sponsors/tannerlinsley"
12
+ },
13
+ "types": "build/lib/index.d.ts",
14
+ "main": "build/lib/index.js",
15
+ "module": "build/lib/index.esm.js",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./build/lib/index.d.ts",
19
+ "import": "./build/lib/index.mjs",
20
+ "default": "./build/lib/index.js"
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "sideEffects": false,
25
+ "files": [
26
+ "build/lib/*",
27
+ "build/umd/*",
28
+ "src"
29
+ ],
30
+ "scripts": {
31
+ "clean": "rm -rf ./build",
32
+ "test:eslint": "../../node_modules/.bin/eslint --ext .ts,.tsx ./src"
33
+ },
34
+ "peerDependencies": {
35
+ "@tanstack/query-core": "4.6.1"
36
+ }
37
+ }
package/src/index.ts ADDED
@@ -0,0 +1,164 @@
1
+ import type {
2
+ QueryClient,
3
+ DehydratedState,
4
+ DehydrateOptions,
5
+ HydrateOptions,
6
+ } from '@tanstack/query-core'
7
+ import { dehydrate, hydrate } from '@tanstack/query-core'
8
+
9
+ export type Promisable<T> = T | PromiseLike<T>
10
+
11
+ export interface Persister {
12
+ persistClient(persistClient: PersistedClient): Promisable<void>
13
+ restoreClient(): Promisable<PersistedClient | undefined>
14
+ removeClient(): Promisable<void>
15
+ }
16
+
17
+ export interface PersistedClient {
18
+ timestamp: number
19
+ buster: string
20
+ clientState: DehydratedState
21
+ }
22
+
23
+ export interface PersistQueryClienRootOptions {
24
+ /** The QueryClient to persist */
25
+ queryClient: QueryClient
26
+ /** The Persister interface for storing and restoring the cache
27
+ * to/from a persisted location */
28
+ persister: Persister
29
+ /** A unique string that can be used to forcefully
30
+ * invalidate existing caches if they do not share the same buster string */
31
+ buster?: string
32
+ }
33
+
34
+ export interface PersistedQueryClientRestoreOptions
35
+ extends PersistQueryClienRootOptions {
36
+ /** The max-allowed age of the cache in milliseconds.
37
+ * If a persisted cache is found that is older than this
38
+ * time, it will be discarded */
39
+ maxAge?: number
40
+ /** The options passed to the hydrate function */
41
+ hydrateOptions?: HydrateOptions
42
+ }
43
+
44
+ export interface PersistedQueryClientSaveOptions
45
+ extends PersistQueryClienRootOptions {
46
+ /** The options passed to the dehydrate function */
47
+ dehydrateOptions?: DehydrateOptions
48
+ }
49
+
50
+ export interface PersistQueryClientOptions
51
+ extends PersistedQueryClientRestoreOptions,
52
+ PersistedQueryClientSaveOptions,
53
+ PersistQueryClienRootOptions {}
54
+
55
+ /**
56
+ * Restores persisted data to the QueryCache
57
+ * - data obtained from persister.restoreClient
58
+ * - data is hydrated using hydrateOptions
59
+ * If data is expired, busted, empty, or throws, it runs persister.removeClient
60
+ */
61
+ export async function persistQueryClientRestore({
62
+ queryClient,
63
+ persister,
64
+ maxAge = 1000 * 60 * 60 * 24,
65
+ buster = '',
66
+ hydrateOptions,
67
+ }: PersistedQueryClientRestoreOptions) {
68
+ try {
69
+ const persistedClient = await persister.restoreClient()
70
+
71
+ if (persistedClient) {
72
+ if (persistedClient.timestamp) {
73
+ const expired = Date.now() - persistedClient.timestamp > maxAge
74
+ const busted = persistedClient.buster !== buster
75
+ if (expired || busted) {
76
+ persister.removeClient()
77
+ } else {
78
+ hydrate(queryClient, persistedClient.clientState, hydrateOptions)
79
+ }
80
+ } else {
81
+ persister.removeClient()
82
+ }
83
+ }
84
+ } catch (err) {
85
+ if (process.env.NODE_ENV !== 'production') {
86
+ queryClient.getLogger().error(err)
87
+ queryClient
88
+ .getLogger()
89
+ .warn(
90
+ 'Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.',
91
+ )
92
+ }
93
+ persister.removeClient()
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Persists data from the QueryCache
99
+ * - data dehydrated using dehydrateOptions
100
+ * - data is persisted using persister.persistClient
101
+ */
102
+ export async function persistQueryClientSave({
103
+ queryClient,
104
+ persister,
105
+ buster = '',
106
+ dehydrateOptions,
107
+ }: PersistedQueryClientSaveOptions) {
108
+ const persistClient: PersistedClient = {
109
+ buster,
110
+ timestamp: Date.now(),
111
+ clientState: dehydrate(queryClient, dehydrateOptions),
112
+ }
113
+
114
+ await persister.persistClient(persistClient)
115
+ }
116
+
117
+ /**
118
+ * Subscribe to QueryCache and MutationCache updates (for persisting)
119
+ * @returns an unsubscribe function (to discontinue monitoring)
120
+ */
121
+ export function persistQueryClientSubscribe(
122
+ props: PersistedQueryClientSaveOptions,
123
+ ) {
124
+ const unsubscribeQueryCache = props.queryClient
125
+ .getQueryCache()
126
+ .subscribe(() => {
127
+ persistQueryClientSave(props)
128
+ })
129
+
130
+ const unusbscribeMutationCache = props.queryClient
131
+ .getMutationCache()
132
+ .subscribe(() => {
133
+ persistQueryClientSave(props)
134
+ })
135
+
136
+ return () => {
137
+ unsubscribeQueryCache()
138
+ unusbscribeMutationCache()
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Restores persisted data to QueryCache and persists further changes.
144
+ */
145
+ export function persistQueryClient(
146
+ props: PersistQueryClientOptions,
147
+ ): [() => void, Promise<void>] {
148
+ let hasUnsubscribed = false
149
+ let persistQueryClientUnsubscribe: (() => void) | undefined
150
+ const unsubscribe = () => {
151
+ hasUnsubscribed = true
152
+ persistQueryClientUnsubscribe?.()
153
+ }
154
+
155
+ // Attempt restore
156
+ const restorePromise = persistQueryClientRestore(props).then(() => {
157
+ if (!hasUnsubscribed) {
158
+ // Subscribe to changes in the query cache to trigger the save
159
+ persistQueryClientUnsubscribe = persistQueryClientSubscribe(props)
160
+ }
161
+ })
162
+
163
+ return [unsubscribe, restorePromise]
164
+ }