@tanstack/query-persist-client-core 5.104.1 → 5.104.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/build/legacy/createPersister.cjs +64 -7
  2. package/build/legacy/createPersister.cjs.map +1 -1
  3. package/build/legacy/createPersister.d.cts +50 -9
  4. package/build/legacy/createPersister.d.cts.map +1 -1
  5. package/build/legacy/createPersister.d.ts +50 -9
  6. package/build/legacy/createPersister.d.ts.map +1 -1
  7. package/build/legacy/createPersister.js +64 -7
  8. package/build/legacy/createPersister.js.map +1 -1
  9. package/build/legacy/persist.cjs +26 -12
  10. package/build/legacy/persist.cjs.map +1 -1
  11. package/build/legacy/persist.d.cts +73 -14
  12. package/build/legacy/persist.d.cts.map +1 -1
  13. package/build/legacy/persist.d.ts +73 -14
  14. package/build/legacy/persist.d.ts.map +1 -1
  15. package/build/legacy/persist.js +26 -12
  16. package/build/legacy/persist.js.map +1 -1
  17. package/build/legacy/retryStrategies.cjs +6 -0
  18. package/build/legacy/retryStrategies.cjs.map +1 -1
  19. package/build/legacy/retryStrategies.d.cts +10 -0
  20. package/build/legacy/retryStrategies.d.cts.map +1 -1
  21. package/build/legacy/retryStrategies.d.ts +10 -0
  22. package/build/legacy/retryStrategies.d.ts.map +1 -1
  23. package/build/legacy/retryStrategies.js +6 -0
  24. package/build/legacy/retryStrategies.js.map +1 -1
  25. package/build/modern/createPersister.cjs +64 -7
  26. package/build/modern/createPersister.cjs.map +1 -1
  27. package/build/modern/createPersister.d.cts +50 -9
  28. package/build/modern/createPersister.d.cts.map +1 -1
  29. package/build/modern/createPersister.d.ts +50 -9
  30. package/build/modern/createPersister.d.ts.map +1 -1
  31. package/build/modern/createPersister.js +64 -7
  32. package/build/modern/createPersister.js.map +1 -1
  33. package/build/modern/persist.cjs +26 -12
  34. package/build/modern/persist.cjs.map +1 -1
  35. package/build/modern/persist.d.cts +73 -14
  36. package/build/modern/persist.d.cts.map +1 -1
  37. package/build/modern/persist.d.ts +73 -14
  38. package/build/modern/persist.d.ts.map +1 -1
  39. package/build/modern/persist.js +26 -12
  40. package/build/modern/persist.js.map +1 -1
  41. package/build/modern/retryStrategies.cjs +6 -0
  42. package/build/modern/retryStrategies.cjs.map +1 -1
  43. package/build/modern/retryStrategies.d.cts +10 -0
  44. package/build/modern/retryStrategies.d.cts.map +1 -1
  45. package/build/modern/retryStrategies.d.ts +10 -0
  46. package/build/modern/retryStrategies.d.ts.map +1 -1
  47. package/build/modern/retryStrategies.js +6 -0
  48. package/build/modern/retryStrategies.js.map +1 -1
  49. package/package.json +4 -4
  50. package/src/createPersister.ts +103 -9
  51. package/src/persist.ts +77 -16
  52. package/src/retryStrategies.ts +10 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/query-persist-client-core",
3
- "version": "5.104.1",
3
+ "version": "5.104.2",
4
4
  "description": "Set of utilities for interacting with persisters, which can save your queryClient for later use",
5
5
  "author": "tannerlinsley",
6
6
  "license": "MIT",
@@ -40,7 +40,7 @@
40
40
  "!src/__tests__"
41
41
  ],
42
42
  "dependencies": {
43
- "@tanstack/query-core": "5.104.1"
43
+ "@tanstack/query-core": "5.104.2"
44
44
  },
45
45
  "devDependencies": {
46
46
  "@tanstack/query-test-utils": "0.0.0",
@@ -49,14 +49,14 @@
49
49
  "scripts": {
50
50
  "clean": "premove ./build ./coverage ./dist-ts ./.cache/test-types",
51
51
  "compile": "tsc --project tsconfig.json",
52
- "test:eslint": "eslint --concurrency=auto ./src",
52
+ "test:oxlint": "oxlint ./src",
53
53
  "test:types": "npm-run-all --serial test:types:*",
54
- "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts56 --tsBuildInfoFile .cache/test-types/ts56.tsbuildinfo",
55
54
  "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts57 --tsBuildInfoFile .cache/test-types/ts57.tsbuildinfo",
56
55
  "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts58 --tsBuildInfoFile .cache/test-types/ts58.tsbuildinfo",
57
56
  "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts59 --tsBuildInfoFile .cache/test-types/ts59.tsbuildinfo",
58
57
  "test:types:tscurrent": "tsc --project tsconfig.json --outDir .cache/test-types/tscurrent --tsBuildInfoFile .cache/test-types/tscurrent.tsbuildinfo",
59
58
  "test:types:ts70": "node ../../node_modules/typescript70/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts70 --tsBuildInfoFile .cache/test-types/ts70.tsbuildinfo",
59
+ "test:types:ts71": "node ../../node_modules/typescript71/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts71 --tsBuildInfoFile .cache/test-types/ts71.tsbuildinfo",
60
60
  "test:lib": "vitest",
61
61
  "test:lib:dev": "pnpm run test:lib --watch",
62
62
  "test:build": "publint --strict && attw --pack",
@@ -13,24 +13,62 @@ import type {
13
13
  QueryState,
14
14
  } from '@tanstack/query-core'
15
15
 
16
+ /**
17
+ * A single query as stored by {@link experimental_createQueryPersister}.
18
+ */
16
19
  export interface PersistedQuery {
20
+ /**
21
+ * The `buster` the query was saved with. Entries with a different `buster` are discarded.
22
+ */
17
23
  buster: string
24
+ /**
25
+ * The hash of the query.
26
+ */
18
27
  queryHash: string
28
+ /**
29
+ * The key of the query.
30
+ */
19
31
  queryKey: QueryKey
32
+ /**
33
+ * The state of the query, including its data and when it was last updated.
34
+ */
20
35
  state: QueryState
21
36
  }
22
37
 
38
+ /**
39
+ * A value, or a promise that resolves to it.
40
+ */
23
41
  export type MaybePromise<T> = T | Promise<T>
24
42
 
43
+ /**
44
+ * A key-value storage, such as `localStorage` or `AsyncStorage`, whose methods may be synchronous
45
+ * or return promises.
46
+ */
25
47
  export interface AsyncStorage<TStorageValue = string> {
48
+ /**
49
+ * Reads the value stored under `key`, or `null`/`undefined` if there is none.
50
+ */
26
51
  getItem: (key: string) => MaybePromise<TStorageValue | undefined | null>
52
+ /**
53
+ * Stores `value` under `key`.
54
+ */
27
55
  setItem: (key: string, value: TStorageValue) => MaybePromise<unknown>
56
+ /**
57
+ * Removes the value stored under `key`.
58
+ */
28
59
  removeItem: (key: string) => MaybePromise<void>
60
+ /**
61
+ * Returns all stored key-value pairs. Required for removing expired entries in bulk.
62
+ */
29
63
  entries?: () => MaybePromise<Array<[key: string, value: TStorageValue]>>
30
64
  }
31
65
 
66
+ /**
67
+ * Options for {@link experimental_createQueryPersister}.
68
+ */
32
69
  export interface StoragePersisterOptions<TStorageValue = string> {
33
- /** The storage client used for setting and retrieving items from cache.
70
+ /**
71
+ * The storage client used for setting and retrieving items from cache.
34
72
  * For SSR pass in `undefined`.
35
73
  */
36
74
  storage: AsyncStorage<TStorageValue> | undefined | null
@@ -66,7 +104,6 @@ export interface StoragePersisterOptions<TStorageValue = string> {
66
104
  * If set to `true`, the query will refetch on successful query restoration if the data is stale.
67
105
  * If set to `false`, the query will not refetch on successful query restoration.
68
106
  * If set to `'always'`, the query will always refetch on successful query restoration.
69
- *
70
107
  * @defaultValue true
71
108
  */
72
109
  refetchOnRestore?: boolean | 'always'
@@ -85,13 +122,17 @@ export const PERSISTER_KEY_PREFIX = 'tanstack-query'
85
122
  *
86
123
  * ```
87
124
  * useQuery({
88
- queryKey: ['myKey'],
89
- queryFn: fetcher,
90
- persister: createPersister({
91
- storage: localStorage,
92
- }),
93
- })
94
- ```
125
+ * queryKey: ['myKey'],
126
+ * queryFn: fetcher,
127
+ * persister: createPersister({
128
+ * storage: localStorage,
129
+ * }),
130
+ * })
131
+ * ```
132
+ * @param options - The storage to persist to, and the options for serializing, expiring, and
133
+ * filtering persisted queries.
134
+ * @returns The `persisterFn` to pass as a query's `persister`, plus functions to persist, retrieve,
135
+ * restore, remove, and garbage collect persisted queries manually.
95
136
  */
96
137
  export function experimental_createQueryPersister<TStorageValue = string>({
97
138
  storage,
@@ -107,6 +148,12 @@ export function experimental_createQueryPersister<TStorageValue = string>({
107
148
  refetchOnRestore = true,
108
149
  filters,
109
150
  }: StoragePersisterOptions<TStorageValue>) {
151
+ /**
152
+ * Checks whether a persisted query should be discarded.
153
+ * @param persistedQuery - The persisted query to check.
154
+ * @returns `true` if it has no `dataUpdatedAt`, is older than `maxAge`, or has a different
155
+ * `buster`.
156
+ */
110
157
  function isExpiredOrBusted(persistedQuery: PersistedQuery) {
111
158
  if (persistedQuery.state.dataUpdatedAt) {
112
159
  const queryAge = Date.now() - persistedQuery.state.dataUpdatedAt
@@ -123,6 +170,14 @@ export function experimental_createQueryPersister<TStorageValue = string>({
123
170
  return true
124
171
  }
125
172
 
173
+ /**
174
+ * Reads the persisted data of a query from storage. Expired, busted, or unreadable entries are
175
+ * removed instead.
176
+ * @param queryHash - The hash of the query to read.
177
+ * @param afterRestoreMacroTask - Scheduled with the persisted query after it is restored.
178
+ * @returns A promise that resolves with the persisted data, or `undefined` if nothing was
179
+ * restored.
180
+ */
126
181
  async function retrieveQuery<T>(
127
182
  queryHash: string,
128
183
  afterRestoreMacroTask?: (persistedQuery: PersistedQuery) => void,
@@ -167,6 +222,12 @@ export function experimental_createQueryPersister<TStorageValue = string>({
167
222
  return
168
223
  }
169
224
 
225
+ /**
226
+ * Persists the query with the given key, if it exists in the client's cache.
227
+ * @param queryKey - The key of the query to persist.
228
+ * @param queryClient - The client whose cache holds the query.
229
+ * @returns A promise that resolves once the query is persisted.
230
+ */
170
231
  async function persistQueryByKey(
171
232
  queryKey: QueryKey,
172
233
  queryClient: QueryClient,
@@ -186,6 +247,11 @@ export function experimental_createQueryPersister<TStorageValue = string>({
186
247
  }
187
248
  }
188
249
 
250
+ /**
251
+ * Writes a query's state, key, hash, and `buster` to storage.
252
+ * @param query - The query to persist.
253
+ * @returns A promise that resolves once the entry is serialized and written.
254
+ */
189
255
  async function persistQuery(query: Query) {
190
256
  if (storage != null) {
191
257
  const storageKey = `${prefix}-${query.queryHash}`
@@ -201,6 +267,14 @@ export function experimental_createQueryPersister<TStorageValue = string>({
201
267
  }
202
268
  }
203
269
 
270
+ /**
271
+ * The `persister` of a query: restores its data from storage if the query has none yet, otherwise
272
+ * runs `queryFn` and persists the result.
273
+ * @param queryFn - The query's own query function.
274
+ * @param ctx - The context passed to `queryFn`.
275
+ * @param query - The query being fetched.
276
+ * @returns A promise that resolves with the restored or fetched data.
277
+ */
204
278
  async function persisterFn<T, TQueryKey extends QueryKey>(
205
279
  queryFn: (context: QueryFunctionContext<TQueryKey>) => T | Promise<T>,
206
280
  ctx: QueryFunctionContext<TQueryKey>,
@@ -246,6 +320,11 @@ export function experimental_createQueryPersister<TStorageValue = string>({
246
320
  return Promise.resolve(queryFnResult)
247
321
  }
248
322
 
323
+ /**
324
+ * Removes expired, busted, or unreadable entries from storage. Requires the storage to implement
325
+ * `entries`.
326
+ * @returns A promise that resolves once every entry is checked.
327
+ */
249
328
  async function persisterGc() {
250
329
  if (storage?.entries) {
251
330
  const storageKeyPrefix = `${prefix}-`
@@ -271,6 +350,14 @@ export function experimental_createQueryPersister<TStorageValue = string>({
271
350
  }
272
351
  }
273
352
 
353
+ /**
354
+ * Restores every persisted query matching `filters` into the client's cache with
355
+ * `queryClient.setQueryData`. Requires the storage to implement `entries`.
356
+ * @param queryClient - The client to restore the queries into.
357
+ * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is
358
+ * restored.
359
+ * @returns A promise that resolves once every entry is checked.
360
+ */
274
361
  async function restoreQueries(
275
362
  queryClient: QueryClient,
276
363
  filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},
@@ -320,6 +407,13 @@ export function experimental_createQueryPersister<TStorageValue = string>({
320
407
  }
321
408
  }
322
409
 
410
+ /**
411
+ * Removes every persisted query matching `filters` from storage. Requires the storage to implement
412
+ * `entries`.
413
+ * @param filters - The `queryKey` and `exact` filters to match. Without them, every query is
414
+ * removed.
415
+ * @returns A promise that resolves once every entry is checked.
416
+ */
323
417
  async function removeQueries(
324
418
  filters: Pick<QueryFilters, 'queryKey' | 'exact'> = {},
325
419
  ): Promise<void> {
package/src/persist.ts CHANGED
@@ -7,66 +7,120 @@ import type {
7
7
  QueryClient,
8
8
  } from '@tanstack/query-core'
9
9
 
10
+ /**
11
+ * A value, or a promise-like that resolves to it.
12
+ */
10
13
  export type Promisable<T> = T | PromiseLike<T>
11
14
 
15
+ /**
16
+ * Saves, restores, and removes a {@link PersistedClient} in a storage.
17
+ */
12
18
  export interface Persister {
19
+ /**
20
+ * Saves the persisted client to the storage.
21
+ */
13
22
  persistClient: (persistClient: PersistedClient) => Promisable<void>
23
+ /**
24
+ * Reads the persisted client from the storage, or `undefined` if nothing was saved.
25
+ */
14
26
  restoreClient: () => Promisable<PersistedClient | undefined>
27
+ /**
28
+ * Removes the persisted client from the storage.
29
+ */
15
30
  removeClient: () => Promisable<void>
16
31
  }
17
32
 
33
+ /**
34
+ * The dehydrated state of a `QueryClient` as it is persisted, with the time it was saved and its
35
+ * `buster`.
36
+ */
18
37
  export interface PersistedClient {
38
+ /**
39
+ * When the client was saved, in milliseconds since the epoch. Compared with `maxAge` on restore.
40
+ */
19
41
  timestamp: number
42
+ /**
43
+ * The `buster` the client was saved with. A persisted client with a different `buster` is
44
+ * discarded.
45
+ */
20
46
  buster: string
47
+ /**
48
+ * The dehydrated cache of the `QueryClient`.
49
+ */
21
50
  clientState: DehydratedState
22
51
  }
23
52
 
53
+ /**
54
+ * The options shared by restoring and saving a persisted `QueryClient`.
55
+ */
24
56
  export interface PersistQueryClientRootOptions {
25
57
  /** The QueryClient to persist */
26
58
  queryClient: QueryClient
27
- /** The Persister interface for storing and restoring the cache
28
- * to/from a persisted location */
59
+ /**
60
+ * The Persister interface for storing and restoring the cache
61
+ * to/from a persisted location
62
+ */
29
63
  persister: Persister
30
- /** A unique string that can be used to forcefully
31
- * invalidate existing caches if they do not share the same buster string */
64
+ /**
65
+ * A unique string that can be used to forcefully
66
+ * invalidate existing caches if they do not share the same buster string
67
+ */
32
68
  buster?: string
33
69
  }
34
70
 
71
+ /**
72
+ * Options for restoring a persisted `QueryClient` with {@link persistQueryClientRestore}.
73
+ */
35
74
  export interface PersistedQueryClientRestoreOptions extends PersistQueryClientRootOptions {
36
- /** The max-allowed age of the cache in milliseconds.
75
+ /**
76
+ * The max-allowed age of the cache in milliseconds.
37
77
  * If a persisted cache is found that is older than this
38
- * time, it will be discarded */
78
+ * time, it will be discarded
79
+ */
39
80
  maxAge?: number
40
81
  /** The options passed to the hydrate function */
41
82
  hydrateOptions?: HydrateOptions
42
83
  }
43
84
 
85
+ /**
86
+ * Options for saving a `QueryClient` with {@link persistQueryClientSave}.
87
+ */
44
88
  export interface PersistedQueryClientSaveOptions extends PersistQueryClientRootOptions {
45
89
  /** The options passed to the dehydrate function */
46
90
  dehydrateOptions?: DehydrateOptions
47
91
  }
48
92
 
93
+ /**
94
+ * Options for {@link persistQueryClient}, which both restores and saves a `QueryClient`.
95
+ */
49
96
  export interface PersistQueryClientOptions
50
97
  extends
51
98
  PersistedQueryClientRestoreOptions,
52
99
  PersistedQueryClientSaveOptions,
53
100
  PersistQueryClientRootOptions {}
54
101
 
102
+ const cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']
103
+
55
104
  /**
56
105
  * Checks if emitted event is about cache change and not about observers.
57
106
  * Useful for persist, where we only want to trigger save when cache is changed.
107
+ * @param eventType - The type of the emitted event.
108
+ * @returns `true` if the event is `'added'`, `'removed'`, or `'updated'`.
58
109
  */
59
- const cacheEventTypes: Array<NotifyEventType> = ['added', 'removed', 'updated']
60
-
61
110
  function isCacheEventType(eventType: NotifyEventType) {
62
111
  return cacheEventTypes.includes(eventType)
63
112
  }
64
113
 
65
114
  /**
66
- * Restores persisted data to the QueryCache
67
- * - data obtained from persister.restoreClient
68
- * - data is hydrated using hydrateOptions
69
- * If data is expired, busted, empty, or throws, it runs persister.removeClient
115
+ * Restores persisted data to the QueryCache.
116
+ * - data obtained from persister.restoreClient.
117
+ * - data is hydrated using hydrateOptions.
118
+ * If data is expired, busted, empty, or throws, it runs persister.removeClient.
119
+ * @param options - The `queryClient` to restore into, the `persister`, and the `maxAge`, `buster`,
120
+ * and `hydrateOptions` that decide whether and how the persisted data is restored.
121
+ * @returns A promise that resolves once the data is restored or removed. If restoring throws, it
122
+ * attempts to remove the persisted data and then rejects with the restore error, or with the removal
123
+ * error if the removal fails too.
70
124
  */
71
125
  export async function persistQueryClientRestore({
72
126
  queryClient,
@@ -106,9 +160,11 @@ export async function persistQueryClientRestore({
106
160
  }
107
161
 
108
162
  /**
109
- * Persists data from the QueryCache
110
- * - data dehydrated using dehydrateOptions
111
- * - data is persisted using persister.persistClient
163
+ * Persists data from the QueryCache.
164
+ * - data dehydrated using dehydrateOptions.
165
+ * - data is persisted using persister.persistClient.
166
+ * @param options - The `queryClient` to persist, the `persister`, the `buster`, and the
167
+ * `dehydrateOptions`.
112
168
  */
113
169
  export async function persistQueryClientSave({
114
170
  queryClient,
@@ -126,7 +182,9 @@ export async function persistQueryClientSave({
126
182
  }
127
183
 
128
184
  /**
129
- * Subscribe to QueryCache and MutationCache updates (for persisting)
185
+ * Subscribe to QueryCache and MutationCache updates (for persisting).
186
+ * @param props - The `queryClient` to monitor, the `persister`, the `buster`, and the
187
+ * `dehydrateOptions` used for each save.
130
188
  * @returns an unsubscribe function (to discontinue monitoring)
131
189
  */
132
190
  export function persistQueryClientSubscribe(
@@ -156,6 +214,9 @@ export function persistQueryClientSubscribe(
156
214
 
157
215
  /**
158
216
  * Restores persisted data to QueryCache and persists further changes.
217
+ * @param props - The options for both restoring and saving.
218
+ * @returns A tuple of a function that stops persisting, and a promise that resolves once the
219
+ * restore is done.
159
220
  */
160
221
  export function persistQueryClient(
161
222
  props: PersistQueryClientOptions,
@@ -1,11 +1,21 @@
1
1
  import type { PersistedClient } from './persist'
2
2
 
3
+ /**
4
+ * Called when saving the persisted client fails. Returns a smaller client to try saving again, or
5
+ * `undefined` to give up.
6
+ */
3
7
  export type PersistRetryer = (props: {
4
8
  persistedClient: PersistedClient
5
9
  error: Error
6
10
  errorCount: number
7
11
  }) => PersistedClient | undefined
8
12
 
13
+ /**
14
+ * A {@link PersistRetryer} that drops the query with the oldest `dataUpdatedAt` and tries again, until
15
+ * no queries are left.
16
+ * @param props - The `persistedClient` that failed to save.
17
+ * @returns A copy of the client without its oldest query, or `undefined` if it has no queries.
18
+ */
9
19
  export const removeOldestQuery: PersistRetryer = ({ persistedClient }) => {
10
20
  const mutations = [...persistedClient.clientState.mutations]
11
21
  const queries = [...persistedClient.clientState.queries]