@tanstack/query-persist-client-core 5.92.2 → 5.94.4

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 (53) hide show
  1. package/package.json +2 -2
  2. package/build/legacy/_tsup-dts-rollup.d.cts +0 -246
  3. package/build/legacy/_tsup-dts-rollup.d.ts +0 -246
  4. package/build/legacy/createPersister.cjs +0 -258
  5. package/build/legacy/createPersister.cjs.map +0 -1
  6. package/build/legacy/createPersister.d.cts +0 -6
  7. package/build/legacy/createPersister.d.ts +0 -6
  8. package/build/legacy/createPersister.js +0 -237
  9. package/build/legacy/createPersister.js.map +0 -1
  10. package/build/legacy/index.cjs +0 -29
  11. package/build/legacy/index.cjs.map +0 -1
  12. package/build/legacy/index.d.cts +0 -19
  13. package/build/legacy/index.d.ts +0 -19
  14. package/build/legacy/index.js +0 -5
  15. package/build/legacy/index.js.map +0 -1
  16. package/build/legacy/persist.cjs +0 -117
  17. package/build/legacy/persist.cjs.map +0 -1
  18. package/build/legacy/persist.d.cts +0 -11
  19. package/build/legacy/persist.d.ts +0 -11
  20. package/build/legacy/persist.js +0 -89
  21. package/build/legacy/persist.js.map +0 -1
  22. package/build/legacy/retryStrategies.cjs +0 -47
  23. package/build/legacy/retryStrategies.cjs.map +0 -1
  24. package/build/legacy/retryStrategies.d.cts +0 -2
  25. package/build/legacy/retryStrategies.d.ts +0 -2
  26. package/build/legacy/retryStrategies.js +0 -22
  27. package/build/legacy/retryStrategies.js.map +0 -1
  28. package/build/modern/_tsup-dts-rollup.d.cts +0 -246
  29. package/build/modern/_tsup-dts-rollup.d.ts +0 -246
  30. package/build/modern/createPersister.cjs +0 -258
  31. package/build/modern/createPersister.cjs.map +0 -1
  32. package/build/modern/createPersister.d.cts +0 -6
  33. package/build/modern/createPersister.d.ts +0 -6
  34. package/build/modern/createPersister.js +0 -237
  35. package/build/modern/createPersister.js.map +0 -1
  36. package/build/modern/index.cjs +0 -29
  37. package/build/modern/index.cjs.map +0 -1
  38. package/build/modern/index.d.cts +0 -19
  39. package/build/modern/index.d.ts +0 -19
  40. package/build/modern/index.js +0 -5
  41. package/build/modern/index.js.map +0 -1
  42. package/build/modern/persist.cjs +0 -117
  43. package/build/modern/persist.cjs.map +0 -1
  44. package/build/modern/persist.d.cts +0 -11
  45. package/build/modern/persist.d.ts +0 -11
  46. package/build/modern/persist.js +0 -89
  47. package/build/modern/persist.js.map +0 -1
  48. package/build/modern/retryStrategies.cjs +0 -47
  49. package/build/modern/retryStrategies.cjs.map +0 -1
  50. package/build/modern/retryStrategies.d.cts +0 -2
  51. package/build/modern/retryStrategies.d.ts +0 -2
  52. package/build/modern/retryStrategies.js +0 -22
  53. package/build/modern/retryStrategies.js.map +0 -1
@@ -1,237 +0,0 @@
1
- // src/createPersister.ts
2
- import {
3
- hashKey,
4
- matchQuery,
5
- notifyManager,
6
- partialMatchKey
7
- } from "@tanstack/query-core";
8
- var PERSISTER_KEY_PREFIX = "tanstack-query";
9
- function experimental_createQueryPersister({
10
- storage,
11
- buster = "",
12
- maxAge = 1e3 * 60 * 60 * 24,
13
- serialize = JSON.stringify,
14
- deserialize = JSON.parse,
15
- prefix = PERSISTER_KEY_PREFIX,
16
- refetchOnRestore = true,
17
- filters
18
- }) {
19
- function isExpiredOrBusted(persistedQuery) {
20
- if (persistedQuery.state.dataUpdatedAt) {
21
- const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt;
22
- const expired = queryAge > maxAge;
23
- const busted = persistedQuery.buster !== buster;
24
- if (expired || busted) {
25
- return true;
26
- }
27
- return false;
28
- }
29
- return true;
30
- }
31
- async function retrieveQuery(queryHash, afterRestoreMacroTask) {
32
- if (storage != null) {
33
- const storageKey = `${prefix}-${queryHash}`;
34
- try {
35
- const storedData = await storage.getItem(storageKey);
36
- if (storedData) {
37
- let persistedQuery;
38
- try {
39
- persistedQuery = await deserialize(storedData);
40
- } catch {
41
- await storage.removeItem(storageKey);
42
- return;
43
- }
44
- if (isExpiredOrBusted(persistedQuery)) {
45
- await storage.removeItem(storageKey);
46
- } else {
47
- if (afterRestoreMacroTask) {
48
- notifyManager.schedule(
49
- () => afterRestoreMacroTask(persistedQuery)
50
- );
51
- }
52
- return persistedQuery.state.data;
53
- }
54
- }
55
- } catch (err) {
56
- if (process.env.NODE_ENV === "development") {
57
- console.error(err);
58
- console.warn(
59
- "Encountered an error attempting to restore query cache from persisted location."
60
- );
61
- }
62
- await storage.removeItem(storageKey);
63
- }
64
- }
65
- return;
66
- }
67
- async function persistQueryByKey(queryKey, queryClient) {
68
- if (storage != null) {
69
- const query = queryClient.getQueryCache().find({ queryKey });
70
- if (query) {
71
- await persistQuery(query);
72
- } else {
73
- if (process.env.NODE_ENV === "development") {
74
- console.warn(
75
- "Could not find query to be persisted. QueryKey:",
76
- JSON.stringify(queryKey)
77
- );
78
- }
79
- }
80
- }
81
- }
82
- async function persistQuery(query) {
83
- if (storage != null) {
84
- const storageKey = `${prefix}-${query.queryHash}`;
85
- storage.setItem(
86
- storageKey,
87
- await serialize({
88
- state: query.state,
89
- queryKey: query.queryKey,
90
- queryHash: query.queryHash,
91
- buster
92
- })
93
- );
94
- }
95
- }
96
- async function persisterFn(queryFn, ctx, query) {
97
- const matchesFilter = filters ? matchQuery(filters, query) : true;
98
- if (matchesFilter && query.state.data === void 0 && storage != null) {
99
- const restoredData = await retrieveQuery(
100
- query.queryHash,
101
- (persistedQuery) => {
102
- query.setState({
103
- dataUpdatedAt: persistedQuery.state.dataUpdatedAt,
104
- errorUpdatedAt: persistedQuery.state.errorUpdatedAt
105
- });
106
- if (refetchOnRestore === "always" || refetchOnRestore === true && query.isStale()) {
107
- query.fetch();
108
- }
109
- }
110
- );
111
- if (restoredData !== void 0) {
112
- return Promise.resolve(restoredData);
113
- }
114
- }
115
- const queryFnResult = await queryFn(ctx);
116
- if (matchesFilter && storage != null) {
117
- notifyManager.schedule(() => {
118
- persistQuery(query);
119
- });
120
- }
121
- return Promise.resolve(queryFnResult);
122
- }
123
- async function persisterGc() {
124
- if (storage?.entries) {
125
- const storageKeyPrefix = `${prefix}-`;
126
- const entries = await storage.entries();
127
- for (const [key, value] of entries) {
128
- if (key.startsWith(storageKeyPrefix)) {
129
- let persistedQuery;
130
- try {
131
- persistedQuery = await deserialize(value);
132
- } catch {
133
- await storage.removeItem(key);
134
- continue;
135
- }
136
- if (isExpiredOrBusted(persistedQuery)) {
137
- await storage.removeItem(key);
138
- }
139
- }
140
- }
141
- } else if (process.env.NODE_ENV === "development") {
142
- throw new Error(
143
- "Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items."
144
- );
145
- }
146
- }
147
- async function restoreQueries(queryClient, filters2 = {}) {
148
- const { exact, queryKey } = filters2;
149
- if (storage?.entries) {
150
- const storageKeyPrefix = `${prefix}-`;
151
- const entries = await storage.entries();
152
- for (const [key, value] of entries) {
153
- if (key.startsWith(storageKeyPrefix)) {
154
- let persistedQuery;
155
- try {
156
- persistedQuery = await deserialize(value);
157
- } catch {
158
- await storage.removeItem(key);
159
- continue;
160
- }
161
- if (isExpiredOrBusted(persistedQuery)) {
162
- await storage.removeItem(key);
163
- continue;
164
- }
165
- if (queryKey) {
166
- if (exact) {
167
- if (persistedQuery.queryHash !== hashKey(queryKey)) {
168
- continue;
169
- }
170
- } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {
171
- continue;
172
- }
173
- }
174
- queryClient.setQueryData(
175
- persistedQuery.queryKey,
176
- persistedQuery.state.data,
177
- {
178
- updatedAt: persistedQuery.state.dataUpdatedAt
179
- }
180
- );
181
- }
182
- }
183
- } else if (process.env.NODE_ENV === "development") {
184
- throw new Error(
185
- "Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items."
186
- );
187
- }
188
- }
189
- async function removeQueries(filters2 = {}) {
190
- const { exact, queryKey } = filters2;
191
- if (storage?.entries) {
192
- const entries = await storage.entries();
193
- const storageKeyPrefix = `${prefix}-`;
194
- for (const [key, value] of entries) {
195
- if (key.startsWith(storageKeyPrefix)) {
196
- if (!queryKey) {
197
- await storage.removeItem(key);
198
- continue;
199
- }
200
- let persistedQuery;
201
- try {
202
- persistedQuery = await deserialize(value);
203
- } catch {
204
- await storage.removeItem(key);
205
- continue;
206
- }
207
- if (exact) {
208
- if (persistedQuery.queryHash !== hashKey(queryKey)) {
209
- continue;
210
- }
211
- } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {
212
- continue;
213
- }
214
- await storage.removeItem(key);
215
- }
216
- }
217
- } else if (process.env.NODE_ENV === "development") {
218
- throw new Error(
219
- "Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items."
220
- );
221
- }
222
- }
223
- return {
224
- persisterFn,
225
- persistQuery,
226
- persistQueryByKey,
227
- retrieveQuery,
228
- persisterGc,
229
- restoreQueries,
230
- removeQueries
231
- };
232
- }
233
- export {
234
- PERSISTER_KEY_PREFIX,
235
- experimental_createQueryPersister
236
- };
237
- //# sourceMappingURL=createPersister.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/createPersister.ts"],"sourcesContent":["import {\n hashKey,\n matchQuery,\n notifyManager,\n partialMatchKey,\n} from '@tanstack/query-core'\nimport type {\n Query,\n QueryClient,\n QueryFilters,\n QueryFunctionContext,\n QueryKey,\n QueryState,\n} from '@tanstack/query-core'\n\nexport interface PersistedQuery {\n buster: string\n queryHash: string\n queryKey: QueryKey\n state: QueryState\n}\n\nexport type MaybePromise<T> = T | Promise<T>\n\nexport interface AsyncStorage<TStorageValue = string> {\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n removeItem: (key: string) => MaybePromise<void>\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /** The storage client used for setting and retrieving items from cache.\n * For SSR pass in `undefined`.\n */\n storage: AsyncStorage<TStorageValue> | undefined | null\n /**\n * How to serialize the data to storage.\n * @default `JSON.stringify`\n */\n serialize?: (persistedQuery: PersistedQuery) => MaybePromise<TStorageValue>\n /**\n * How to deserialize the data from storage.\n * @default `JSON.parse`\n */\n deserialize?: (cachedString: TStorageValue) => MaybePromise<PersistedQuery>\n /**\n * A unique string that can be used to forcefully invalidate existing caches,\n * if they do not share the same buster string\n */\n buster?: string\n /**\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 * @default 24 hours\n */\n maxAge?: number\n /**\n * Prefix to be used for storage key.\n * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.\n * @default 'tanstack-query'\n */\n prefix?: string\n /**\n * If set to `true`, the query will refetch on successful query restoration if the data is stale.\n * If set to `false`, the query will not refetch on successful query restoration.\n * If set to `'always'`, the query will always refetch on successful query restoration.\n * Defaults to `true`.\n */\n refetchOnRestore?: boolean | 'always'\n /**\n * Filters to narrow down which Queries should be persisted.\n */\n filters?: QueryFilters\n}\n\nexport const PERSISTER_KEY_PREFIX = 'tanstack-query'\n\n/**\n * Warning: experimental feature.\n * This utility function enables fine-grained query persistence.\n * Simple add it as a `persister` parameter to `useQuery` or `defaultOptions` on `queryClient`.\n *\n * ```\n * useQuery({\n queryKey: ['myKey'],\n queryFn: fetcher,\n persister: createPersister({\n storage: localStorage,\n }),\n })\n ```\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 1000 * 60 * 60 * 24,\n serialize = JSON.stringify as Required<\n StoragePersisterOptions<TStorageValue>\n >['serialize'],\n deserialize = JSON.parse as Required<\n StoragePersisterOptions<TStorageValue>\n >['deserialize'],\n prefix = PERSISTER_KEY_PREFIX,\n refetchOnRestore = true,\n filters,\n}: StoragePersisterOptions<TStorageValue>) {\n function isExpiredOrBusted(persistedQuery: PersistedQuery) {\n if (persistedQuery.state.dataUpdatedAt) {\n const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt\n const expired = queryAge > maxAge\n const busted = persistedQuery.buster !== buster\n\n if (expired || busted) {\n return true\n }\n\n return false\n }\n\n return true\n }\n\n async function retrieveQuery<T>(\n queryHash: string,\n afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,\n ) {\n if (storage != null) {\n const storageKey = `${prefix}-${queryHash}`\n try {\n const storedData = await storage.getItem(storageKey)\n if (storedData) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(storedData)\n } catch {\n await storage.removeItem(storageKey)\n return\n }\n\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(storageKey)\n } else {\n if (afterRestoreMacroTask) {\n // Just after restoring we want to get fresh data from the server if it's stale\n notifyManager.schedule(() =>\n afterRestoreMacroTask(persistedQuery),\n )\n }\n // We must resolve the promise here, as otherwise we will have `loading` state in the app until `queryFn` resolves\n return persistedQuery.state.data as T\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV === 'development') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to restore query cache from persisted location.',\n )\n }\n await storage.removeItem(storageKey)\n }\n }\n\n return\n }\n\n async function persistQueryByKey(\n queryKey: QueryKey,\n queryClient: QueryClient,\n ) {\n if (storage != null) {\n const query = queryClient.getQueryCache().find({ queryKey })\n if (query) {\n await persistQuery(query)\n } else {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n 'Could not find query to be persisted. QueryKey:',\n JSON.stringify(queryKey),\n )\n }\n }\n }\n }\n\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n storage.setItem(\n storageKey,\n await serialize({\n state: query.state,\n queryKey: query.queryKey,\n queryHash: query.queryHash,\n buster: buster,\n }),\n )\n }\n }\n\n async function persisterFn<T, TQueryKey extends QueryKey>(\n queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,\n ctx: QueryFunctionContext<TQueryKey>,\n query: Query,\n ) {\n const matchesFilter = filters ? matchQuery(filters, query) : true\n\n // Try to restore only if we do not have any data in the cache and we have persister defined\n if (matchesFilter && query.state.data === undefined && storage != null) {\n const restoredData = await retrieveQuery(\n query.queryHash,\n (persistedQuery: PersistedQuery) => {\n // Set proper updatedAt, since resolving in the first pass overrides those values\n query.setState({\n dataUpdatedAt: persistedQuery.state.dataUpdatedAt,\n errorUpdatedAt: persistedQuery.state.errorUpdatedAt,\n })\n\n if (\n refetchOnRestore === 'always' ||\n (refetchOnRestore === true && query.isStale())\n ) {\n query.fetch()\n }\n },\n )\n\n if (restoredData !== undefined) {\n return Promise.resolve(restoredData as T)\n }\n }\n\n // If we did not restore, or restoration failed - fetch\n const queryFnResult = await queryFn(ctx)\n\n if (matchesFilter && storage != null) {\n // Persist if we have storage defined, we use timeout to get proper state to be persisted\n notifyManager.schedule(() => {\n persistQuery(query)\n })\n }\n\n return Promise.resolve(queryFnResult)\n }\n\n async function persisterGc() {\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n }\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Garbage collection is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n async function restoreQueries(\n queryClient: QueryClient,\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const storageKeyPrefix = `${prefix}-`\n const entries = await storage.entries()\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n if (isExpiredOrBusted(persistedQuery)) {\n await storage.removeItem(key)\n continue\n }\n\n if (queryKey) {\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n }\n\n queryClient.setQueryData(\n persistedQuery.queryKey,\n persistedQuery.state.data,\n {\n updatedAt: persistedQuery.state.dataUpdatedAt,\n },\n )\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Restoration of all stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n async function removeQueries(\n filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},\n ): Promise<void> {\n const { exact, queryKey } = filters\n\n if (storage?.entries) {\n const entries = await storage.entries()\n const storageKeyPrefix = `${prefix}-`\n for (const [key, value] of entries) {\n if (key.startsWith(storageKeyPrefix)) {\n if (!queryKey) {\n await storage.removeItem(key)\n continue\n }\n\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(value)\n } catch {\n await storage.removeItem(key)\n continue\n }\n\n if (exact) {\n if (persistedQuery.queryHash !== hashKey(queryKey)) {\n continue\n }\n } else if (!partialMatchKey(persistedQuery.queryKey, queryKey)) {\n continue\n }\n\n await storage.removeItem(key)\n }\n }\n } else if (process.env.NODE_ENV === 'development') {\n throw new Error(\n 'Provided storage does not implement `entries` method. Removal of stored entries is not possible without ability to iterate over storage items.',\n )\n }\n }\n\n return {\n persisterFn,\n persistQuery,\n persistQueryByKey,\n retrieveQuery,\n persisterGc,\n restoreQueries,\n removeQueries,\n }\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAwEA,IAAM,uBAAuB;AAiB7B,SAAS,kCAA0D;AAAA,EACxE;AAAA,EACA,SAAS;AAAA,EACT,SAAS,MAAO,KAAK,KAAK;AAAA,EAC1B,YAAY,KAAK;AAAA,EAGjB,cAAc,KAAK;AAAA,EAGnB,SAAS;AAAA,EACT,mBAAmB;AAAA,EACnB;AACF,GAA2C;AACzC,WAAS,kBAAkB,gBAAgC;AACzD,QAAI,eAAe,MAAM,eAAe;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AIA;AAE5B,QAAI,SAAS,SAAS;AACpB,YAAM,UAAU,MAAM,QAAQ,QAAQ;AACtC,YAAM,mBAAmB,GAAG,MAAM;AAClC,iBAAW,CAAC,KAAK,KAAK,KAAK,SAAS;AAClC,YAAI,IAAI,WAAW,gBAAgB,GAAG;AACpC,cAAI,CAAC,UAAU;AACb,kBAAM,QAAQ,WAAW,GAAG;AAC5B;AAAA,UACF;AAEA,cAAI;AACJ,cAAI;AACF,6BAAiB,MAAM,YAAY,KAAK;AAAA,UAC1C,QAAQ;AACN,kBAAM,QAAQ,WAAW,GAAG;AAC5B;AAAA,UACF;AAEA,cAAI,OAAO;AACT,gBAAI,eAAe,cAAc,QAAQ,QAAQ,GAAG;AAClD;AAAA,YACF;AAAA,UACF,WAAW,CAAC,gBAAgB,eAAe,UAAU,QAAQ,GAAG;AAC9D;AAAA,UACF;AAEA,gBAAM,QAAQ,WAAW,GAAG;AAAA,QAC9B;AAAA,MACF;AAAA,IACF,WAAW,QAAQ,IAAI,aAAa,eAAe;AACjD,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":["filters"]}
@@ -1,29 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __copyProps = (to, from, except, desc) => {
7
- if (from && typeof from === "object" || typeof from === "function") {
8
- for (let key of __getOwnPropNames(from))
9
- if (!__hasOwnProp.call(to, key) && key !== except)
10
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
- }
12
- return to;
13
- };
14
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
-
17
- // src/index.ts
18
- var index_exports = {};
19
- module.exports = __toCommonJS(index_exports);
20
- __reExport(index_exports, require("./persist.cjs"), module.exports);
21
- __reExport(index_exports, require("./retryStrategies.cjs"), module.exports);
22
- __reExport(index_exports, require("./createPersister.cjs"), module.exports);
23
- // Annotate the CommonJS export names for ESM import in node:
24
- 0 && (module.exports = {
25
- ...require("./persist.cjs"),
26
- ...require("./retryStrategies.cjs"),
27
- ...require("./createPersister.cjs")
28
- });
29
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport * from './persist'\nexport * from './retryStrategies'\nexport * from './createPersister'\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA;AAAA;AAEA,0BAAc,0BAFd;AAGA,0BAAc,kCAHd;AAIA,0BAAc,kCAJd;","names":[]}
@@ -1,19 +0,0 @@
1
- export { persistQueryClientRestore } from './_tsup-dts-rollup.cjs';
2
- export { persistQueryClientSave } from './_tsup-dts-rollup.cjs';
3
- export { persistQueryClientSubscribe } from './_tsup-dts-rollup.cjs';
4
- export { persistQueryClient } from './_tsup-dts-rollup.cjs';
5
- export { Promisable } from './_tsup-dts-rollup.cjs';
6
- export { Persister } from './_tsup-dts-rollup.cjs';
7
- export { PersistedClient } from './_tsup-dts-rollup.cjs';
8
- export { PersistQueryClientRootOptions } from './_tsup-dts-rollup.cjs';
9
- export { PersistedQueryClientRestoreOptions } from './_tsup-dts-rollup.cjs';
10
- export { PersistedQueryClientSaveOptions } from './_tsup-dts-rollup.cjs';
11
- export { PersistQueryClientOptions } from './_tsup-dts-rollup.cjs';
12
- export { PersistRetryer } from './_tsup-dts-rollup.cjs';
13
- export { removeOldestQuery } from './_tsup-dts-rollup.cjs';
14
- export { experimental_createQueryPersister_alias_1 as experimental_createQueryPersister } from './_tsup-dts-rollup.cjs';
15
- export { PersistedQuery_alias_1 as PersistedQuery } from './_tsup-dts-rollup.cjs';
16
- export { MaybePromise_alias_1 as MaybePromise } from './_tsup-dts-rollup.cjs';
17
- export { AsyncStorage_alias_1 as AsyncStorage } from './_tsup-dts-rollup.cjs';
18
- export { StoragePersisterOptions_alias_1 as StoragePersisterOptions } from './_tsup-dts-rollup.cjs';
19
- export { PERSISTER_KEY_PREFIX_alias_1 as PERSISTER_KEY_PREFIX } from './_tsup-dts-rollup.cjs';
@@ -1,19 +0,0 @@
1
- export { persistQueryClientRestore } from './_tsup-dts-rollup.js';
2
- export { persistQueryClientSave } from './_tsup-dts-rollup.js';
3
- export { persistQueryClientSubscribe } from './_tsup-dts-rollup.js';
4
- export { persistQueryClient } from './_tsup-dts-rollup.js';
5
- export { Promisable } from './_tsup-dts-rollup.js';
6
- export { Persister } from './_tsup-dts-rollup.js';
7
- export { PersistedClient } from './_tsup-dts-rollup.js';
8
- export { PersistQueryClientRootOptions } from './_tsup-dts-rollup.js';
9
- export { PersistedQueryClientRestoreOptions } from './_tsup-dts-rollup.js';
10
- export { PersistedQueryClientSaveOptions } from './_tsup-dts-rollup.js';
11
- export { PersistQueryClientOptions } from './_tsup-dts-rollup.js';
12
- export { PersistRetryer } from './_tsup-dts-rollup.js';
13
- export { removeOldestQuery } from './_tsup-dts-rollup.js';
14
- export { experimental_createQueryPersister_alias_1 as experimental_createQueryPersister } from './_tsup-dts-rollup.js';
15
- export { PersistedQuery_alias_1 as PersistedQuery } from './_tsup-dts-rollup.js';
16
- export { MaybePromise_alias_1 as MaybePromise } from './_tsup-dts-rollup.js';
17
- export { AsyncStorage_alias_1 as AsyncStorage } from './_tsup-dts-rollup.js';
18
- export { StoragePersisterOptions_alias_1 as StoragePersisterOptions } from './_tsup-dts-rollup.js';
19
- export { PERSISTER_KEY_PREFIX_alias_1 as PERSISTER_KEY_PREFIX } from './_tsup-dts-rollup.js';
@@ -1,5 +0,0 @@
1
- // src/index.ts
2
- export * from "./persist.js";
3
- export * from "./retryStrategies.js";
4
- export * from "./createPersister.js";
5
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["/* istanbul ignore file */\n\nexport * from './persist'\nexport * from './retryStrategies'\nexport * from './createPersister'\n"],"mappings":";AAEA,cAAc;AACd,cAAc;AACd,cAAc;","names":[]}
@@ -1,117 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/persist.ts
21
- var persist_exports = {};
22
- __export(persist_exports, {
23
- persistQueryClient: () => persistQueryClient,
24
- persistQueryClientRestore: () => persistQueryClientRestore,
25
- persistQueryClientSave: () => persistQueryClientSave,
26
- persistQueryClientSubscribe: () => persistQueryClientSubscribe
27
- });
28
- module.exports = __toCommonJS(persist_exports);
29
- var import_query_core = require("@tanstack/query-core");
30
- var cacheEventTypes = ["added", "removed", "updated"];
31
- function isCacheEventType(eventType) {
32
- return cacheEventTypes.includes(eventType);
33
- }
34
- async function persistQueryClientRestore({
35
- queryClient,
36
- persister,
37
- maxAge = 1e3 * 60 * 60 * 24,
38
- buster = "",
39
- hydrateOptions
40
- }) {
41
- try {
42
- const persistedClient = await persister.restoreClient();
43
- if (persistedClient) {
44
- if (persistedClient.timestamp) {
45
- const expired = Date.now() - persistedClient.timestamp > maxAge;
46
- const busted = persistedClient.buster !== buster;
47
- if (expired || busted) {
48
- return persister.removeClient();
49
- } else {
50
- (0, import_query_core.hydrate)(queryClient, persistedClient.clientState, hydrateOptions);
51
- }
52
- } else {
53
- return persister.removeClient();
54
- }
55
- }
56
- } catch (err) {
57
- if (process.env.NODE_ENV !== "production") {
58
- console.error(err);
59
- console.warn(
60
- "Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded."
61
- );
62
- }
63
- await persister.removeClient();
64
- throw err;
65
- }
66
- }
67
- async function persistQueryClientSave({
68
- queryClient,
69
- persister,
70
- buster = "",
71
- dehydrateOptions
72
- }) {
73
- const persistClient = {
74
- buster,
75
- timestamp: Date.now(),
76
- clientState: (0, import_query_core.dehydrate)(queryClient, dehydrateOptions)
77
- };
78
- await persister.persistClient(persistClient);
79
- }
80
- function persistQueryClientSubscribe(props) {
81
- const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe((event) => {
82
- if (isCacheEventType(event.type)) {
83
- persistQueryClientSave(props);
84
- }
85
- });
86
- const unsubscribeMutationCache = props.queryClient.getMutationCache().subscribe((event) => {
87
- if (isCacheEventType(event.type)) {
88
- persistQueryClientSave(props);
89
- }
90
- });
91
- return () => {
92
- unsubscribeQueryCache();
93
- unsubscribeMutationCache();
94
- };
95
- }
96
- function persistQueryClient(props) {
97
- let hasUnsubscribed = false;
98
- let persistQueryClientUnsubscribe;
99
- const unsubscribe = () => {
100
- hasUnsubscribed = true;
101
- persistQueryClientUnsubscribe?.();
102
- };
103
- const restorePromise = persistQueryClientRestore(props).then(() => {
104
- if (!hasUnsubscribed) {
105
- persistQueryClientUnsubscribe = persistQueryClientSubscribe(props);
106
- }
107
- });
108
- return [unsubscribe, restorePromise];
109
- }
110
- // Annotate the CommonJS export names for ESM import in node:
111
- 0 && (module.exports = {
112
- persistQueryClient,
113
- persistQueryClientRestore,
114
- persistQueryClientSave,
115
- persistQueryClientSubscribe
116
- });
117
- //# sourceMappingURL=persist.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/persist.ts"],"sourcesContent":["import { dehydrate, hydrate } from '@tanstack/query-core'\nimport type {\n DehydrateOptions,\n DehydratedState,\n HydrateOptions,\n NotifyEventType,\n QueryClient,\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 PersistQueryClientRootOptions {\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 extends PersistQueryClientRootOptions {\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 extends PersistQueryClientRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\nexport interface PersistQueryClientOptions\n extends\n PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClientRootOptions {}\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 cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']\n\nfunction isCacheEventType(eventType: NotifyEventType) {\n return cacheEventTypes.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 return persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n return persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(err)\n console.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\n await persister.removeClient()\n\n throw err\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 (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n const unsubscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unsubscribeMutationCache()\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAmC;AA0DnC,IAAM,kBAA0C,CAAC,SAAS,WAAW,SAAS;AAE9E,SAAS,iBAAiB,WAA4B;AACpD,SAAO,gBAAgB,SAAS,SAAS;AAC3C;AAQA,eAAsB,0BAA0B;AAAA,EAC9C;AAAA,EACA;AAAA,EACA,SAAS,MAAO,KAAK,KAAK;AAAA,EAC1B,SAAS;AAAA,EACT;AACF,GAAuC;AACrC,MAAI;AACF,UAAM,kBAAkB,MAAM,UAAU,cAAc;AAEtD,QAAI,iBAAiB;AACnB,UAAI,gBAAgB,WAAW;AAC7B,cAAM,UAAU,KAAK,IAAI,IAAI,gBAAgB,YAAY;AACzD,cAAM,SAAS,gBAAgB,WAAW;AAC1C,YAAI,WAAW,QAAQ;AACrB,iBAAO,UAAU,aAAa;AAAA,QAChC,OAAO;AACL,yCAAQ,aAAa,gBAAgB,aAAa,cAAc;AAAA,QAClE;AAAA,MACF,OAAO;AACL,eAAO,UAAU,aAAa;AAAA,MAChC;AAAA,IACF;AAAA,EACF,SAAS,KAAK;AACZ,QAAI,QAAQ,IAAI,aAAa,cAAc;AACzC,cAAQ,MAAM,GAAG;AACjB,cAAQ;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAEA,UAAM,UAAU,aAAa;AAE7B,UAAM;AAAA,EACR;AACF;AAOA,eAAsB,uBAAuB;AAAA,EAC3C;AAAA,EACA;AAAA,EACA,SAAS;AAAA,EACT;AACF,GAAoC;AAClC,QAAM,gBAAiC;AAAA,IACrC;AAAA,IACA,WAAW,KAAK,IAAI;AAAA,IACpB,iBAAa,6BAAU,aAAa,gBAAgB;AAAA,EACtD;AAEA,QAAM,UAAU,cAAc,aAAa;AAC7C;AAMO,SAAS,4BACd,OACA;AACA,QAAM,wBAAwB,MAAM,YACjC,cAAc,EACd,UAAU,CAAC,UAAU;AACpB,QAAI,iBAAiB,MAAM,IAAI,GAAG;AAChC,6BAAuB,KAAK;AAAA,IAC9B;AAAA,EACF,CAAC;AAEH,QAAM,2BAA2B,MAAM,YACpC,iBAAiB,EACjB,UAAU,CAAC,UAAU;AACpB,QAAI,iBAAiB,MAAM,IAAI,GAAG;AAChC,6BAAuB,KAAK;AAAA,IAC9B;AAAA,EACF,CAAC;AAEH,SAAO,MAAM;AACX,0BAAsB;AACtB,6BAAyB;AAAA,EAC3B;AACF;AAKO,SAAS,mBACd,OAC6B;AAC7B,MAAI,kBAAkB;AACtB,MAAI;AACJ,QAAM,cAAc,MAAM;AACxB,sBAAkB;AAClB,oCAAgC;AAAA,EAClC;AAGA,QAAM,iBAAiB,0BAA0B,KAAK,EAAE,KAAK,MAAM;AACjE,QAAI,CAAC,iBAAiB;AAEpB,sCAAgC,4BAA4B,KAAK;AAAA,IACnE;AAAA,EACF,CAAC;AAED,SAAO,CAAC,aAAa,cAAc;AACrC;","names":[]}
@@ -1,11 +0,0 @@
1
- export { persistQueryClientRestore_alias_1 as persistQueryClientRestore } from './_tsup-dts-rollup.cjs';
2
- export { persistQueryClientSave_alias_1 as persistQueryClientSave } from './_tsup-dts-rollup.cjs';
3
- export { persistQueryClientSubscribe_alias_1 as persistQueryClientSubscribe } from './_tsup-dts-rollup.cjs';
4
- export { persistQueryClient_alias_1 as persistQueryClient } from './_tsup-dts-rollup.cjs';
5
- export { Promisable_alias_1 as Promisable } from './_tsup-dts-rollup.cjs';
6
- export { Persister_alias_1 as Persister } from './_tsup-dts-rollup.cjs';
7
- export { PersistedClient_alias_1 as PersistedClient } from './_tsup-dts-rollup.cjs';
8
- export { PersistQueryClientRootOptions_alias_1 as PersistQueryClientRootOptions } from './_tsup-dts-rollup.cjs';
9
- export { PersistedQueryClientRestoreOptions_alias_1 as PersistedQueryClientRestoreOptions } from './_tsup-dts-rollup.cjs';
10
- export { PersistedQueryClientSaveOptions_alias_1 as PersistedQueryClientSaveOptions } from './_tsup-dts-rollup.cjs';
11
- export { PersistQueryClientOptions_alias_1 as PersistQueryClientOptions } from './_tsup-dts-rollup.cjs';
@@ -1,11 +0,0 @@
1
- export { persistQueryClientRestore_alias_1 as persistQueryClientRestore } from './_tsup-dts-rollup.js';
2
- export { persistQueryClientSave_alias_1 as persistQueryClientSave } from './_tsup-dts-rollup.js';
3
- export { persistQueryClientSubscribe_alias_1 as persistQueryClientSubscribe } from './_tsup-dts-rollup.js';
4
- export { persistQueryClient_alias_1 as persistQueryClient } from './_tsup-dts-rollup.js';
5
- export { Promisable_alias_1 as Promisable } from './_tsup-dts-rollup.js';
6
- export { Persister_alias_1 as Persister } from './_tsup-dts-rollup.js';
7
- export { PersistedClient_alias_1 as PersistedClient } from './_tsup-dts-rollup.js';
8
- export { PersistQueryClientRootOptions_alias_1 as PersistQueryClientRootOptions } from './_tsup-dts-rollup.js';
9
- export { PersistedQueryClientRestoreOptions_alias_1 as PersistedQueryClientRestoreOptions } from './_tsup-dts-rollup.js';
10
- export { PersistedQueryClientSaveOptions_alias_1 as PersistedQueryClientSaveOptions } from './_tsup-dts-rollup.js';
11
- export { PersistQueryClientOptions_alias_1 as PersistQueryClientOptions } from './_tsup-dts-rollup.js';
@@ -1,89 +0,0 @@
1
- // src/persist.ts
2
- import { dehydrate, hydrate } from "@tanstack/query-core";
3
- var cacheEventTypes = ["added", "removed", "updated"];
4
- function isCacheEventType(eventType) {
5
- return cacheEventTypes.includes(eventType);
6
- }
7
- async function persistQueryClientRestore({
8
- queryClient,
9
- persister,
10
- maxAge = 1e3 * 60 * 60 * 24,
11
- buster = "",
12
- hydrateOptions
13
- }) {
14
- try {
15
- const persistedClient = await persister.restoreClient();
16
- if (persistedClient) {
17
- if (persistedClient.timestamp) {
18
- const expired = Date.now() - persistedClient.timestamp > maxAge;
19
- const busted = persistedClient.buster !== buster;
20
- if (expired || busted) {
21
- return persister.removeClient();
22
- } else {
23
- hydrate(queryClient, persistedClient.clientState, hydrateOptions);
24
- }
25
- } else {
26
- return persister.removeClient();
27
- }
28
- }
29
- } catch (err) {
30
- if (process.env.NODE_ENV !== "production") {
31
- console.error(err);
32
- console.warn(
33
- "Encountered an error attempting to restore client cache from persisted location. As a precaution, the persisted cache will be discarded."
34
- );
35
- }
36
- await persister.removeClient();
37
- throw err;
38
- }
39
- }
40
- async function persistQueryClientSave({
41
- queryClient,
42
- persister,
43
- buster = "",
44
- dehydrateOptions
45
- }) {
46
- const persistClient = {
47
- buster,
48
- timestamp: Date.now(),
49
- clientState: dehydrate(queryClient, dehydrateOptions)
50
- };
51
- await persister.persistClient(persistClient);
52
- }
53
- function persistQueryClientSubscribe(props) {
54
- const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe((event) => {
55
- if (isCacheEventType(event.type)) {
56
- persistQueryClientSave(props);
57
- }
58
- });
59
- const unsubscribeMutationCache = props.queryClient.getMutationCache().subscribe((event) => {
60
- if (isCacheEventType(event.type)) {
61
- persistQueryClientSave(props);
62
- }
63
- });
64
- return () => {
65
- unsubscribeQueryCache();
66
- unsubscribeMutationCache();
67
- };
68
- }
69
- function persistQueryClient(props) {
70
- let hasUnsubscribed = false;
71
- let persistQueryClientUnsubscribe;
72
- const unsubscribe = () => {
73
- hasUnsubscribed = true;
74
- persistQueryClientUnsubscribe?.();
75
- };
76
- const restorePromise = persistQueryClientRestore(props).then(() => {
77
- if (!hasUnsubscribed) {
78
- persistQueryClientUnsubscribe = persistQueryClientSubscribe(props);
79
- }
80
- });
81
- return [unsubscribe, restorePromise];
82
- }
83
- export {
84
- persistQueryClient,
85
- persistQueryClientRestore,
86
- persistQueryClientSave,
87
- persistQueryClientSubscribe
88
- };
89
- //# sourceMappingURL=persist.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/persist.ts"],"sourcesContent":["import { dehydrate, hydrate } from '@tanstack/query-core'\nimport type {\n DehydrateOptions,\n DehydratedState,\n HydrateOptions,\n NotifyEventType,\n QueryClient,\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 PersistQueryClientRootOptions {\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 extends PersistQueryClientRootOptions {\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 extends PersistQueryClientRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\nexport interface PersistQueryClientOptions\n extends\n PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClientRootOptions {}\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 cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']\n\nfunction isCacheEventType(eventType: NotifyEventType) {\n return cacheEventTypes.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 return persister.removeClient()\n } else {\n hydrate(queryClient, persistedClient.clientState, hydrateOptions)\n }\n } else {\n return persister.removeClient()\n }\n }\n } catch (err) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(err)\n console.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\n await persister.removeClient()\n\n throw err\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 (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n const unsubscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n persistQueryClientSave(props)\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unsubscribeMutationCache()\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"],"mappings":";AAAA,SAAS,WAAW,eAAe;AA0DnC,IAAM,kBAA0C,CAAC,SAAS,WAAW,SAAS;AAE9E,SAAS,iBAAiB,WAA4B;AACpD,SAAO,gBAAgB,SAAS,SAAS;AAC3C;AAQA,eAAsB,0BAA0B;AAAA,EAC9C;AAAA,EACA;AAAA,EACA,SAAS,MAAO,KAAK,KAAK;AAAA,EAC1B,SAAS;AAAA,EACT;AACF,GAAuC;AACrC,MAAI;AACF,UAAM,kBAAkB,MAAM,UAAU,cAAc;AAEtD,QAAI,iBAAiB;AACnB,UAAI,gBAAgB,WAAW;AAC7B,cAAM,UAAU,KAAK,IAAI,IAAI,gBAAgB,YAAY;AACzD,cAAM,SAAS,gBAAgB,WAAW;AAC1C,YAAI,WAAW,QAAQ;AACrB,iBAAO,UAAU,aAAa;AAAA,QAChC,OAAO;AACL,kBAAQ,aAAa,gBAAgB,aAAa,cAAc;AAAA,QAClE;AAAA,MACF,OAAO;AACL,eAAO,UAAU,aAAa;AAAA,MAChC;AAAA,IACF;AAAA,EACF,SAAS,KAAK;AACZ,QAAI,QAAQ,IAAI,aAAa,cAAc;AACzC,cAAQ,MAAM,GAAG;AACjB,cAAQ;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAEA,UAAM,UAAU,aAAa;AAE7B,UAAM;AAAA,EACR;AACF;AAOA,eAAsB,uBAAuB;AAAA,EAC3C;AAAA,EACA;AAAA,EACA,SAAS;AAAA,EACT;AACF,GAAoC;AAClC,QAAM,gBAAiC;AAAA,IACrC;AAAA,IACA,WAAW,KAAK,IAAI;AAAA,IACpB,aAAa,UAAU,aAAa,gBAAgB;AAAA,EACtD;AAEA,QAAM,UAAU,cAAc,aAAa;AAC7C;AAMO,SAAS,4BACd,OACA;AACA,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