@tanstack/query-persist-client-core 5.104.5 → 5.105.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/legacy/createPersister.cjs +18 -4
- package/build/legacy/createPersister.cjs.map +1 -1
- package/build/legacy/createPersister.d.cts +1 -3
- package/build/legacy/createPersister.d.cts.map +1 -1
- package/build/legacy/createPersister.d.ts +1 -3
- package/build/legacy/createPersister.d.ts.map +1 -1
- package/build/legacy/createPersister.js +18 -4
- package/build/legacy/createPersister.js.map +1 -1
- package/build/legacy/index.cjs +1 -2
- package/build/legacy/index.js +1 -2
- package/build/legacy/persist.cjs +11 -4
- package/build/legacy/persist.cjs.map +1 -1
- package/build/legacy/persist.d.cts +0 -2
- package/build/legacy/persist.d.cts.map +1 -1
- package/build/legacy/persist.d.ts +0 -2
- package/build/legacy/persist.d.ts.map +1 -1
- package/build/legacy/persist.js +11 -4
- package/build/legacy/persist.js.map +1 -1
- package/build/legacy/retryStrategies.cjs +1 -2
- package/build/legacy/retryStrategies.d.cts +0 -2
- package/build/legacy/retryStrategies.d.cts.map +1 -1
- package/build/legacy/retryStrategies.d.ts +0 -2
- package/build/legacy/retryStrategies.d.ts.map +1 -1
- package/build/legacy/retryStrategies.js +1 -2
- package/build/modern/createPersister.cjs +18 -4
- package/build/modern/createPersister.cjs.map +1 -1
- package/build/modern/createPersister.d.cts +1 -3
- package/build/modern/createPersister.d.cts.map +1 -1
- package/build/modern/createPersister.d.ts +1 -3
- package/build/modern/createPersister.d.ts.map +1 -1
- package/build/modern/createPersister.js +18 -4
- package/build/modern/createPersister.js.map +1 -1
- package/build/modern/index.cjs +1 -2
- package/build/modern/index.js +1 -2
- package/build/modern/persist.cjs +11 -4
- package/build/modern/persist.cjs.map +1 -1
- package/build/modern/persist.d.cts +0 -2
- package/build/modern/persist.d.cts.map +1 -1
- package/build/modern/persist.d.ts +0 -2
- package/build/modern/persist.d.ts.map +1 -1
- package/build/modern/persist.js +11 -4
- package/build/modern/persist.js.map +1 -1
- package/build/modern/retryStrategies.cjs +1 -2
- package/build/modern/retryStrategies.d.cts +0 -2
- package/build/modern/retryStrategies.d.cts.map +1 -1
- package/build/modern/retryStrategies.d.ts +0 -2
- package/build/modern/retryStrategies.d.ts.map +1 -1
- package/build/modern/retryStrategies.js +1 -2
- package/package.json +2 -2
- package/src/createPersister.ts +42 -3
- package/src/persist.ts +14 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"persist.js","names":[],"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\n/**\n * A value, or a promise-like that resolves to it.\n */\nexport type Promisable<T> = T | PromiseLike<T>\n\n/**\n * Saves, restores, and removes a {@link PersistedClient} in a storage.\n */\nexport interface Persister {\n /**\n * Saves the persisted client to the storage.\n */\n persistClient: (persistClient: PersistedClient) => Promisable<void>\n /**\n * Reads the persisted client from the storage, or `undefined` if nothing was saved.\n */\n restoreClient: () => Promisable<PersistedClient | undefined>\n /**\n * Removes the persisted client from the storage.\n */\n removeClient: () => Promisable<void>\n}\n\n/**\n * The dehydrated state of a `QueryClient` as it is persisted, with the time it was saved and its\n * `buster`.\n */\nexport interface PersistedClient {\n /**\n * When the client was saved, in milliseconds since the epoch. Compared with `maxAge` on restore.\n */\n timestamp: number\n /**\n * The `buster` the client was saved with. A persisted client with a different `buster` is\n * discarded.\n */\n buster: string\n /**\n * The dehydrated cache of the `QueryClient`.\n */\n clientState: DehydratedState\n}\n\n/**\n * The options shared by restoring and saving a persisted `QueryClient`.\n */\nexport interface PersistQueryClientRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /**\n * The Persister interface for storing and restoring the cache\n * to/from a persisted location\n */\n persister: Persister\n /**\n * A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string\n */\n buster?: string\n}\n\n/**\n * Options for restoring a persisted `QueryClient` with {@link persistQueryClientRestore}.\n */\nexport interface PersistedQueryClientRestoreOptions extends PersistQueryClientRootOptions {\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 */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\n/**\n * Options for saving a `QueryClient` with {@link persistQueryClientSave}.\n */\nexport interface PersistedQueryClientSaveOptions extends PersistQueryClientRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\n/**\n * Options for {@link persistQueryClient}, which both restores and saves a `QueryClient`.\n */\nexport interface PersistQueryClientOptions\n extends\n PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClientRootOptions {}\n\nconst cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']\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 * @param eventType - The type of the emitted event.\n * @returns `true` if the event is `'added'`, `'removed'`, or `'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 * @param options - The `queryClient` to restore into, the `persister`, and the `maxAge`, `buster`,\n * and `hydrateOptions` that decide whether and how the persisted data is restored.\n * @returns A promise that resolves once the data is restored or removed. If restoring throws, it\n * attempts to remove the persisted data and then rejects with the restore error, or with the removal\n * error if the removal fails too.\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge =
|
|
1
|
+
{"version":3,"file":"persist.js","names":[],"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\n/**\n * A value, or a promise-like that resolves to it.\n */\nexport type Promisable<T> = T | PromiseLike<T>\n\n/**\n * Saves, restores, and removes a {@link PersistedClient} in a storage.\n */\nexport interface Persister {\n /**\n * Saves the persisted client to the storage.\n */\n persistClient: (persistClient: PersistedClient) => Promisable<void>\n /**\n * Reads the persisted client from the storage, or `undefined` if nothing was saved.\n */\n restoreClient: () => Promisable<PersistedClient | undefined>\n /**\n * Removes the persisted client from the storage.\n */\n removeClient: () => Promisable<void>\n}\n\n/**\n * The dehydrated state of a `QueryClient` as it is persisted, with the time it was saved and its\n * `buster`.\n */\nexport interface PersistedClient {\n /**\n * When the client was saved, in milliseconds since the epoch. Compared with `maxAge` on restore.\n */\n timestamp: number\n /**\n * The `buster` the client was saved with. A persisted client with a different `buster` is\n * discarded.\n */\n buster: string\n /**\n * The dehydrated cache of the `QueryClient`.\n */\n clientState: DehydratedState\n}\n\n/**\n * The options shared by restoring and saving a persisted `QueryClient`.\n */\nexport interface PersistQueryClientRootOptions {\n /** The QueryClient to persist */\n queryClient: QueryClient\n /**\n * The Persister interface for storing and restoring the cache\n * to/from a persisted location\n */\n persister: Persister\n /**\n * A unique string that can be used to forcefully\n * invalidate existing caches if they do not share the same buster string\n */\n buster?: string\n}\n\n/**\n * Options for restoring a persisted `QueryClient` with {@link persistQueryClientRestore}.\n */\nexport interface PersistedQueryClientRestoreOptions extends PersistQueryClientRootOptions {\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 */\n maxAge?: number\n /** The options passed to the hydrate function */\n hydrateOptions?: HydrateOptions\n}\n\n/**\n * Options for saving a `QueryClient` with {@link persistQueryClientSave}.\n */\nexport interface PersistedQueryClientSaveOptions extends PersistQueryClientRootOptions {\n /** The options passed to the dehydrate function */\n dehydrateOptions?: DehydrateOptions\n}\n\n/**\n * Options for {@link persistQueryClient}, which both restores and saves a `QueryClient`.\n */\nexport interface PersistQueryClientOptions\n extends\n PersistedQueryClientRestoreOptions,\n PersistedQueryClientSaveOptions,\n PersistQueryClientRootOptions {}\n\nconst cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']\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 * @param eventType - The type of the emitted event.\n * @returns `true` if the event is `'added'`, `'removed'`, or `'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 * @param options - The `queryClient` to restore into, the `persister`, and the `maxAge`, `buster`,\n * and `hydrateOptions` that decide whether and how the persisted data is restored.\n * @returns A promise that resolves once the data is restored or removed. If restoring throws, it\n * attempts to remove the persisted data and then rejects with the restore error, or with the removal\n * error if the removal fails too.\n */\nexport async function persistQueryClientRestore({\n queryClient,\n persister,\n maxAge = 24 * 60 * 60 * 1000,\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 * @param options - The `queryClient` to persist, the `persister`, the `buster`, and the\n * `dehydrateOptions`.\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 * @param props - The `queryClient` to monitor, the `persister`, the `buster`, and the\n * `dehydrateOptions` used for each save.\n * @returns an unsubscribe function (to discontinue monitoring)\n */\nexport function persistQueryClientSubscribe(\n props: PersistedQueryClientSaveOptions,\n) {\n const save = () => {\n persistQueryClientSave(props).catch((err) => {\n if (process.env.NODE_ENV !== 'production') {\n console.error(err)\n console.warn(\n 'Encountered an error attempting to persist client cache to persisted location.',\n )\n }\n })\n }\n\n const unsubscribeQueryCache = props.queryClient\n .getQueryCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n save()\n }\n })\n\n const unsubscribeMutationCache = props.queryClient\n .getMutationCache()\n .subscribe((event) => {\n if (isCacheEventType(event.type)) {\n save()\n }\n })\n\n return () => {\n unsubscribeQueryCache()\n unsubscribeMutationCache()\n }\n}\n\n/**\n * Restores persisted data to QueryCache and persists further changes.\n * @param props - The options for both restoring and saving.\n * @returns A tuple of a function that stops persisting, and a promise that resolves once the\n * restore is done.\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":";;AAqGA,MAAM,kBAA0C;CAAC;CAAS;CAAW;AAAS;;;;;;;AAQ9E,SAAS,iBAAiB,WAA4B;CACpD,OAAO,gBAAgB,SAAS,S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;;;;;AAQA,SAAgB,mBACd,OAC6B;CAC7B,IAAI,kBAAkB;CACtB,IAAI;CACJ,MAAM,oBAAoB;EACxB,kBAAkB;EAClB,kCAAA,QAAA,kCAAA,KAAA,KAAA,8BAAgC;CAClC;CAUA,OAAO,CAAC,aAPe,0BAA0B,KAAK,CAAC,CAAC,WAAW;EACjE,IAAI,CAAC,iBAEH,gCAAgC,4BAA4B,KAAK;CAErE,CAEkC,CAAC;AACrC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
|
|
2
|
+
// src/retryStrategies.ts
|
|
3
3
|
/**
|
|
4
4
|
* A {@link PersistRetryer} that drops the query with the oldest `dataUpdatedAt` and tries again, until
|
|
5
5
|
* no queries are left.
|
|
@@ -23,7 +23,6 @@ const removeOldestQuery = ({ persistedClient }) => {
|
|
|
23
23
|
return client;
|
|
24
24
|
}
|
|
25
25
|
};
|
|
26
|
-
//#endregion
|
|
27
26
|
exports.removeOldestQuery = removeOldestQuery;
|
|
28
27
|
|
|
29
28
|
//# sourceMappingURL=retryStrategies.cjs.map
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { PersistedClient } from "./persist.cjs";
|
|
2
|
-
//#region src/retryStrategies.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* Called when saving the persisted client fails. Returns a smaller client to try saving again, or
|
|
5
4
|
* `undefined` to give up.
|
|
@@ -16,5 +15,4 @@ export type PersistRetryer = (props: {
|
|
|
16
15
|
* @returns A copy of the client without its oldest query, or `undefined` if it has no queries.
|
|
17
16
|
*/
|
|
18
17
|
export declare const removeOldestQuery: PersistRetryer;
|
|
19
|
-
//#endregion
|
|
20
18
|
//# sourceMappingURL=retryStrategies.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retryStrategies.d.cts","names":[],"sources":["../../src/retryStrategies.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"retryStrategies.d.cts","names":[],"sources":["../../src/retryStrategies.ts"],"mappings":";;;;;YAMY,kBAAkB;EAC5B,iBAAiB;EACjB,OAAO;EACP;MACI;;;;;;;qBAQO,mBAAmB"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { PersistedClient } from "./persist.js";
|
|
2
|
-
//#region src/retryStrategies.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* Called when saving the persisted client fails. Returns a smaller client to try saving again, or
|
|
5
4
|
* `undefined` to give up.
|
|
@@ -16,5 +15,4 @@ export type PersistRetryer = (props: {
|
|
|
16
15
|
* @returns A copy of the client without its oldest query, or `undefined` if it has no queries.
|
|
17
16
|
*/
|
|
18
17
|
export declare const removeOldestQuery: PersistRetryer;
|
|
19
|
-
//#endregion
|
|
20
18
|
//# sourceMappingURL=retryStrategies.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retryStrategies.d.ts","names":[],"sources":["../../src/retryStrategies.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"retryStrategies.d.ts","names":[],"sources":["../../src/retryStrategies.ts"],"mappings":";;;;;YAMY,kBAAkB;EAC5B,iBAAiB;EACjB,OAAO;EACP;MACI;;;;;;;qBAQO,mBAAmB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/retryStrategies.ts
|
|
2
2
|
/**
|
|
3
3
|
* A {@link PersistRetryer} that drops the query with the oldest `dataUpdatedAt` and tries again, until
|
|
4
4
|
* no queries are left.
|
|
@@ -22,7 +22,6 @@ const removeOldestQuery = ({ persistedClient }) => {
|
|
|
22
22
|
return client;
|
|
23
23
|
}
|
|
24
24
|
};
|
|
25
|
-
//#endregion
|
|
26
25
|
export { removeOldestQuery };
|
|
27
26
|
|
|
28
27
|
//# sourceMappingURL=retryStrategies.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
let _tanstack_query_core = require("@tanstack/query-core");
|
|
3
|
-
|
|
3
|
+
// src/createPersister.ts
|
|
4
4
|
const PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
5
5
|
/**
|
|
6
6
|
* Warning: experimental feature.
|
|
@@ -21,7 +21,18 @@ const PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
|
21
21
|
* @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
|
|
22
22
|
* restore, remove, and garbage collect persisted queries manually.
|
|
23
23
|
*/
|
|
24
|
-
function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e5, serialize = JSON.stringify, deserialize = JSON.parse, prefix = PERSISTER_KEY_PREFIX, refetchOnRestore = true, filters }) {
|
|
24
|
+
function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e5, serialize = JSON.stringify, deserialize = JSON.parse, prefix = PERSISTER_KEY_PREFIX, refetchOnRestore = true, filters: persistFilters }) {
|
|
25
|
+
/**
|
|
26
|
+
* Checks the fields used to filter, expire, and restore a deserialized query.
|
|
27
|
+
* @param value - The deserialized value to check.
|
|
28
|
+
* @returns `true` if the value can be processed as a persisted query.
|
|
29
|
+
*/
|
|
30
|
+
function isValidPersistedQuery(value) {
|
|
31
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
32
|
+
const persistedQuery = value;
|
|
33
|
+
const state = persistedQuery.state;
|
|
34
|
+
return typeof persistedQuery.queryHash === "string" && Array.isArray(persistedQuery.queryKey) && typeof state === "object" && state !== null && !Array.isArray(state) && Number.isFinite(state.dataUpdatedAt);
|
|
35
|
+
}
|
|
25
36
|
/**
|
|
26
37
|
* Checks whether a persisted query should be discarded.
|
|
27
38
|
* @param persistedQuery - The persisted query to check.
|
|
@@ -54,6 +65,7 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
54
65
|
let persistedQuery;
|
|
55
66
|
try {
|
|
56
67
|
persistedQuery = await deserialize(storedData);
|
|
68
|
+
if (!isValidPersistedQuery(persistedQuery)) throw new Error("Invalid persisted query");
|
|
57
69
|
} catch {
|
|
58
70
|
await storage.removeItem(storageKey);
|
|
59
71
|
return;
|
|
@@ -111,7 +123,7 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
111
123
|
* @returns A promise that resolves with the restored or fetched data.
|
|
112
124
|
*/
|
|
113
125
|
async function persisterFn(queryFn, ctx, query) {
|
|
114
|
-
const matchesFilter =
|
|
126
|
+
const matchesFilter = persistFilters ? (0, _tanstack_query_core.matchQuery)(persistFilters, query) : true;
|
|
115
127
|
if (matchesFilter && query.state.data === void 0 && storage != null) {
|
|
116
128
|
const restoredData = await retrieveQuery(query.queryHash, (persistedQuery) => {
|
|
117
129
|
query.setState({
|
|
@@ -141,6 +153,7 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
141
153
|
let persistedQuery;
|
|
142
154
|
try {
|
|
143
155
|
persistedQuery = await deserialize(value);
|
|
156
|
+
if (!isValidPersistedQuery(persistedQuery)) throw new Error("Invalid persisted query");
|
|
144
157
|
} catch {
|
|
145
158
|
await storage.removeItem(key);
|
|
146
159
|
continue;
|
|
@@ -166,6 +179,7 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
166
179
|
let persistedQuery;
|
|
167
180
|
try {
|
|
168
181
|
persistedQuery = await deserialize(value);
|
|
182
|
+
if (!isValidPersistedQuery(persistedQuery)) throw new Error("Invalid persisted query");
|
|
169
183
|
} catch {
|
|
170
184
|
await storage.removeItem(key);
|
|
171
185
|
continue;
|
|
@@ -203,6 +217,7 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
203
217
|
let persistedQuery;
|
|
204
218
|
try {
|
|
205
219
|
persistedQuery = await deserialize(value);
|
|
220
|
+
if (!isValidPersistedQuery(persistedQuery)) throw new Error("Invalid persisted query");
|
|
206
221
|
} catch {
|
|
207
222
|
await storage.removeItem(key);
|
|
208
223
|
continue;
|
|
@@ -224,7 +239,6 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
224
239
|
removeQueries
|
|
225
240
|
};
|
|
226
241
|
}
|
|
227
|
-
//#endregion
|
|
228
242
|
exports.PERSISTER_KEY_PREFIX = PERSISTER_KEY_PREFIX;
|
|
229
243
|
exports.experimental_createQueryPersister = experimental_createQueryPersister;
|
|
230
244
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPersister.cjs","names":["matchQuery","hashKey","partialMatchKey"],"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\n/**\n * A single query as stored by {@link experimental_createQueryPersister}.\n */\nexport interface PersistedQuery {\n /**\n * The `buster` the query was saved with. Entries with a different `buster` are discarded.\n */\n buster: string\n /**\n * The hash of the query.\n */\n queryHash: string\n /**\n * The key of the query.\n */\n queryKey: QueryKey\n /**\n * The state of the query, including its data and when it was last updated.\n */\n state: QueryState\n}\n\n/**\n * A value, or a promise that resolves to it.\n */\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous\n * or return promises.\n */\nexport interface AsyncStorage<TStorageValue = string> {\n /**\n * Reads the value stored under `key`, or `null`/`undefined` if there is none.\n */\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n /**\n * Stores `value` under `key`.\n */\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n /**\n * Removes the value stored under `key`.\n */\n removeItem: (key: string) => MaybePromise<void>\n /**\n * Returns all stored key-value pairs. Required for removing expired entries in bulk.\n */\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\n/**\n * Options for {@link experimental_createQueryPersister}.\n */\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /**\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 * @defaultValue 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 * @param options - The storage to persist to, and the options for serializing, expiring, and\n * filtering persisted queries.\n * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,\n * restore, remove, and garbage collect persisted queries manually.\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 /**\n * Checks whether a persisted query should be discarded.\n * @param persistedQuery - The persisted query to check.\n * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different\n * `buster`.\n */\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 /**\n * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are\n * removed instead.\n * @param queryHash - The hash of the query to read.\n * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.\n * @returns A promise that resolves with the persisted data, or `undefined` if nothing was\n * restored.\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 != null) {\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 /**\n * Persists the query with the given key, if it exists in the client's cache.\n * @param queryKey - The key of the query to persist.\n * @param queryClient - The client whose cache holds the query.\n * @returns A promise that resolves once the query is persisted.\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 /**\n * Writes a query's state, key, hash, and `buster` to storage.\n * @param query - The query to persist.\n * @returns A promise that resolves once the entry is serialized and written.\n */\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n await 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 /**\n * The `persister` of a query: restores its data from storage if the query has none yet, otherwise\n * runs `queryFn` and persists the result.\n * @param queryFn - The query's own query function.\n * @param ctx - The context passed to `queryFn`.\n * @param query - The query being fetched.\n * @returns A promise that resolves with the restored or fetched data.\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 /**\n * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement\n * `entries`.\n * @returns A promise that resolves once every entry is checked.\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 /**\n * Restores every persisted query matching `filters` into the client's cache with\n * `queryClient.setQueryData`. Requires the storage to implement `entries`.\n * @param queryClient - The client to restore the queries into.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * restored.\n * @returns A promise that resolves once every entry is checked.\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 /**\n * Removes every persisted query matching `filters` from storage. Requires the storage to implement\n * `entries`.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * removed.\n * @returns A promise that resolves once every entry is checked.\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":";;;AAmHA,MAAa,uBAAuB;;;;;;;;;;;;;;;;;;;;AAqBpC,SAAgB,kCAA0D,EACxE,SACA,SAAS,IACT,SAAS,OACT,YAAY,KAAK,WAGjB,cAAc,KAAK,OAGnB,SAAS,sBACT,mBAAmB,MACnB,WACyC;;;;;;;CAOzC,SAAS,kBAAkB,gBAAgC;EACzD,IAAI,eAAe,MAAM,eAAe;GAEtC,MAAM,UADW,KAAK,IAAI,IAAI,eAAe,MAAM,gBACxB;GAC3B,MAAM,SAAS,eAAe,WAAW;GAEzC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EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"createPersister.cjs","names":["matchQuery","hashKey","partialMatchKey"],"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\n/**\n * A single query as stored by {@link experimental_createQueryPersister}.\n */\nexport interface PersistedQuery {\n /**\n * The `buster` the query was saved with. Entries with a different `buster` are discarded.\n */\n buster: string\n /**\n * The hash of the query.\n */\n queryHash: string\n /**\n * The key of the query.\n */\n queryKey: QueryKey\n /**\n * The state of the query, including its data and when it was last updated.\n */\n state: QueryState\n}\n\n/**\n * A value, or a promise that resolves to it.\n */\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous\n * or return promises.\n */\nexport interface AsyncStorage<TStorageValue = string> {\n /**\n * Reads the value stored under `key`, or `null`/`undefined` if there is none.\n */\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n /**\n * Stores `value` under `key`.\n */\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n /**\n * Removes the value stored under `key`.\n */\n removeItem: (key: string) => MaybePromise<void>\n /**\n * Returns all stored key-value pairs. Required for removing expired entries in bulk.\n */\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\n/**\n * Options for {@link experimental_createQueryPersister}.\n */\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /**\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 * @defaultValue 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 * @param options - The storage to persist to, and the options for serializing, expiring, and\n * filtering persisted queries.\n * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,\n * restore, remove, and garbage collect persisted queries manually.\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 24 * 60 * 60 * 1000,\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: persistFilters,\n}: StoragePersisterOptions<TStorageValue>) {\n /**\n * Checks the fields used to filter, expire, and restore a deserialized query.\n * @param value - The deserialized value to check.\n * @returns `true` if the value can be processed as a persisted query.\n */\n function isValidPersistedQuery(value: unknown) {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false\n }\n\n const persistedQuery = value as Partial<Omit<PersistedQuery, 'state'>> & {\n state?: Partial<QueryState> | null\n }\n const state = persistedQuery.state\n\n return (\n typeof persistedQuery.queryHash === 'string' &&\n Array.isArray(persistedQuery.queryKey) &&\n typeof state === 'object' &&\n state !== null &&\n !Array.isArray(state) &&\n Number.isFinite(state.dataUpdatedAt)\n )\n }\n\n /**\n * Checks whether a persisted query should be discarded.\n * @param persistedQuery - The persisted query to check.\n * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different\n * `buster`.\n */\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 /**\n * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are\n * removed instead.\n * @param queryHash - The hash of the query to read.\n * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.\n * @returns A promise that resolves with the persisted data, or `undefined` if nothing was\n * restored.\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 != null) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(storedData)\n if (!isValidPersistedQuery(persistedQuery)) {\n throw new Error('Invalid persisted query')\n }\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 /**\n * Persists the query with the given key, if it exists in the client's cache.\n * @param queryKey - The key of the query to persist.\n * @param queryClient - The client whose cache holds the query.\n * @returns A promise that resolves once the query is persisted.\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 /**\n * Writes a query's state, key, hash, and `buster` to storage.\n * @param query - The query to persist.\n * @returns A promise that resolves once the entry is serialized and written.\n */\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n await 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 /**\n * The `persister` of a query: restores its data from storage if the query has none yet, otherwise\n * runs `queryFn` and persists the result.\n * @param queryFn - The query's own query function.\n * @param ctx - The context passed to `queryFn`.\n * @param query - The query being fetched.\n * @returns A promise that resolves with the restored or fetched data.\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 = persistFilters\n ? matchQuery(persistFilters, query)\n : 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 /**\n * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement\n * `entries`.\n * @returns A promise that resolves once every entry is checked.\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 if (!isValidPersistedQuery(persistedQuery)) {\n throw new Error('Invalid persisted query')\n }\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 /**\n * Restores every persisted query matching `filters` into the client's cache with\n * `queryClient.setQueryData`. Requires the storage to implement `entries`.\n * @param queryClient - The client to restore the queries into.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * restored.\n * @returns A promise that resolves once every entry is checked.\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 if (!isValidPersistedQuery(persistedQuery)) {\n throw new Error('Invalid persisted query')\n }\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 /**\n * Removes every persisted query matching `filters` from storage. Requires the storage to implement\n * `entries`.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * removed.\n * @returns A promise that resolves once every entry is checked.\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 if (!isValidPersistedQuery(persistedQuery)) {\n throw new Error('Invalid persisted query')\n }\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 persistQu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C,qBAAAA,gBAAAA,CAAgB,eAAe,UAAU,QAAQ,GAC3D;IAEJ;IAEA,YAAY,aACV,eAAe,UACf,eAAe,MAAM,MACrB,EACE,WAAW,eAAe,MAAM,cAClC,CACF;GACF;EAEJ,OAAO,IAAI,QAAQ,IAAI,aAAa,eAClC,MAAM,IAAI,MACR,wJACF;CAEJ;;;;;;;;CASA,eAAe,cACb,UAAoD,CAAC,GACtC;EACf,MAAM,EAAE,OAAO,aAAa;EAE5B,IAAI,SAAS,SAAS;GACpB,MAAM,UAAU,MAAM,QAAQ,QAAQ;GACtC,MAAM,mBAAmB,GAAG,OAAO;GACnC,KAAK,MAAM,CAAC,KAAK,UAAU,SACzB,IAAI,IAAI,WAAW,gBAAgB,GAAG;IACpC,IAAI,CAAC,UAAU;KACb,MAAM,QAAQ,WAAW,GAAG;KAC5B;IACF;IAEA,IAAI;IACJ,IAAI;KACF,iBAAiB,MAAM,YAAY,KAAK;KACxC,IAAI,CAAC,sBAAsB,cAAc,GACvC,MAAM,IAAI,MAAM,yBAAyB;IAE7C,QAAQ;KACN,MAAM,QAAQ,WAAW,GAAG;KAC5B;IACF;IAEA,IAAI,OACE;SAAA,eAAe,eAAA,GAAcD,qBAAAA,QAAAA,CAAQ,QAAQ,GAC/C;IAAA,OAEG,IAAI,EAAA,GAACC,qBAAAA,gBAAAA,CAAgB,eAAe,UAAU,QAAQ,GAC3D;IAGF,MAAM,QAAQ,WAAW,GAAG;GAC9B;EAEJ,OAAO,IAAI,QAAQ,IAAI,aAAa,eAClC,MAAM,IAAI,MACR,gJACF;CAEJ;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Query, QueryClient, QueryFilters, QueryFunctionContext, QueryKey, QueryState } from "@tanstack/query-core";
|
|
2
|
-
//#region src/createPersister.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* A single query as stored by {@link experimental_createQueryPersister}.
|
|
5
4
|
*/
|
|
@@ -116,7 +115,7 @@ export declare const PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
|
116
115
|
* @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
|
|
117
116
|
* restore, remove, and garbage collect persisted queries manually.
|
|
118
117
|
*/
|
|
119
|
-
export declare function experimental_createQueryPersister<TStorageValue = string>({ storage, buster, maxAge, serialize, deserialize, prefix, refetchOnRestore, filters }: StoragePersisterOptions<TStorageValue>): {
|
|
118
|
+
export declare function experimental_createQueryPersister<TStorageValue = string>({ storage, buster, maxAge, serialize, deserialize, prefix, refetchOnRestore, filters: persistFilters }: StoragePersisterOptions<TStorageValue>): {
|
|
120
119
|
persisterFn: <T, TQueryKey extends QueryKey>(queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>, ctx: QueryFunctionContext<TQueryKey>, query: Query) => Promise<T>;
|
|
121
120
|
persistQuery: (query: Query) => Promise<void>;
|
|
122
121
|
persistQueryByKey: (queryKey: QueryKey, queryClient: QueryClient) => Promise<void>;
|
|
@@ -125,5 +124,4 @@ export declare function experimental_createQueryPersister<TStorageValue = string
|
|
|
125
124
|
restoreQueries: (queryClient: QueryClient, filters?: Pick<QueryFilters, "queryKey" | "exact">) => Promise<void>;
|
|
126
125
|
removeQueries: (filters?: Pick<QueryFilters, "queryKey" | "exact">) => Promise<void>;
|
|
127
126
|
};
|
|
128
|
-
//#endregion
|
|
129
127
|
//# sourceMappingURL=createPersister.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPersister.d.cts","names":[],"sources":["../../src/createPersister.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"createPersister.d.cts","names":[],"sources":["../../src/createPersister.ts"],"mappings":";;;;iBAkBiB;;;;EAIf;;;;EAIA;;;;EAIA,UAAU;;;;EAIV,OAAO;;;;;YAMG,aAAa,KAAK,IAAI,QAAQ;;;;;iBAMzB,aAAa;;;;EAI5B,UAAU,gBAAgB,aAAa;;;;EAIvC,UAAU,aAAa,OAAO,kBAAkB;;;;EAIhD,aAAa,gBAAgB;;;;EAI7B,gBAAgB,aAAa,OAAO,aAAa,OAAO;;;;;iBAMzC,wBAAwB;;;;;EAKvC,SAAS,aAAa;;;;;EAKtB,aAAa,gBAAgB,mBAAmB,aAAa;;;;;EAK7D,eAAe,cAAc,kBAAkB,aAAa;;;;;EAK5D;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA;;;;EAIA,UAAU;;qBAGC;;;;;;;;;;;;;;;;;;;;wBAqBG,kCAAkC,0BAChD,SACA,QACA,QACA,WAGA,aAGA,QACA,kBACA,SAAS,kBACR,wBAAwB;EA4JE,cAAA,GAAG,kBAAkB,UAAQ,UAC5C,SAAS,qBAAqB,eAAe,IAAI,QAAQ,IAAE,KAChE,qBAAqB,YAAU,OAC7B,UAAK,QAAA;EA1BqB,eAAA,OAAA,UAAK;EAvB5B,oBAAA,UAAA,UAAQ,aACL,gBAAW;EAvDG,gBAAA,GAAC,mBACX,yBACQ,gBAAgB,4BAAuB,QAAA;;EA2LnD,iBAAA,aAAA,aAAW,UACf,KAAK,wCACb;EAyDQ,gBAAA,UAAA,KAAK,wCACb"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Query, QueryClient, QueryFilters, QueryFunctionContext, QueryKey, QueryState } from "@tanstack/query-core";
|
|
2
|
-
//#region src/createPersister.d.ts
|
|
3
2
|
/**
|
|
4
3
|
* A single query as stored by {@link experimental_createQueryPersister}.
|
|
5
4
|
*/
|
|
@@ -116,7 +115,7 @@ export declare const PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
|
116
115
|
* @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
|
|
117
116
|
* restore, remove, and garbage collect persisted queries manually.
|
|
118
117
|
*/
|
|
119
|
-
export declare function experimental_createQueryPersister<TStorageValue = string>({ storage, buster, maxAge, serialize, deserialize, prefix, refetchOnRestore, filters }: StoragePersisterOptions<TStorageValue>): {
|
|
118
|
+
export declare function experimental_createQueryPersister<TStorageValue = string>({ storage, buster, maxAge, serialize, deserialize, prefix, refetchOnRestore, filters: persistFilters }: StoragePersisterOptions<TStorageValue>): {
|
|
120
119
|
persisterFn: <T, TQueryKey extends QueryKey>(queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>, ctx: QueryFunctionContext<TQueryKey>, query: Query) => Promise<T>;
|
|
121
120
|
persistQuery: (query: Query) => Promise<void>;
|
|
122
121
|
persistQueryByKey: (queryKey: QueryKey, queryClient: QueryClient) => Promise<void>;
|
|
@@ -125,5 +124,4 @@ export declare function experimental_createQueryPersister<TStorageValue = string
|
|
|
125
124
|
restoreQueries: (queryClient: QueryClient, filters?: Pick<QueryFilters, "queryKey" | "exact">) => Promise<void>;
|
|
126
125
|
removeQueries: (filters?: Pick<QueryFilters, "queryKey" | "exact">) => Promise<void>;
|
|
127
126
|
};
|
|
128
|
-
//#endregion
|
|
129
127
|
//# sourceMappingURL=createPersister.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPersister.d.ts","names":[],"sources":["../../src/createPersister.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"createPersister.d.ts","names":[],"sources":["../../src/createPersister.ts"],"mappings":";;;;iBAkBiB;;;;EAIf;;;;EAIA;;;;EAIA,UAAU;;;;EAIV,OAAO;;;;;YAMG,aAAa,KAAK,IAAI,QAAQ;;;;;iBAMzB,aAAa;;;;EAI5B,UAAU,gBAAgB,aAAa;;;;EAIvC,UAAU,aAAa,OAAO,kBAAkB;;;;EAIhD,aAAa,gBAAgB;;;;EAI7B,gBAAgB,aAAa,OAAO,aAAa,OAAO;;;;;iBAMzC,wBAAwB;;;;;EAKvC,SAAS,aAAa;;;;;EAKtB,aAAa,gBAAgB,mBAAmB,aAAa;;;;;EAK7D,eAAe,cAAc,kBAAkB,aAAa;;;;;EAK5D;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA;;;;EAIA,UAAU;;qBAGC;;;;;;;;;;;;;;;;;;;;wBAqBG,kCAAkC,0BAChD,SACA,QACA,QACA,WAGA,aAGA,QACA,kBACA,SAAS,kBACR,wBAAwB;EA4JE,cAAA,GAAG,kBAAkB,UAAQ,UAC5C,SAAS,qBAAqB,eAAe,IAAI,QAAQ,IAAE,KAChE,qBAAqB,YAAU,OAC7B,UAAK,QAAA;EA1BqB,eAAA,OAAA,UAAK;EAvB5B,oBAAA,UAAA,UAAQ,aACL,gBAAW;EAvDG,gBAAA,GAAC,mBACX,yBACQ,gBAAgB,4BAAuB,QAAA;;EA2LnD,iBAAA,aAAA,aAAW,UACf,KAAK,wCACb;EAyDQ,gBAAA,UAAA,KAAK,wCACb"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { hashKey, matchQuery, notifyManager, partialMatchKey } from "@tanstack/query-core";
|
|
2
|
-
|
|
2
|
+
// src/createPersister.ts
|
|
3
3
|
const PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
4
4
|
/**
|
|
5
5
|
* Warning: experimental feature.
|
|
@@ -20,7 +20,18 @@ const PERSISTER_KEY_PREFIX = "tanstack-query";
|
|
|
20
20
|
* @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
|
|
21
21
|
* restore, remove, and garbage collect persisted queries manually.
|
|
22
22
|
*/
|
|
23
|
-
function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e5, serialize = JSON.stringify, deserialize = JSON.parse, prefix = PERSISTER_KEY_PREFIX, refetchOnRestore = true, filters }) {
|
|
23
|
+
function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e5, serialize = JSON.stringify, deserialize = JSON.parse, prefix = PERSISTER_KEY_PREFIX, refetchOnRestore = true, filters: persistFilters }) {
|
|
24
|
+
/**
|
|
25
|
+
* Checks the fields used to filter, expire, and restore a deserialized query.
|
|
26
|
+
* @param value - The deserialized value to check.
|
|
27
|
+
* @returns `true` if the value can be processed as a persisted query.
|
|
28
|
+
*/
|
|
29
|
+
function isValidPersistedQuery(value) {
|
|
30
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
31
|
+
const persistedQuery = value;
|
|
32
|
+
const state = persistedQuery.state;
|
|
33
|
+
return typeof persistedQuery.queryHash === "string" && Array.isArray(persistedQuery.queryKey) && typeof state === "object" && state !== null && !Array.isArray(state) && Number.isFinite(state.dataUpdatedAt);
|
|
34
|
+
}
|
|
24
35
|
/**
|
|
25
36
|
* Checks whether a persisted query should be discarded.
|
|
26
37
|
* @param persistedQuery - The persisted query to check.
|
|
@@ -53,6 +64,7 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
53
64
|
let persistedQuery;
|
|
54
65
|
try {
|
|
55
66
|
persistedQuery = await deserialize(storedData);
|
|
67
|
+
if (!isValidPersistedQuery(persistedQuery)) throw new Error("Invalid persisted query");
|
|
56
68
|
} catch {
|
|
57
69
|
await storage.removeItem(storageKey);
|
|
58
70
|
return;
|
|
@@ -110,7 +122,7 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
110
122
|
* @returns A promise that resolves with the restored or fetched data.
|
|
111
123
|
*/
|
|
112
124
|
async function persisterFn(queryFn, ctx, query) {
|
|
113
|
-
const matchesFilter =
|
|
125
|
+
const matchesFilter = persistFilters ? matchQuery(persistFilters, query) : true;
|
|
114
126
|
if (matchesFilter && query.state.data === void 0 && storage != null) {
|
|
115
127
|
const restoredData = await retrieveQuery(query.queryHash, (persistedQuery) => {
|
|
116
128
|
query.setState({
|
|
@@ -140,6 +152,7 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
140
152
|
let persistedQuery;
|
|
141
153
|
try {
|
|
142
154
|
persistedQuery = await deserialize(value);
|
|
155
|
+
if (!isValidPersistedQuery(persistedQuery)) throw new Error("Invalid persisted query");
|
|
143
156
|
} catch {
|
|
144
157
|
await storage.removeItem(key);
|
|
145
158
|
continue;
|
|
@@ -165,6 +178,7 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
165
178
|
let persistedQuery;
|
|
166
179
|
try {
|
|
167
180
|
persistedQuery = await deserialize(value);
|
|
181
|
+
if (!isValidPersistedQuery(persistedQuery)) throw new Error("Invalid persisted query");
|
|
168
182
|
} catch {
|
|
169
183
|
await storage.removeItem(key);
|
|
170
184
|
continue;
|
|
@@ -202,6 +216,7 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
202
216
|
let persistedQuery;
|
|
203
217
|
try {
|
|
204
218
|
persistedQuery = await deserialize(value);
|
|
219
|
+
if (!isValidPersistedQuery(persistedQuery)) throw new Error("Invalid persisted query");
|
|
205
220
|
} catch {
|
|
206
221
|
await storage.removeItem(key);
|
|
207
222
|
continue;
|
|
@@ -223,7 +238,6 @@ function experimental_createQueryPersister({ storage, buster = "", maxAge = 864e
|
|
|
223
238
|
removeQueries
|
|
224
239
|
};
|
|
225
240
|
}
|
|
226
|
-
//#endregion
|
|
227
241
|
export { PERSISTER_KEY_PREFIX, experimental_createQueryPersister };
|
|
228
242
|
|
|
229
243
|
//# sourceMappingURL=createPersister.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPersister.js","names":[],"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\n/**\n * A single query as stored by {@link experimental_createQueryPersister}.\n */\nexport interface PersistedQuery {\n /**\n * The `buster` the query was saved with. Entries with a different `buster` are discarded.\n */\n buster: string\n /**\n * The hash of the query.\n */\n queryHash: string\n /**\n * The key of the query.\n */\n queryKey: QueryKey\n /**\n * The state of the query, including its data and when it was last updated.\n */\n state: QueryState\n}\n\n/**\n * A value, or a promise that resolves to it.\n */\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous\n * or return promises.\n */\nexport interface AsyncStorage<TStorageValue = string> {\n /**\n * Reads the value stored under `key`, or `null`/`undefined` if there is none.\n */\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n /**\n * Stores `value` under `key`.\n */\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n /**\n * Removes the value stored under `key`.\n */\n removeItem: (key: string) => MaybePromise<void>\n /**\n * Returns all stored key-value pairs. Required for removing expired entries in bulk.\n */\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\n/**\n * Options for {@link experimental_createQueryPersister}.\n */\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /**\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 * @defaultValue 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 * @param options - The storage to persist to, and the options for serializing, expiring, and\n * filtering persisted queries.\n * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,\n * restore, remove, and garbage collect persisted queries manually.\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 /**\n * Checks whether a persisted query should be discarded.\n * @param persistedQuery - The persisted query to check.\n * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different\n * `buster`.\n */\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 /**\n * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are\n * removed instead.\n * @param queryHash - The hash of the query to read.\n * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.\n * @returns A promise that resolves with the persisted data, or `undefined` if nothing was\n * restored.\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 != null) {\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 /**\n * Persists the query with the given key, if it exists in the client's cache.\n * @param queryKey - The key of the query to persist.\n * @param queryClient - The client whose cache holds the query.\n * @returns A promise that resolves once the query is persisted.\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 /**\n * Writes a query's state, key, hash, and `buster` to storage.\n * @param query - The query to persist.\n * @returns A promise that resolves once the entry is serialized and written.\n */\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n await 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 /**\n * The `persister` of a query: restores its data from storage if the query has none yet, otherwise\n * runs `queryFn` and persists the result.\n * @param queryFn - The query's own query function.\n * @param ctx - The context passed to `queryFn`.\n * @param query - The query being fetched.\n * @returns A promise that resolves with the restored or fetched data.\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 /**\n * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement\n * `entries`.\n * @returns A promise that resolves once every entry is checked.\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 /**\n * Restores every persisted query matching `filters` into the client's cache with\n * `queryClient.setQueryData`. Requires the storage to implement `entries`.\n * @param queryClient - The client to restore the queries into.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * restored.\n * @returns A promise that resolves once every entry is checked.\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 /**\n * Removes every persisted query matching `filters` from storage. Requires the storage to implement\n * `entries`.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * removed.\n * @returns A promise that resolves once every entry is checked.\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":";;AAmHA,MAAa,uBAAuB;;;;;;;;;;;;;;;;;;;;AAqBpC,SAAgB,kCAA0D,EACxE,SACA,SAAS,IACT,SAAS,OACT,YAAY,KAAK,WAGjB,cAAc,KAAK,OAGnB,SAAS,sBACT,mBAAmB,MACnB,WACyC;;;;;;;CAOzC,SAAS,kBAAkB,gBAAgC;EACzD,IAAI,eAAe,MAAM,eAAe;GAEtC,MAAM,UADW,KAAK,IAAI,IAAI,eAAe,MAAM,gBACxB;GAC3B,MAAM,SAAS,eAAe,WAAW;GAEzC,IAAI,WAAW,QACb,OAAO;GAGT,OAAO;EACT;EAEA,OAAO;CACT;;;;;;;;;CAUA,eAAe,cACb,WACA,uBACA;EACA,IAAI,WAAW,MAAM;GACnB,MAAM,aAAa,GAAG,OAAO,GAAG;GAChC,IAAI;IACF,MAAM,aAAa,MAAM,QAAQ,QAAQ,UAAU;IACnD,IAAI,cAAc,MAAM;KACtB,IAAI;KACJ,IAAI;MACF,iBAAiB,MAAM,YAAY,UAAU;KAC/C,QAAQ;MACN,MAAM,QAAQ,WAAW,UAAU;MACnC;KACF;KAEA,IAAI,kBAAkB,cAAc,GAClC,MAAM,QAAQ,WAAW,UAAU;UAC9B;MACL,IAAI,uBAEF,cAAc,eACZ,sBAAsB,cAAc,CACtC;MAGF,OAAO,eAAe,MAAM;KAC9B;IACF;GACF,SAAS,KAAK;IACZ,IAAI,QAAQ,IAAI,aAAa,eAAe;KAC1C,QAAQ,MAAM,GAAG;KACjB,QAAQ,KACN,iFACF;IACF;IACA,MAAM,QAAQ,WAAW,UAAU;GACrC;EACF;CAGF;;;;;;;CAQA,eAAe,kBACb,UACA,aACA;EACA,IAAI,WAAW,MAAM;GACnB,MAAM,QAAQ,YAAY,cAAc,CAAC,CAAC,KAAK,EAAE,SAAS,CAAC;GAC3D,IAAI,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Y,KAAK;IAC1C,QAAQ;KACN,MAAM,QAAQ,WAAW,GAAG;KAC5B;IACF;IAEA,IAAI,OACE;SAAA,eAAe,cAAc,QAAQ,QAAQ,GAC/C;IAAA,OAEG,IAAI,CAAC,gBAAgB,eAAe,UAAU,QAAQ,GAC3D;IAGF,MAAM,QAAQ,WAAW,GAAG;GAC9B;EAEJ,OAAO,IAAI,QAAQ,IAAI,aAAa,eAClC,MAAM,IAAI,MACR,gJACF;CAEJ;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"createPersister.js","names":[],"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\n/**\n * A single query as stored by {@link experimental_createQueryPersister}.\n */\nexport interface PersistedQuery {\n /**\n * The `buster` the query was saved with. Entries with a different `buster` are discarded.\n */\n buster: string\n /**\n * The hash of the query.\n */\n queryHash: string\n /**\n * The key of the query.\n */\n queryKey: QueryKey\n /**\n * The state of the query, including its data and when it was last updated.\n */\n state: QueryState\n}\n\n/**\n * A value, or a promise that resolves to it.\n */\nexport type MaybePromise<T> = T | Promise<T>\n\n/**\n * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous\n * or return promises.\n */\nexport interface AsyncStorage<TStorageValue = string> {\n /**\n * Reads the value stored under `key`, or `null`/`undefined` if there is none.\n */\n getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>\n /**\n * Stores `value` under `key`.\n */\n setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>\n /**\n * Removes the value stored under `key`.\n */\n removeItem: (key: string) => MaybePromise<void>\n /**\n * Returns all stored key-value pairs. Required for removing expired entries in bulk.\n */\n entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>\n}\n\n/**\n * Options for {@link experimental_createQueryPersister}.\n */\nexport interface StoragePersisterOptions<TStorageValue = string> {\n /**\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 * @defaultValue 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 * @param options - The storage to persist to, and the options for serializing, expiring, and\n * filtering persisted queries.\n * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,\n * restore, remove, and garbage collect persisted queries manually.\n */\nexport function experimental_createQueryPersister<TStorageValue = string>({\n storage,\n buster = '',\n maxAge = 24 * 60 * 60 * 1000,\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: persistFilters,\n}: StoragePersisterOptions<TStorageValue>) {\n /**\n * Checks the fields used to filter, expire, and restore a deserialized query.\n * @param value - The deserialized value to check.\n * @returns `true` if the value can be processed as a persisted query.\n */\n function isValidPersistedQuery(value: unknown) {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false\n }\n\n const persistedQuery = value as Partial<Omit<PersistedQuery, 'state'>> & {\n state?: Partial<QueryState> | null\n }\n const state = persistedQuery.state\n\n return (\n typeof persistedQuery.queryHash === 'string' &&\n Array.isArray(persistedQuery.queryKey) &&\n typeof state === 'object' &&\n state !== null &&\n !Array.isArray(state) &&\n Number.isFinite(state.dataUpdatedAt)\n )\n }\n\n /**\n * Checks whether a persisted query should be discarded.\n * @param persistedQuery - The persisted query to check.\n * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different\n * `buster`.\n */\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 /**\n * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are\n * removed instead.\n * @param queryHash - The hash of the query to read.\n * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.\n * @returns A promise that resolves with the persisted data, or `undefined` if nothing was\n * restored.\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 != null) {\n let persistedQuery: PersistedQuery\n try {\n persistedQuery = await deserialize(storedData)\n if (!isValidPersistedQuery(persistedQuery)) {\n throw new Error('Invalid persisted query')\n }\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 /**\n * Persists the query with the given key, if it exists in the client's cache.\n * @param queryKey - The key of the query to persist.\n * @param queryClient - The client whose cache holds the query.\n * @returns A promise that resolves once the query is persisted.\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 /**\n * Writes a query's state, key, hash, and `buster` to storage.\n * @param query - The query to persist.\n * @returns A promise that resolves once the entry is serialized and written.\n */\n async function persistQuery(query: Query) {\n if (storage != null) {\n const storageKey = `${prefix}-${query.queryHash}`\n await 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 /**\n * The `persister` of a query: restores its data from storage if the query has none yet, otherwise\n * runs `queryFn` and persists the result.\n * @param queryFn - The query's own query function.\n * @param ctx - The context passed to `queryFn`.\n * @param query - The query being fetched.\n * @returns A promise that resolves with the restored or fetched data.\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 = persistFilters\n ? matchQuery(persistFilters, query)\n : 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 /**\n * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement\n * `entries`.\n * @returns A promise that resolves once every entry is checked.\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 if (!isValidPersistedQuery(persistedQuery)) {\n throw new Error('Invalid persisted query')\n }\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 /**\n * Restores every persisted query matching `filters` into the client's cache with\n * `queryClient.setQueryData`. Requires the storage to implement `entries`.\n * @param queryClient - The client to restore the queries into.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * restored.\n * @returns A promise that resolves once every entry is checked.\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 if (!isValidPersistedQuery(persistedQuery)) {\n throw new Error('Invalid persisted query')\n }\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 /**\n * Removes every persisted query matching `filters` from storage. Requires the storage to implement\n * `entries`.\n * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is\n * removed.\n * @returns A promise that resolves once every entry is checked.\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 if (!isValidPersistedQuery(persistedQuery)) {\n throw new Error('Invalid persisted query')\n }\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":";;AAmHA,MAAa,uBAAuB;;;;;;;;;;;;;;;;;;;;AAqBpC,SAAgB,kCAA0D,EACxE,SACA,SAAS,IACT,SAAS,OACT,YAAY,KAAK,WAGjB,cAAc,KAAK,OAGnB,SAAS,sBACT,mBAAmB,MACnB,SAAS,kBACgC;;;;;;CAMzC,SAAS,sBAAsB,OAAgB;EAC7C,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GACpE,OAAO;EAGT,MAAM,iBAAiB;EAGvB,MAAM,QAAQ,eAAe;EAE7B,OACE,OAAO,eAAe,cAAc,YACpC,MAAM,QAAQ,eAAe,QAAQ,KACrC,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,KAAK,KACpB,OAAO,SAAS,MAAM,aAAa;CAEvC;;;;;;;CAQA,SAAS,kBAAkB,gBAAgC;EACzD,IAAI,eAAe,MAAM,eAAe;GAEtC,MAAM,UADW,KAAK,IAAI,IAAI,eAAe,MAAM,gBACxB;GAC3B,MAAM,SAAS,eAAe,WAAW;GAEzC,IAAI,WAAW,QACb,OAAO;GAGT,OAAO;EACT;EAEA,OAAO;CACT;;;;;;;;;CAUA,eAAe,cACb,WACA,uBACA;EACA,IAAI,WAAW,MAAM;GACnB,MAAM,aAAa,GAAG,OAAO,GAAG;GAChC,IAAI;IACF,MAAM,aAAa,MAAM,QAAQ,QAAQ,UAAU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,9 +2,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
2
2
|
const require_createPersister = require("./createPersister.cjs");
|
|
3
3
|
const require_persist = require("./persist.cjs");
|
|
4
4
|
const require_retryStrategies = require("./retryStrategies.cjs");
|
|
5
|
-
|
|
5
|
+
// src/index.ts
|
|
6
6
|
/* istanbul ignore file */
|
|
7
|
-
//#endregion
|
|
8
7
|
exports.PERSISTER_KEY_PREFIX = require_createPersister.PERSISTER_KEY_PREFIX;
|
|
9
8
|
exports.experimental_createQueryPersister = require_createPersister.experimental_createQueryPersister;
|
|
10
9
|
exports.persistQueryClient = require_persist.persistQueryClient;
|
package/build/modern/index.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { PERSISTER_KEY_PREFIX, experimental_createQueryPersister } from "./createPersister.js";
|
|
2
2
|
import { persistQueryClient, persistQueryClientRestore, persistQueryClientSave, persistQueryClientSubscribe } from "./persist.js";
|
|
3
3
|
import { removeOldestQuery } from "./retryStrategies.js";
|
|
4
|
-
|
|
4
|
+
// src/index.ts
|
|
5
5
|
/* istanbul ignore file */
|
|
6
|
-
//#endregion
|
|
7
6
|
export { PERSISTER_KEY_PREFIX, experimental_createQueryPersister, persistQueryClient, persistQueryClientRestore, persistQueryClientSave, persistQueryClientSubscribe, removeOldestQuery };
|
|
8
7
|
|
|
9
8
|
//# sourceMappingURL=index.js.map
|
package/build/modern/persist.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
let _tanstack_query_core = require("@tanstack/query-core");
|
|
3
|
-
|
|
3
|
+
// src/persist.ts
|
|
4
4
|
const cacheEventTypes = [
|
|
5
5
|
"added",
|
|
6
6
|
"removed",
|
|
@@ -68,11 +68,19 @@ async function persistQueryClientSave({ queryClient, persister, buster = "", deh
|
|
|
68
68
|
* @returns an unsubscribe function (to discontinue monitoring)
|
|
69
69
|
*/
|
|
70
70
|
function persistQueryClientSubscribe(props) {
|
|
71
|
+
const save = () => {
|
|
72
|
+
persistQueryClientSave(props).catch((err) => {
|
|
73
|
+
if (process.env.NODE_ENV !== "production") {
|
|
74
|
+
console.error(err);
|
|
75
|
+
console.warn("Encountered an error attempting to persist client cache to persisted location.");
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
};
|
|
71
79
|
const unsubscribeQueryCache = props.queryClient.getQueryCache().subscribe((event) => {
|
|
72
|
-
if (isCacheEventType(event.type))
|
|
80
|
+
if (isCacheEventType(event.type)) save();
|
|
73
81
|
});
|
|
74
82
|
const unsubscribeMutationCache = props.queryClient.getMutationCache().subscribe((event) => {
|
|
75
|
-
if (isCacheEventType(event.type))
|
|
83
|
+
if (isCacheEventType(event.type)) save();
|
|
76
84
|
});
|
|
77
85
|
return () => {
|
|
78
86
|
unsubscribeQueryCache();
|
|
@@ -96,7 +104,6 @@ function persistQueryClient(props) {
|
|
|
96
104
|
if (!hasUnsubscribed) persistQueryClientUnsubscribe = persistQueryClientSubscribe(props);
|
|
97
105
|
})];
|
|
98
106
|
}
|
|
99
|
-
//#endregion
|
|
100
107
|
exports.persistQueryClient = persistQueryClient;
|
|
101
108
|
exports.persistQueryClientRestore = persistQueryClientRestore;
|
|
102
109
|
exports.persistQueryClientSave = persistQueryClientSave;
|