@tanstack/react-query-persist-client 4.2.1 → 4.3.0-beta.3

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.
Files changed (68) hide show
  1. package/build/{types/packages/react-query-persist-client/src → lib}/PersistQueryClientProvider.d.ts +0 -0
  2. package/build/{types/packages/react-query-persist-client/src → lib}/index.d.ts +0 -0
  3. package/build/lib/index.js +225 -0
  4. package/build/lib/index.js.map +1 -0
  5. package/build/{cjs/react-query-persist-client/src/persist.js → lib/index.mjs} +89 -12
  6. package/build/lib/index.mjs.map +1 -0
  7. package/build/{types/packages/react-query-persist-client/src → lib}/persist.d.ts +0 -0
  8. package/build/{types/packages/react-query-persist-client/src → lib}/retryStrategies.d.ts +0 -0
  9. package/build/umd/index.development.js +6 -303
  10. package/build/umd/index.development.js.map +1 -1
  11. package/build/umd/index.production.js +1 -11
  12. package/build/umd/index.production.js.map +1 -1
  13. package/package.json +19 -8
  14. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js +0 -33
  15. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js.map +0 -1
  16. package/build/cjs/query-core/build/esm/index.js +0 -314
  17. package/build/cjs/query-core/build/esm/index.js.map +0 -1
  18. package/build/cjs/react-query-persist-client/src/PersistQueryClientProvider.js +0 -83
  19. package/build/cjs/react-query-persist-client/src/PersistQueryClientProvider.js.map +0 -1
  20. package/build/cjs/react-query-persist-client/src/index.js +0 -27
  21. package/build/cjs/react-query-persist-client/src/index.js.map +0 -1
  22. package/build/cjs/react-query-persist-client/src/persist.js.map +0 -1
  23. package/build/cjs/react-query-persist-client/src/retryStrategies.js +0 -39
  24. package/build/cjs/react-query-persist-client/src/retryStrategies.js.map +0 -1
  25. package/build/esm/index.js +0 -492
  26. package/build/esm/index.js.map +0 -1
  27. package/build/stats-html.html +0 -2689
  28. package/build/stats.json +0 -217
  29. package/build/types/packages/query-core/src/focusManager.d.ts +0 -16
  30. package/build/types/packages/query-core/src/hydration.d.ts +0 -34
  31. package/build/types/packages/query-core/src/index.d.ts +0 -20
  32. package/build/types/packages/query-core/src/infiniteQueryBehavior.d.ts +0 -15
  33. package/build/types/packages/query-core/src/infiniteQueryObserver.d.ts +0 -18
  34. package/build/types/packages/query-core/src/logger.d.ts +0 -8
  35. package/build/types/packages/query-core/src/mutation.d.ts +0 -70
  36. package/build/types/packages/query-core/src/mutationCache.d.ts +0 -57
  37. package/build/types/packages/query-core/src/mutationObserver.d.ts +0 -23
  38. package/build/types/packages/query-core/src/notifyManager.d.ts +0 -18
  39. package/build/types/packages/query-core/src/onlineManager.d.ts +0 -16
  40. package/build/types/packages/query-core/src/queriesObserver.d.ts +0 -23
  41. package/build/types/packages/query-core/src/query.d.ts +0 -119
  42. package/build/types/packages/query-core/src/queryCache.d.ts +0 -64
  43. package/build/types/packages/query-core/src/queryClient.d.ts +0 -65
  44. package/build/types/packages/query-core/src/queryObserver.d.ts +0 -61
  45. package/build/types/packages/query-core/src/removable.d.ts +0 -9
  46. package/build/types/packages/query-core/src/retryer.d.ts +0 -33
  47. package/build/types/packages/query-core/src/subscribable.d.ts +0 -10
  48. package/build/types/packages/query-core/src/types.d.ts +0 -419
  49. package/build/types/packages/query-core/src/utils.d.ts +0 -99
  50. package/build/types/packages/react-query/src/Hydrate.d.ts +0 -10
  51. package/build/types/packages/react-query/src/QueryClientProvider.d.ts +0 -24
  52. package/build/types/packages/react-query/src/QueryErrorResetBoundary.d.ts +0 -12
  53. package/build/types/packages/react-query/src/index.d.ts +0 -17
  54. package/build/types/packages/react-query/src/isRestoring.d.ts +0 -3
  55. package/build/types/packages/react-query/src/reactBatchedUpdates.d.ts +0 -2
  56. package/build/types/packages/react-query/src/setBatchUpdatesFn.d.ts +0 -1
  57. package/build/types/packages/react-query/src/types.d.ts +0 -34
  58. package/build/types/packages/react-query/src/useBaseQuery.d.ts +0 -3
  59. package/build/types/packages/react-query/src/useInfiniteQuery.d.ts +0 -5
  60. package/build/types/packages/react-query/src/useIsFetching.d.ts +0 -7
  61. package/build/types/packages/react-query/src/useIsMutating.d.ts +0 -7
  62. package/build/types/packages/react-query/src/useMutation.d.ts +0 -6
  63. package/build/types/packages/react-query/src/useQueries.d.ts +0 -49
  64. package/build/types/packages/react-query/src/useQuery.d.ts +0 -23
  65. package/build/types/packages/react-query/src/utils.d.ts +0 -1
  66. package/build/types/packages/react-query-persist-client/src/__tests__/PersistQueryClientProvider.test.d.ts +0 -1
  67. package/build/types/packages/react-query-persist-client/src/__tests__/persist.test.d.ts +0 -1
  68. package/build/types/tests/utils.d.ts +0 -24
@@ -1,27 +0,0 @@
1
- /**
2
- * react-query-persist-client
3
- *
4
- * Copyright (c) TanStack
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- 'use strict';
12
-
13
- Object.defineProperty(exports, '__esModule', { value: true });
14
-
15
- var persist = require('./persist.js');
16
- var PersistQueryClientProvider = require('./PersistQueryClientProvider.js');
17
- var retryStrategies = require('./retryStrategies.js');
18
-
19
-
20
-
21
- exports.persistQueryClient = persist.persistQueryClient;
22
- exports.persistQueryClientRestore = persist.persistQueryClientRestore;
23
- exports.persistQueryClientSave = persist.persistQueryClientSave;
24
- exports.persistQueryClientSubscribe = persist.persistQueryClientSubscribe;
25
- exports.PersistQueryClientProvider = PersistQueryClientProvider.PersistQueryClientProvider;
26
- exports.removeOldestQuery = retryStrategies.removeOldestQuery;
27
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"persist.js","sources":["../../../../src/persist.ts"],"sourcesContent":["import {\n QueryClient,\n dehydrate,\n DehydratedState,\n DehydrateOptions,\n HydrateOptions,\n hydrate,\n} 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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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,39 +0,0 @@
1
- /**
2
- * react-query-persist-client
3
- *
4
- * Copyright (c) TanStack
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- 'use strict';
12
-
13
- Object.defineProperty(exports, '__esModule', { value: true });
14
-
15
- const removeOldestQuery = ({
16
- persistedClient
17
- }) => {
18
- const mutations = [...persistedClient.clientState.mutations];
19
- const queries = [...persistedClient.clientState.queries];
20
- const client = { ...persistedClient,
21
- clientState: {
22
- mutations,
23
- queries
24
- }
25
- }; // sort queries by dataUpdatedAt (oldest first)
26
-
27
- const sortedQueries = [...queries].sort((a, b) => a.state.dataUpdatedAt - b.state.dataUpdatedAt); // clean oldest query
28
-
29
- if (sortedQueries.length > 0) {
30
- const oldestData = sortedQueries.shift();
31
- client.clientState.queries = queries.filter(q => q !== oldestData);
32
- return client;
33
- }
34
-
35
- return undefined;
36
- };
37
-
38
- exports.removeOldestQuery = removeOldestQuery;
39
- //# sourceMappingURL=retryStrategies.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"retryStrategies.js","sources":["../../../../src/retryStrategies.ts"],"sourcesContent":["import { PersistedClient } from './persist'\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":["removeOldestQuery","persistedClient","mutations","clientState","queries","client","sortedQueries","sort","a","b","state","dataUpdatedAt","length","oldestData","shift","filter","q","undefined"],"mappings":";;;;;;;;;;;;;;AAQO,MAAMA,iBAAiC,GAAG,CAAC;AAAEC,EAAAA,eAAAA;AAAF,CAAD,KAAyB;EACxE,MAAMC,SAAS,GAAG,CAAC,GAAGD,eAAe,CAACE,WAAhB,CAA4BD,SAAhC,CAAlB,CAAA;EACA,MAAME,OAAO,GAAG,CAAC,GAAGH,eAAe,CAACE,WAAhB,CAA4BC,OAAhC,CAAhB,CAAA;AACA,EAAA,MAAMC,MAAuB,GAAG,EAC9B,GAAGJ,eAD2B;AAE9BE,IAAAA,WAAW,EAAE;MAAED,SAAF;AAAaE,MAAAA,OAAAA;AAAb,KAAA;AAFiB,GAAhC,CAHwE;;EASxE,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;;AAcxE,EAAA,IAAIL,aAAa,CAACM,MAAd,GAAuB,CAA3B,EAA8B;AAC5B,IAAA,MAAMC,UAAU,GAAGP,aAAa,CAACQ,KAAd,EAAnB,CAAA;AACAT,IAAAA,MAAM,CAACF,WAAP,CAAmBC,OAAnB,GAA6BA,OAAO,CAACW,MAAR,CAAgBC,CAAD,IAAOA,CAAC,KAAKH,UAA5B,CAA7B,CAAA;AACA,IAAA,OAAOR,MAAP,CAAA;AACD,GAAA;;AAED,EAAA,OAAOY,SAAP,CAAA;AACD;;;;"}
@@ -1,492 +0,0 @@
1
- /**
2
- * react-query-persist-client
3
- *
4
- * Copyright (c) TanStack
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- import * as React from 'react';
12
- import { QueryClientProvider, IsRestoringProvider } from '@tanstack/react-query';
13
-
14
- /**
15
- * query-core
16
- *
17
- * Copyright (c) TanStack
18
- *
19
- * This source code is licensed under the MIT license found in the
20
- * LICENSE.md file in the root directory of this source tree.
21
- *
22
- * @license MIT
23
- */
24
- class Subscribable {
25
- constructor() {
26
- this.listeners = [];
27
- this.subscribe = this.subscribe.bind(this);
28
- }
29
-
30
- subscribe(listener) {
31
- this.listeners.push(listener);
32
- this.onSubscribe();
33
- return () => {
34
- this.listeners = this.listeners.filter(x => x !== listener);
35
- this.onUnsubscribe();
36
- };
37
- }
38
-
39
- hasListeners() {
40
- return this.listeners.length > 0;
41
- }
42
-
43
- onSubscribe() {// Do nothing
44
- }
45
-
46
- onUnsubscribe() {// Do nothing
47
- }
48
-
49
- }
50
-
51
- // TYPES
52
- // UTILS
53
- const isServer = typeof window === 'undefined';
54
-
55
- class FocusManager extends Subscribable {
56
- constructor() {
57
- super();
58
-
59
- this.setup = onFocus => {
60
- // addEventListener does not exist in React Native, but window does
61
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
62
- if (!isServer && window.addEventListener) {
63
- const listener = () => onFocus(); // Listen to visibillitychange and focus
64
-
65
-
66
- window.addEventListener('visibilitychange', listener, false);
67
- window.addEventListener('focus', listener, false);
68
- return () => {
69
- // Be sure to unsubscribe if a new handler is set
70
- window.removeEventListener('visibilitychange', listener);
71
- window.removeEventListener('focus', listener);
72
- };
73
- }
74
- };
75
- }
76
-
77
- onSubscribe() {
78
- if (!this.cleanup) {
79
- this.setEventListener(this.setup);
80
- }
81
- }
82
-
83
- onUnsubscribe() {
84
- if (!this.hasListeners()) {
85
- var _this$cleanup;
86
-
87
- (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
88
- this.cleanup = undefined;
89
- }
90
- }
91
-
92
- setEventListener(setup) {
93
- var _this$cleanup2;
94
-
95
- this.setup = setup;
96
- (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
97
- this.cleanup = setup(focused => {
98
- if (typeof focused === 'boolean') {
99
- this.setFocused(focused);
100
- } else {
101
- this.onFocus();
102
- }
103
- });
104
- }
105
-
106
- setFocused(focused) {
107
- this.focused = focused;
108
-
109
- if (focused) {
110
- this.onFocus();
111
- }
112
- }
113
-
114
- onFocus() {
115
- this.listeners.forEach(listener => {
116
- listener();
117
- });
118
- }
119
-
120
- isFocused() {
121
- if (typeof this.focused === 'boolean') {
122
- return this.focused;
123
- } // document global can be unavailable in react native
124
-
125
-
126
- if (typeof document === 'undefined') {
127
- return true;
128
- }
129
-
130
- return [undefined, 'visible', 'prerender'].includes(document.visibilityState);
131
- }
132
-
133
- }
134
- new FocusManager();
135
-
136
- class OnlineManager extends Subscribable {
137
- constructor() {
138
- super();
139
-
140
- this.setup = onOnline => {
141
- // addEventListener does not exist in React Native, but window does
142
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
143
- if (!isServer && window.addEventListener) {
144
- const listener = () => onOnline(); // Listen to online
145
-
146
-
147
- window.addEventListener('online', listener, false);
148
- window.addEventListener('offline', listener, false);
149
- return () => {
150
- // Be sure to unsubscribe if a new handler is set
151
- window.removeEventListener('online', listener);
152
- window.removeEventListener('offline', listener);
153
- };
154
- }
155
- };
156
- }
157
-
158
- onSubscribe() {
159
- if (!this.cleanup) {
160
- this.setEventListener(this.setup);
161
- }
162
- }
163
-
164
- onUnsubscribe() {
165
- if (!this.hasListeners()) {
166
- var _this$cleanup;
167
-
168
- (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
169
- this.cleanup = undefined;
170
- }
171
- }
172
-
173
- setEventListener(setup) {
174
- var _this$cleanup2;
175
-
176
- this.setup = setup;
177
- (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
178
- this.cleanup = setup(online => {
179
- if (typeof online === 'boolean') {
180
- this.setOnline(online);
181
- } else {
182
- this.onOnline();
183
- }
184
- });
185
- }
186
-
187
- setOnline(online) {
188
- this.online = online;
189
-
190
- if (online) {
191
- this.onOnline();
192
- }
193
- }
194
-
195
- onOnline() {
196
- this.listeners.forEach(listener => {
197
- listener();
198
- });
199
- }
200
-
201
- isOnline() {
202
- if (typeof this.online === 'boolean') {
203
- return this.online;
204
- }
205
-
206
- if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') {
207
- return true;
208
- }
209
-
210
- return navigator.onLine;
211
- }
212
-
213
- }
214
- new OnlineManager();
215
-
216
- // TYPES
217
- // FUNCTIONS
218
- function dehydrateMutation(mutation) {
219
- return {
220
- mutationKey: mutation.options.mutationKey,
221
- state: mutation.state
222
- };
223
- } // Most config is not dehydrated but instead meant to configure again when
224
- // consuming the de/rehydrated data, typically with useQuery on the client.
225
- // Sometimes it might make sense to prefetch data on the server and include
226
- // in the html-payload, but not consume it on the initial render.
227
-
228
-
229
- function dehydrateQuery(query) {
230
- return {
231
- state: query.state,
232
- queryKey: query.queryKey,
233
- queryHash: query.queryHash
234
- };
235
- }
236
-
237
- function defaultShouldDehydrateMutation(mutation) {
238
- return mutation.state.isPaused;
239
- }
240
-
241
- function defaultShouldDehydrateQuery(query) {
242
- return query.state.status === 'success';
243
- }
244
-
245
- function dehydrate(client, options = {}) {
246
- const mutations = [];
247
- const queries = [];
248
-
249
- if (options.dehydrateMutations !== false) {
250
- const shouldDehydrateMutation = options.shouldDehydrateMutation || defaultShouldDehydrateMutation;
251
- client.getMutationCache().getAll().forEach(mutation => {
252
- if (shouldDehydrateMutation(mutation)) {
253
- mutations.push(dehydrateMutation(mutation));
254
- }
255
- });
256
- }
257
-
258
- if (options.dehydrateQueries !== false) {
259
- const shouldDehydrateQuery = options.shouldDehydrateQuery || defaultShouldDehydrateQuery;
260
- client.getQueryCache().getAll().forEach(query => {
261
- if (shouldDehydrateQuery(query)) {
262
- queries.push(dehydrateQuery(query));
263
- }
264
- });
265
- }
266
-
267
- return {
268
- mutations,
269
- queries
270
- };
271
- }
272
- function hydrate(client, dehydratedState, options) {
273
- if (typeof dehydratedState !== 'object' || dehydratedState === null) {
274
- return;
275
- }
276
-
277
- const mutationCache = client.getMutationCache();
278
- const queryCache = client.getQueryCache(); // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
279
-
280
- const mutations = dehydratedState.mutations || []; // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
281
-
282
- const queries = dehydratedState.queries || [];
283
- mutations.forEach(dehydratedMutation => {
284
- var _options$defaultOptio;
285
-
286
- mutationCache.build(client, { ...(options == null ? void 0 : (_options$defaultOptio = options.defaultOptions) == null ? void 0 : _options$defaultOptio.mutations),
287
- mutationKey: dehydratedMutation.mutationKey
288
- }, dehydratedMutation.state);
289
- });
290
- queries.forEach(dehydratedQuery => {
291
- var _options$defaultOptio2;
292
-
293
- const query = queryCache.get(dehydratedQuery.queryHash); // Do not hydrate if an existing query exists with newer data
294
-
295
- if (query) {
296
- if (query.state.dataUpdatedAt < dehydratedQuery.state.dataUpdatedAt) {
297
- query.setState(dehydratedQuery.state);
298
- }
299
-
300
- return;
301
- } // Restore query
302
-
303
-
304
- queryCache.build(client, { ...(options == null ? void 0 : (_options$defaultOptio2 = options.defaultOptions) == null ? void 0 : _options$defaultOptio2.queries),
305
- queryKey: dehydratedQuery.queryKey,
306
- queryHash: dehydratedQuery.queryHash
307
- }, dehydratedQuery.state);
308
- });
309
- }
310
-
311
- /**
312
- * Restores persisted data to the QueryCache
313
- * - data obtained from persister.restoreClient
314
- * - data is hydrated using hydrateOptions
315
- * If data is expired, busted, empty, or throws, it runs persister.removeClient
316
- */
317
- async function persistQueryClientRestore({
318
- queryClient,
319
- persister,
320
- maxAge = 1000 * 60 * 60 * 24,
321
- buster = '',
322
- hydrateOptions
323
- }) {
324
- try {
325
- const persistedClient = await persister.restoreClient();
326
-
327
- if (persistedClient) {
328
- if (persistedClient.timestamp) {
329
- const expired = Date.now() - persistedClient.timestamp > maxAge;
330
- const busted = persistedClient.buster !== buster;
331
-
332
- if (expired || busted) {
333
- persister.removeClient();
334
- } else {
335
- hydrate(queryClient, persistedClient.clientState, hydrateOptions);
336
- }
337
- } else {
338
- persister.removeClient();
339
- }
340
- }
341
- } catch (err) {
342
- if (process.env.NODE_ENV !== 'production') {
343
- queryClient.getLogger().error(err);
344
- queryClient.getLogger().warn('Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded.');
345
- }
346
-
347
- persister.removeClient();
348
- }
349
- }
350
- /**
351
- * Persists data from the QueryCache
352
- * - data dehydrated using dehydrateOptions
353
- * - data is persisted using persister.persistClient
354
- */
355
-
356
- async function persistQueryClientSave({
357
- queryClient,
358
- persister,
359
- buster = '',
360
- dehydrateOptions
361
- }) {
362
- const persistClient = {
363
- buster,
364
- timestamp: Date.now(),
365
- clientState: dehydrate(queryClient, dehydrateOptions)
366
- };
367
- await persister.persistClient(persistClient);
368
- }
369
- /**
370
- * Subscribe to QueryCache and MutationCache updates (for persisting)
371
- * @returns an unsubscribe function (to discontinue monitoring)
372
- */
373
-
374
- function persistQueryClientSubscribe(props) {
375
- const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe(() => {
376
- persistQueryClientSave(props);
377
- });
378
- const unusbscribeMutationCache = props.queryClient.getMutationCache().subscribe(() => {
379
- persistQueryClientSave(props);
380
- });
381
- return () => {
382
- unsubscribeQueryCache();
383
- unusbscribeMutationCache();
384
- };
385
- }
386
- /**
387
- * Restores persisted data to QueryCache and persists further changes.
388
- */
389
-
390
- function persistQueryClient(props) {
391
- let hasUnsubscribed = false;
392
- let persistQueryClientUnsubscribe;
393
-
394
- const unsubscribe = () => {
395
- hasUnsubscribed = true;
396
- persistQueryClientUnsubscribe == null ? void 0 : persistQueryClientUnsubscribe();
397
- }; // Attempt restore
398
-
399
-
400
- const restorePromise = persistQueryClientRestore(props).then(() => {
401
- if (!hasUnsubscribed) {
402
- // Subscribe to changes in the query cache to trigger the save
403
- persistQueryClientUnsubscribe = persistQueryClientSubscribe(props);
404
- }
405
- });
406
- return [unsubscribe, restorePromise];
407
- }
408
-
409
- function _extends() {
410
- _extends = Object.assign ? Object.assign.bind() : function (target) {
411
- for (var i = 1; i < arguments.length; i++) {
412
- var source = arguments[i];
413
-
414
- for (var key in source) {
415
- if (Object.prototype.hasOwnProperty.call(source, key)) {
416
- target[key] = source[key];
417
- }
418
- }
419
- }
420
-
421
- return target;
422
- };
423
- return _extends.apply(this, arguments);
424
- }
425
-
426
- const PersistQueryClientProvider = ({
427
- client,
428
- children,
429
- persistOptions,
430
- onSuccess,
431
- ...props
432
- }) => {
433
- const [isRestoring, setIsRestoring] = React.useState(true);
434
- const refs = React.useRef({
435
- persistOptions,
436
- onSuccess
437
- });
438
- React.useEffect(() => {
439
- refs.current = {
440
- persistOptions,
441
- onSuccess
442
- };
443
- });
444
- React.useEffect(() => {
445
- let isStale = false;
446
- setIsRestoring(true);
447
- const [unsubscribe, promise] = persistQueryClient({ ...refs.current.persistOptions,
448
- queryClient: client
449
- });
450
- promise.then(() => {
451
- if (!isStale) {
452
- refs.current.onSuccess == null ? void 0 : refs.current.onSuccess();
453
- setIsRestoring(false);
454
- }
455
- });
456
- return () => {
457
- isStale = true;
458
- unsubscribe();
459
- };
460
- }, [client]);
461
- return /*#__PURE__*/React.createElement(QueryClientProvider, _extends({
462
- client: client
463
- }, props), /*#__PURE__*/React.createElement(IsRestoringProvider, {
464
- value: isRestoring
465
- }, children));
466
- };
467
-
468
- const removeOldestQuery = ({
469
- persistedClient
470
- }) => {
471
- const mutations = [...persistedClient.clientState.mutations];
472
- const queries = [...persistedClient.clientState.queries];
473
- const client = { ...persistedClient,
474
- clientState: {
475
- mutations,
476
- queries
477
- }
478
- }; // sort queries by dataUpdatedAt (oldest first)
479
-
480
- const sortedQueries = [...queries].sort((a, b) => a.state.dataUpdatedAt - b.state.dataUpdatedAt); // clean oldest query
481
-
482
- if (sortedQueries.length > 0) {
483
- const oldestData = sortedQueries.shift();
484
- client.clientState.queries = queries.filter(q => q !== oldestData);
485
- return client;
486
- }
487
-
488
- return undefined;
489
- };
490
-
491
- export { PersistQueryClientProvider, persistQueryClient, persistQueryClientRestore, persistQueryClientSave, persistQueryClientSubscribe, removeOldestQuery };
492
- //# sourceMappingURL=index.js.map