@tanstack/query-core 4.24.10 → 5.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/build/lib/focusManager.d.ts +1 -3
  2. package/build/lib/focusManager.esm.js +19 -36
  3. package/build/lib/focusManager.esm.js.map +1 -1
  4. package/build/lib/focusManager.js +19 -38
  5. package/build/lib/focusManager.js.map +1 -1
  6. package/build/lib/focusManager.mjs +19 -36
  7. package/build/lib/focusManager.mjs.map +1 -1
  8. package/build/lib/hydration.esm.js +21 -23
  9. package/build/lib/hydration.esm.js.map +1 -1
  10. package/build/lib/hydration.js +21 -25
  11. package/build/lib/hydration.js.map +1 -1
  12. package/build/lib/hydration.mjs +21 -23
  13. package/build/lib/hydration.mjs.map +1 -1
  14. package/build/lib/index.d.ts +1 -2
  15. package/build/lib/index.esm.js +1 -1
  16. package/build/lib/index.js +2 -8
  17. package/build/lib/index.js.map +1 -1
  18. package/build/lib/index.mjs +1 -1
  19. package/build/lib/infiniteQueryBehavior.d.ts +3 -7
  20. package/build/lib/infiniteQueryBehavior.esm.js +52 -75
  21. package/build/lib/infiniteQueryBehavior.esm.js.map +1 -1
  22. package/build/lib/infiniteQueryBehavior.js +50 -77
  23. package/build/lib/infiniteQueryBehavior.js.map +1 -1
  24. package/build/lib/infiniteQueryBehavior.mjs +52 -75
  25. package/build/lib/infiniteQueryBehavior.mjs.map +1 -1
  26. package/build/lib/infiniteQueryObserver.d.ts +4 -4
  27. package/build/lib/infiniteQueryObserver.esm.js +18 -26
  28. package/build/lib/infiniteQueryObserver.esm.js.map +1 -1
  29. package/build/lib/infiniteQueryObserver.js +18 -28
  30. package/build/lib/infiniteQueryObserver.js.map +1 -1
  31. package/build/lib/infiniteQueryObserver.mjs +18 -26
  32. package/build/lib/infiniteQueryObserver.mjs.map +1 -1
  33. package/build/lib/mutation.d.ts +11 -22
  34. package/build/lib/mutation.esm.js +73 -105
  35. package/build/lib/mutation.esm.js.map +1 -1
  36. package/build/lib/mutation.js +73 -107
  37. package/build/lib/mutation.js.map +1 -1
  38. package/build/lib/mutation.mjs +73 -105
  39. package/build/lib/mutation.mjs.map +1 -1
  40. package/build/lib/mutationCache.d.ts +4 -6
  41. package/build/lib/mutationCache.esm.js +23 -32
  42. package/build/lib/mutationCache.esm.js.map +1 -1
  43. package/build/lib/mutationCache.js +23 -34
  44. package/build/lib/mutationCache.js.map +1 -1
  45. package/build/lib/mutationCache.mjs +23 -32
  46. package/build/lib/mutationCache.mjs.map +1 -1
  47. package/build/lib/mutationObserver.d.ts +4 -9
  48. package/build/lib/mutationObserver.esm.js +43 -72
  49. package/build/lib/mutationObserver.esm.js.map +1 -1
  50. package/build/lib/mutationObserver.js +43 -74
  51. package/build/lib/mutationObserver.js.map +1 -1
  52. package/build/lib/mutationObserver.mjs +43 -72
  53. package/build/lib/mutationObserver.mjs.map +1 -1
  54. package/build/lib/notifyManager.esm.js +7 -17
  55. package/build/lib/notifyManager.esm.js.map +1 -1
  56. package/build/lib/notifyManager.js +7 -19
  57. package/build/lib/notifyManager.js.map +1 -1
  58. package/build/lib/notifyManager.mjs +7 -17
  59. package/build/lib/notifyManager.mjs.map +1 -1
  60. package/build/lib/onlineManager.d.ts +1 -3
  61. package/build/lib/onlineManager.esm.js +16 -30
  62. package/build/lib/onlineManager.esm.js.map +1 -1
  63. package/build/lib/onlineManager.js +16 -32
  64. package/build/lib/onlineManager.js.map +1 -1
  65. package/build/lib/onlineManager.mjs +16 -30
  66. package/build/lib/onlineManager.mjs.map +1 -1
  67. package/build/lib/queriesObserver.d.ts +3 -10
  68. package/build/lib/queriesObserver.esm.js +47 -71
  69. package/build/lib/queriesObserver.esm.js.map +1 -1
  70. package/build/lib/queriesObserver.js +49 -75
  71. package/build/lib/queriesObserver.js.map +1 -1
  72. package/build/lib/queriesObserver.mjs +47 -71
  73. package/build/lib/queriesObserver.mjs.map +1 -1
  74. package/build/lib/query.d.ts +14 -21
  75. package/build/lib/query.esm.js +140 -194
  76. package/build/lib/query.esm.js.map +1 -1
  77. package/build/lib/query.js +139 -195
  78. package/build/lib/query.js.map +1 -1
  79. package/build/lib/query.mjs +140 -194
  80. package/build/lib/query.mjs.map +1 -1
  81. package/build/lib/queryCache.d.ts +12 -7
  82. package/build/lib/queryCache.esm.js +21 -45
  83. package/build/lib/queryCache.esm.js.map +1 -1
  84. package/build/lib/queryCache.js +20 -46
  85. package/build/lib/queryCache.js.map +1 -1
  86. package/build/lib/queryCache.mjs +21 -45
  87. package/build/lib/queryCache.mjs.map +1 -1
  88. package/build/lib/queryClient.d.ts +18 -46
  89. package/build/lib/queryClient.esm.js +137 -216
  90. package/build/lib/queryClient.esm.js.map +1 -1
  91. package/build/lib/queryClient.js +136 -217
  92. package/build/lib/queryClient.js.map +1 -1
  93. package/build/lib/queryClient.mjs +137 -216
  94. package/build/lib/queryClient.mjs.map +1 -1
  95. package/build/lib/queryObserver.d.ts +4 -29
  96. package/build/lib/queryObserver.esm.js +176 -258
  97. package/build/lib/queryObserver.esm.js.map +1 -1
  98. package/build/lib/queryObserver.js +176 -260
  99. package/build/lib/queryObserver.js.map +1 -1
  100. package/build/lib/queryObserver.mjs +176 -258
  101. package/build/lib/queryObserver.mjs.map +1 -1
  102. package/build/lib/removable.d.ts +3 -3
  103. package/build/lib/removable.esm.js +10 -14
  104. package/build/lib/removable.esm.js.map +1 -1
  105. package/build/lib/removable.js +10 -16
  106. package/build/lib/removable.js.map +1 -1
  107. package/build/lib/removable.mjs +10 -14
  108. package/build/lib/removable.mjs.map +1 -1
  109. package/build/lib/retryer.d.ts +5 -5
  110. package/build/lib/retryer.esm.js +27 -44
  111. package/build/lib/retryer.esm.js.map +1 -1
  112. package/build/lib/retryer.js +27 -46
  113. package/build/lib/retryer.js.map +1 -1
  114. package/build/lib/retryer.mjs +27 -44
  115. package/build/lib/retryer.mjs.map +1 -1
  116. package/build/lib/subscribable.esm.js +4 -7
  117. package/build/lib/subscribable.esm.js.map +1 -1
  118. package/build/lib/subscribable.js +4 -9
  119. package/build/lib/subscribable.js.map +1 -1
  120. package/build/lib/subscribable.mjs +4 -7
  121. package/build/lib/subscribable.mjs.map +1 -1
  122. package/build/lib/tests/utils.d.ts +3 -12
  123. package/build/lib/types.d.ts +111 -99
  124. package/build/lib/utils.d.ts +8 -18
  125. package/build/lib/utils.esm.js +39 -132
  126. package/build/lib/utils.esm.js.map +1 -1
  127. package/build/lib/utils.js +42 -144
  128. package/build/lib/utils.js.map +1 -1
  129. package/build/lib/utils.mjs +39 -132
  130. package/build/lib/utils.mjs.map +1 -1
  131. package/build/umd/index.development.js +868 -1398
  132. package/build/umd/index.development.js.map +1 -1
  133. package/build/umd/index.production.js +1 -1
  134. package/build/umd/index.production.js.map +1 -1
  135. package/package.json +1 -1
  136. package/src/focusManager.ts +17 -24
  137. package/src/index.ts +1 -11
  138. package/src/infiniteQueryBehavior.ts +54 -94
  139. package/src/infiniteQueryObserver.ts +10 -12
  140. package/src/mutation.ts +68 -92
  141. package/src/mutationCache.ts +27 -27
  142. package/src/mutationObserver.ts +60 -97
  143. package/src/onlineManager.ts +14 -14
  144. package/src/queriesObserver.ts +50 -54
  145. package/src/query.ts +106 -110
  146. package/src/queryCache.ts +42 -41
  147. package/src/queryClient.ts +155 -434
  148. package/src/queryObserver.ts +155 -192
  149. package/src/removable.ts +13 -13
  150. package/src/retryer.ts +5 -5
  151. package/src/tests/focusManager.test.tsx +25 -25
  152. package/src/tests/hydration.test.tsx +167 -81
  153. package/src/tests/infiniteQueryBehavior.test.tsx +209 -17
  154. package/src/tests/infiniteQueryObserver.test.tsx +6 -2
  155. package/src/tests/mutationCache.test.tsx +127 -127
  156. package/src/tests/mutationObserver.test.tsx +1 -31
  157. package/src/tests/mutations.test.tsx +62 -43
  158. package/src/tests/onlineManager.test.tsx +12 -4
  159. package/src/tests/queriesObserver.test.tsx +41 -77
  160. package/src/tests/query.test.tsx +175 -243
  161. package/src/tests/queryCache.test.tsx +170 -93
  162. package/src/tests/queryClient.test.tsx +229 -378
  163. package/src/tests/queryObserver.test.tsx +23 -147
  164. package/src/tests/utils.test.tsx +84 -29
  165. package/src/tests/utils.ts +9 -18
  166. package/src/types.ts +187 -140
  167. package/src/utils.ts +31 -124
  168. package/build/lib/logger.d.ts +0 -8
  169. package/build/lib/logger.esm.js +0 -4
  170. package/build/lib/logger.esm.js.map +0 -1
  171. package/build/lib/logger.js +0 -8
  172. package/build/lib/logger.js.map +0 -1
  173. package/build/lib/logger.mjs +0 -4
  174. package/build/lib/logger.mjs.map +0 -1
  175. package/build/lib/logger.native.d.ts +0 -6
  176. package/build/lib/logger.native.esm.js +0 -12
  177. package/build/lib/logger.native.esm.js.map +0 -1
  178. package/build/lib/logger.native.js +0 -16
  179. package/build/lib/logger.native.js.map +0 -1
  180. package/build/lib/logger.native.mjs +0 -12
  181. package/build/lib/logger.native.mjs.map +0 -1
  182. package/src/logger.native.ts +0 -11
  183. package/src/logger.ts +0 -9
@@ -9,7 +9,6 @@
9
9
  this.listeners = [];
10
10
  this.subscribe = this.subscribe.bind(this);
11
11
  }
12
-
13
12
  subscribe(listener) {
14
13
  this.listeners.push(listener);
15
14
  this.onSubscribe();
@@ -18,21 +17,21 @@
18
17
  this.onUnsubscribe();
19
18
  };
20
19
  }
21
-
22
20
  hasListeners() {
23
21
  return this.listeners.length > 0;
24
22
  }
25
-
26
- onSubscribe() {// Do nothing
23
+ onSubscribe() {
24
+ // Do nothing
27
25
  }
28
-
29
- onUnsubscribe() {// Do nothing
26
+ onUnsubscribe() {
27
+ // Do nothing
30
28
  }
31
-
32
29
  }
33
30
 
34
31
  // TYPES
32
+
35
33
  // UTILS
34
+
36
35
  const isServer = typeof window === 'undefined' || 'Deno' in window;
37
36
  function noop() {
38
37
  return undefined;
@@ -43,66 +42,9 @@
43
42
  function isValidTimeout(value) {
44
43
  return typeof value === 'number' && value >= 0 && value !== Infinity;
45
44
  }
46
- function difference(array1, array2) {
47
- return array1.filter(x => array2.indexOf(x) === -1);
48
- }
49
- function replaceAt(array, index, value) {
50
- const copy = array.slice(0);
51
- copy[index] = value;
52
- return copy;
53
- }
54
45
  function timeUntilStale(updatedAt, staleTime) {
55
46
  return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
56
47
  }
57
- function parseQueryArgs(arg1, arg2, arg3) {
58
- if (!isQueryKey(arg1)) {
59
- return arg1;
60
- }
61
-
62
- if (typeof arg2 === 'function') {
63
- return { ...arg3,
64
- queryKey: arg1,
65
- queryFn: arg2
66
- };
67
- }
68
-
69
- return { ...arg2,
70
- queryKey: arg1
71
- };
72
- }
73
- function parseMutationArgs(arg1, arg2, arg3) {
74
- if (isQueryKey(arg1)) {
75
- if (typeof arg2 === 'function') {
76
- return { ...arg3,
77
- mutationKey: arg1,
78
- mutationFn: arg2
79
- };
80
- }
81
-
82
- return { ...arg2,
83
- mutationKey: arg1
84
- };
85
- }
86
-
87
- if (typeof arg1 === 'function') {
88
- return { ...arg2,
89
- mutationFn: arg1
90
- };
91
- }
92
-
93
- return { ...arg1
94
- };
95
- }
96
- function parseFilterArgs(arg1, arg2, arg3) {
97
- return isQueryKey(arg1) ? [{ ...arg2,
98
- queryKey: arg1
99
- }, arg3] : [arg1 || {}, arg2];
100
- }
101
- function parseMutationFilterArgs(arg1, arg2, arg3) {
102
- return isQueryKey(arg1) ? [{ ...arg2,
103
- mutationKey: arg1
104
- }, arg3] : [arg1 || {}, arg2];
105
- }
106
48
  function matchQuery(filters, query) {
107
49
  const {
108
50
  type = 'all',
@@ -112,8 +54,7 @@
112
54
  queryKey,
113
55
  stale
114
56
  } = filters;
115
-
116
- if (isQueryKey(queryKey)) {
57
+ if (queryKey) {
117
58
  if (exact) {
118
59
  if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
119
60
  return false;
@@ -122,106 +63,86 @@
122
63
  return false;
123
64
  }
124
65
  }
125
-
126
66
  if (type !== 'all') {
127
67
  const isActive = query.isActive();
128
-
129
68
  if (type === 'active' && !isActive) {
130
69
  return false;
131
70
  }
132
-
133
71
  if (type === 'inactive' && isActive) {
134
72
  return false;
135
73
  }
136
74
  }
137
-
138
75
  if (typeof stale === 'boolean' && query.isStale() !== stale) {
139
76
  return false;
140
77
  }
141
-
142
78
  if (typeof fetchStatus !== 'undefined' && fetchStatus !== query.state.fetchStatus) {
143
79
  return false;
144
80
  }
145
-
146
81
  if (predicate && !predicate(query)) {
147
82
  return false;
148
83
  }
149
-
150
84
  return true;
151
85
  }
152
86
  function matchMutation(filters, mutation) {
153
87
  const {
154
88
  exact,
155
- fetching,
89
+ status,
156
90
  predicate,
157
91
  mutationKey
158
92
  } = filters;
159
-
160
- if (isQueryKey(mutationKey)) {
93
+ if (mutationKey) {
161
94
  if (!mutation.options.mutationKey) {
162
95
  return false;
163
96
  }
164
-
165
97
  if (exact) {
166
- if (hashQueryKey(mutation.options.mutationKey) !== hashQueryKey(mutationKey)) {
98
+ if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {
167
99
  return false;
168
100
  }
169
101
  } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
170
102
  return false;
171
103
  }
172
104
  }
173
-
174
- if (typeof fetching === 'boolean' && mutation.state.status === 'loading' !== fetching) {
105
+ if (status && mutation.state.status !== status) {
175
106
  return false;
176
107
  }
177
-
178
108
  if (predicate && !predicate(mutation)) {
179
109
  return false;
180
110
  }
181
-
182
111
  return true;
183
112
  }
184
113
  function hashQueryKeyByOptions(queryKey, options) {
185
- const hashFn = (options == null ? void 0 : options.queryKeyHashFn) || hashQueryKey;
114
+ const hashFn = options?.queryKeyHashFn || hashKey;
186
115
  return hashFn(queryKey);
187
116
  }
117
+
188
118
  /**
189
- * Default query keys hash function.
119
+ * Default query & mutation keys hash function.
190
120
  * Hashes the value into a stable hash.
191
121
  */
192
-
193
- function hashQueryKey(queryKey) {
122
+ function hashKey(queryKey) {
194
123
  return JSON.stringify(queryKey, (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
195
124
  result[key] = val[key];
196
125
  return result;
197
126
  }, {}) : val);
198
127
  }
128
+
199
129
  /**
200
130
  * Checks if key `b` partially matches with key `a`.
201
131
  */
202
132
 
203
133
  function partialMatchKey(a, b) {
204
- return partialDeepEqual(a, b);
205
- }
206
- /**
207
- * Checks if `b` partially matches with `a`.
208
- */
209
-
210
- function partialDeepEqual(a, b) {
211
134
  if (a === b) {
212
135
  return true;
213
136
  }
214
-
215
137
  if (typeof a !== typeof b) {
216
138
  return false;
217
139
  }
218
-
219
140
  if (a && b && typeof a === 'object' && typeof b === 'object') {
220
- return !Object.keys(b).some(key => !partialDeepEqual(a[key], b[key]));
141
+ return !Object.keys(b).some(key => !partialMatchKey(a[key], b[key]));
221
142
  }
222
-
223
143
  return false;
224
144
  }
145
+
225
146
  /**
226
147
  * This function returns `a` if `b` is deeply equal.
227
148
  * If not, it will replace any deeply equal children of `b` with those of `a`.
@@ -232,168 +153,142 @@
232
153
  if (a === b) {
233
154
  return a;
234
155
  }
235
-
236
156
  const array = isPlainArray(a) && isPlainArray(b);
237
-
238
157
  if (array || isPlainObject(a) && isPlainObject(b)) {
239
158
  const aSize = array ? a.length : Object.keys(a).length;
240
159
  const bItems = array ? b : Object.keys(b);
241
160
  const bSize = bItems.length;
242
161
  const copy = array ? [] : {};
243
162
  let equalItems = 0;
244
-
245
163
  for (let i = 0; i < bSize; i++) {
246
164
  const key = array ? i : bItems[i];
247
165
  copy[key] = replaceEqualDeep(a[key], b[key]);
248
-
249
166
  if (copy[key] === a[key]) {
250
167
  equalItems++;
251
168
  }
252
169
  }
253
-
254
170
  return aSize === bSize && equalItems === aSize ? a : copy;
255
171
  }
256
-
257
172
  return b;
258
173
  }
174
+
259
175
  /**
260
176
  * Shallow compare objects. Only works with objects that always have the same properties.
261
177
  */
262
-
263
178
  function shallowEqualObjects(a, b) {
264
179
  if (a && !b || b && !a) {
265
180
  return false;
266
181
  }
267
-
268
182
  for (const key in a) {
269
183
  if (a[key] !== b[key]) {
270
184
  return false;
271
185
  }
272
186
  }
273
-
274
187
  return true;
275
188
  }
276
189
  function isPlainArray(value) {
277
190
  return Array.isArray(value) && value.length === Object.keys(value).length;
278
- } // Copied from: https://github.com/jonschlinkert/is-plain-object
191
+ }
279
192
 
193
+ // Copied from: https://github.com/jonschlinkert/is-plain-object
280
194
  function isPlainObject(o) {
281
195
  if (!hasObjectPrototype(o)) {
282
196
  return false;
283
- } // If has modified constructor
284
-
197
+ }
285
198
 
199
+ // If has modified constructor
286
200
  const ctor = o.constructor;
287
-
288
201
  if (typeof ctor === 'undefined') {
289
202
  return true;
290
- } // If has modified prototype
291
-
203
+ }
292
204
 
205
+ // If has modified prototype
293
206
  const prot = ctor.prototype;
294
-
295
207
  if (!hasObjectPrototype(prot)) {
296
208
  return false;
297
- } // If constructor does not have an Object-specific method
298
-
209
+ }
299
210
 
211
+ // If constructor does not have an Object-specific method
300
212
  if (!prot.hasOwnProperty('isPrototypeOf')) {
301
213
  return false;
302
- } // Most likely a plain Object
303
-
214
+ }
304
215
 
216
+ // Most likely a plain Object
305
217
  return true;
306
218
  }
307
-
308
219
  function hasObjectPrototype(o) {
309
220
  return Object.prototype.toString.call(o) === '[object Object]';
310
221
  }
311
-
312
- function isQueryKey(value) {
313
- return Array.isArray(value);
314
- }
315
- function isError(value) {
316
- return value instanceof Error;
317
- }
318
222
  function sleep(timeout) {
319
223
  return new Promise(resolve => {
320
224
  setTimeout(resolve, timeout);
321
225
  });
322
226
  }
227
+
323
228
  /**
324
229
  * Schedules a microtask.
325
230
  * This can be useful to schedule state updates after rendering.
326
231
  */
327
-
328
232
  function scheduleMicrotask(callback) {
329
233
  sleep(0).then(callback);
330
234
  }
331
- function getAbortController() {
332
- if (typeof AbortController === 'function') {
333
- return new AbortController();
334
- }
335
-
336
- return;
337
- }
338
235
  function replaceData(prevData, data, options) {
339
- // Use prev data if an isDataEqual function is defined and returns `true`
340
- if (options.isDataEqual != null && options.isDataEqual(prevData, data)) {
341
- return prevData;
342
- } else if (typeof options.structuralSharing === 'function') {
236
+ if (typeof options.structuralSharing === 'function') {
343
237
  return options.structuralSharing(prevData, data);
344
238
  } else if (options.structuralSharing !== false) {
345
239
  // Structurally share data between prev and new data if needed
346
240
  return replaceEqualDeep(prevData, data);
347
241
  }
348
-
349
242
  return data;
350
243
  }
244
+ function keepPreviousData(previousData) {
245
+ return previousData;
246
+ }
247
+ function addToEnd(items, item, max = 0) {
248
+ const newItems = [...items, item];
249
+ return max && newItems.length > max ? newItems.slice(1) : newItems;
250
+ }
251
+ function addToStart(items, item, max = 0) {
252
+ const newItems = [item, ...items];
253
+ return max && newItems.length > max ? newItems.slice(0, -1) : newItems;
254
+ }
351
255
 
352
256
  class FocusManager extends Subscribable {
257
+ #focused;
258
+ #cleanup;
259
+ #setup;
353
260
  constructor() {
354
261
  super();
355
-
356
- this.setup = onFocus => {
262
+ this.#setup = onFocus => {
357
263
  // addEventListener does not exist in React Native, but window does
358
264
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
359
265
  if (!isServer && window.addEventListener) {
360
- const listener = () => onFocus(); // Listen to visibillitychange and focus
361
-
362
-
266
+ const listener = () => onFocus();
267
+ // Listen to visibilitychange
363
268
  window.addEventListener('visibilitychange', listener, false);
364
- window.addEventListener('focus', listener, false);
365
269
  return () => {
366
270
  // Be sure to unsubscribe if a new handler is set
367
271
  window.removeEventListener('visibilitychange', listener);
368
- window.removeEventListener('focus', listener);
369
272
  };
370
273
  }
371
-
372
274
  return;
373
275
  };
374
276
  }
375
-
376
277
  onSubscribe() {
377
- if (!this.cleanup) {
378
- this.setEventListener(this.setup);
278
+ if (!this.#cleanup) {
279
+ this.setEventListener(this.#setup);
379
280
  }
380
281
  }
381
-
382
282
  onUnsubscribe() {
383
283
  if (!this.hasListeners()) {
384
- var _this$cleanup;
385
-
386
- (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
387
- this.cleanup = undefined;
284
+ this.#cleanup?.();
285
+ this.#cleanup = undefined;
388
286
  }
389
287
  }
390
-
391
288
  setEventListener(setup) {
392
- var _this$cleanup2;
393
-
394
- this.setup = setup;
395
- (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
396
- this.cleanup = setup(focused => {
289
+ this.#setup = setup;
290
+ this.#cleanup?.();
291
+ this.#cleanup = setup(focused => {
397
292
  if (typeof focused === 'boolean') {
398
293
  this.setFocused(focused);
399
294
  } else {
@@ -401,48 +296,41 @@
401
296
  }
402
297
  });
403
298
  }
404
-
405
299
  setFocused(focused) {
406
- this.focused = focused;
407
-
300
+ this.#focused = focused;
408
301
  if (focused) {
409
302
  this.onFocus();
410
303
  }
411
304
  }
412
-
413
305
  onFocus() {
414
306
  this.listeners.forEach(listener => {
415
307
  listener();
416
308
  });
417
309
  }
418
-
419
310
  isFocused() {
420
- if (typeof this.focused === 'boolean') {
421
- return this.focused;
422
- } // document global can be unavailable in react native
423
-
424
-
425
- if (typeof document === 'undefined') {
426
- return true;
311
+ if (typeof this.#focused === 'boolean') {
312
+ return this.#focused;
427
313
  }
428
314
 
429
- return [undefined, 'visible', 'prerender'].includes(document.visibilityState);
315
+ // document global can be unavailable in react native
316
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
317
+ return globalThis.document?.visibilityState !== 'hidden';
430
318
  }
431
-
432
319
  }
433
320
  const focusManager = new FocusManager();
434
321
 
435
322
  class OnlineManager extends Subscribable {
323
+ #online;
324
+ #cleanup;
325
+ #setup;
436
326
  constructor() {
437
327
  super();
438
-
439
- this.setup = onOnline => {
328
+ this.#setup = onOnline => {
440
329
  // addEventListener does not exist in React Native, but window does
441
330
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
442
331
  if (!isServer && window.addEventListener) {
443
- const listener = () => onOnline(); // Listen to online
444
-
445
-
332
+ const listener = () => onOnline();
333
+ // Listen to online
446
334
  window.addEventListener('online', listener, false);
447
335
  window.addEventListener('offline', listener, false);
448
336
  return () => {
@@ -451,32 +339,24 @@
451
339
  window.removeEventListener('offline', listener);
452
340
  };
453
341
  }
454
-
455
342
  return;
456
343
  };
457
344
  }
458
-
459
345
  onSubscribe() {
460
- if (!this.cleanup) {
461
- this.setEventListener(this.setup);
346
+ if (!this.#cleanup) {
347
+ this.setEventListener(this.#setup);
462
348
  }
463
349
  }
464
-
465
350
  onUnsubscribe() {
466
351
  if (!this.hasListeners()) {
467
- var _this$cleanup;
468
-
469
- (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
470
- this.cleanup = undefined;
352
+ this.#cleanup?.();
353
+ this.#cleanup = undefined;
471
354
  }
472
355
  }
473
-
474
356
  setEventListener(setup) {
475
- var _this$cleanup2;
476
-
477
- this.setup = setup;
478
- (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
479
- this.cleanup = setup(online => {
357
+ this.#setup = setup;
358
+ this.#cleanup?.();
359
+ this.#cleanup = setup(online => {
480
360
  if (typeof online === 'boolean') {
481
361
  this.setOnline(online);
482
362
  } else {
@@ -484,49 +364,40 @@
484
364
  }
485
365
  });
486
366
  }
487
-
488
367
  setOnline(online) {
489
- this.online = online;
490
-
368
+ this.#online = online;
491
369
  if (online) {
492
370
  this.onOnline();
493
371
  }
494
372
  }
495
-
496
373
  onOnline() {
497
374
  this.listeners.forEach(listener => {
498
375
  listener();
499
376
  });
500
377
  }
501
-
502
378
  isOnline() {
503
- if (typeof this.online === 'boolean') {
504
- return this.online;
379
+ if (typeof this.#online === 'boolean') {
380
+ return this.#online;
505
381
  }
506
-
507
382
  if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') {
508
383
  return true;
509
384
  }
510
-
511
385
  return navigator.onLine;
512
386
  }
513
-
514
387
  }
515
388
  const onlineManager = new OnlineManager();
516
389
 
517
390
  function defaultRetryDelay(failureCount) {
518
391
  return Math.min(1000 * 2 ** failureCount, 30000);
519
392
  }
520
-
521
393
  function canFetch(networkMode) {
522
- return (networkMode != null ? networkMode : 'online') === 'online' ? onlineManager.isOnline() : true;
394
+ return (networkMode ?? 'online') === 'online' ? onlineManager.isOnline() : true;
523
395
  }
524
396
  class CancelledError {
525
397
  constructor(options) {
526
- this.revert = options == null ? void 0 : options.revert;
527
- this.silent = options == null ? void 0 : options.silent;
398
+ this.revert = options?.revert;
399
+ this.silent = options?.silent;
528
400
  }
529
-
530
401
  }
531
402
  function isCancelledError(value) {
532
403
  return value instanceof CancelledError;
@@ -542,109 +413,95 @@
542
413
  promiseResolve = outerResolve;
543
414
  promiseReject = outerReject;
544
415
  });
545
-
546
416
  const cancel = cancelOptions => {
547
417
  if (!isResolved) {
548
418
  reject(new CancelledError(cancelOptions));
549
- config.abort == null ? void 0 : config.abort();
419
+ config.abort?.();
550
420
  }
551
421
  };
552
-
553
422
  const cancelRetry = () => {
554
423
  isRetryCancelled = true;
555
424
  };
556
-
557
425
  const continueRetry = () => {
558
426
  isRetryCancelled = false;
559
427
  };
560
-
561
428
  const shouldPause = () => !focusManager.isFocused() || config.networkMode !== 'always' && !onlineManager.isOnline();
562
-
563
429
  const resolve = value => {
564
430
  if (!isResolved) {
565
431
  isResolved = true;
566
- config.onSuccess == null ? void 0 : config.onSuccess(value);
567
- continueFn == null ? void 0 : continueFn();
432
+ config.onSuccess?.(value);
433
+ continueFn?.();
568
434
  promiseResolve(value);
569
435
  }
570
436
  };
571
-
572
437
  const reject = value => {
573
438
  if (!isResolved) {
574
439
  isResolved = true;
575
- config.onError == null ? void 0 : config.onError(value);
576
- continueFn == null ? void 0 : continueFn();
440
+ config.onError?.(value);
441
+ continueFn?.();
577
442
  promiseReject(value);
578
443
  }
579
444
  };
580
-
581
445
  const pause = () => {
582
446
  return new Promise(continueResolve => {
583
447
  continueFn = value => {
584
448
  const canContinue = isResolved || !shouldPause();
585
-
586
449
  if (canContinue) {
587
450
  continueResolve(value);
588
451
  }
589
-
590
452
  return canContinue;
591
453
  };
592
-
593
- config.onPause == null ? void 0 : config.onPause();
454
+ config.onPause?.();
594
455
  }).then(() => {
595
456
  continueFn = undefined;
596
-
597
457
  if (!isResolved) {
598
- config.onContinue == null ? void 0 : config.onContinue();
458
+ config.onContinue?.();
599
459
  }
600
460
  });
601
- }; // Create loop function
602
-
461
+ };
603
462
 
463
+ // Create loop function
604
464
  const run = () => {
605
465
  // Do nothing if already resolved
606
466
  if (isResolved) {
607
467
  return;
608
468
  }
469
+ let promiseOrValue;
609
470
 
610
- let promiseOrValue; // Execute query
611
-
471
+ // Execute query
612
472
  try {
613
473
  promiseOrValue = config.fn();
614
474
  } catch (error) {
615
475
  promiseOrValue = Promise.reject(error);
616
476
  }
617
-
618
477
  Promise.resolve(promiseOrValue).then(resolve).catch(error => {
619
- var _config$retry, _config$retryDelay;
620
-
621
478
  // Stop if the fetch is already resolved
622
479
  if (isResolved) {
623
480
  return;
624
- } // Do we need to retry the request?
625
-
481
+ }
626
482
 
627
- const retry = (_config$retry = config.retry) != null ? _config$retry : 3;
628
- const retryDelay = (_config$retryDelay = config.retryDelay) != null ? _config$retryDelay : defaultRetryDelay;
483
+ // Do we need to retry the request?
484
+ const retry = config.retry ?? 3;
485
+ const retryDelay = config.retryDelay ?? defaultRetryDelay;
629
486
  const delay = typeof retryDelay === 'function' ? retryDelay(failureCount, error) : retryDelay;
630
487
  const shouldRetry = retry === true || typeof retry === 'number' && failureCount < retry || typeof retry === 'function' && retry(failureCount, error);
631
-
632
488
  if (isRetryCancelled || !shouldRetry) {
633
489
  // We are done if the query does not need to be retried
634
490
  reject(error);
635
491
  return;
636
492
  }
493
+ failureCount++;
637
494
 
638
- failureCount++; // Notify on fail
639
-
640
- config.onFail == null ? void 0 : config.onFail(failureCount, error); // Delay
495
+ // Notify on fail
496
+ config.onFail?.(failureCount, error);
641
497
 
642
- sleep(delay) // Pause if the document is not visible or when the device is offline
498
+ // Delay
499
+ sleep(delay)
500
+ // Pause if the document is not visible or when the device is offline
643
501
  .then(() => {
644
502
  if (shouldPause()) {
645
503
  return pause();
646
504
  }
647
-
648
505
  return;
649
506
  }).then(() => {
650
507
  if (isRetryCancelled) {
@@ -654,20 +511,19 @@
654
511
  }
655
512
  });
656
513
  });
657
- }; // Start loop
658
-
514
+ };
659
515
 
516
+ // Start loop
660
517
  if (canFetch(config.networkMode)) {
661
518
  run();
662
519
  } else {
663
520
  pause().then(run);
664
521
  }
665
-
666
522
  return {
667
523
  promise,
668
524
  cancel,
669
525
  continue: () => {
670
- const didContinue = continueFn == null ? void 0 : continueFn();
526
+ const didContinue = continueFn?.();
671
527
  return didContinue ? promise : Promise.resolve();
672
528
  },
673
529
  cancelRetry,
@@ -675,37 +531,30 @@
675
531
  };
676
532
  }
677
533
 
678
- const defaultLogger = console;
534
+ // TYPES
679
535
 
680
536
  function createNotifyManager() {
681
537
  let queue = [];
682
538
  let transactions = 0;
683
-
684
539
  let notifyFn = callback => {
685
540
  callback();
686
541
  };
687
-
688
542
  let batchNotifyFn = callback => {
689
543
  callback();
690
544
  };
691
-
692
545
  const batch = callback => {
693
546
  let result;
694
547
  transactions++;
695
-
696
548
  try {
697
549
  result = callback();
698
550
  } finally {
699
551
  transactions--;
700
-
701
552
  if (!transactions) {
702
553
  flush();
703
554
  }
704
555
  }
705
-
706
556
  return result;
707
557
  };
708
-
709
558
  const schedule = callback => {
710
559
  if (transactions) {
711
560
  queue.push(callback);
@@ -715,11 +564,10 @@
715
564
  });
716
565
  }
717
566
  };
567
+
718
568
  /**
719
569
  * All calls to the wrapped function will be batched.
720
570
  */
721
-
722
-
723
571
  const batchCalls = callback => {
724
572
  return (...args) => {
725
573
  schedule(() => {
@@ -727,11 +575,9 @@
727
575
  });
728
576
  };
729
577
  };
730
-
731
578
  const flush = () => {
732
579
  const originalQueue = queue;
733
580
  queue = [];
734
-
735
581
  if (originalQueue.length) {
736
582
  scheduleMicrotask(() => {
737
583
  batchNotifyFn(() => {
@@ -742,25 +588,22 @@
742
588
  });
743
589
  }
744
590
  };
591
+
745
592
  /**
746
593
  * Use this method to set a custom notify function.
747
594
  * This can be used to for example wrap notifications with `React.act` while running tests.
748
595
  */
749
-
750
-
751
596
  const setNotifyFunction = fn => {
752
597
  notifyFn = fn;
753
598
  };
599
+
754
600
  /**
755
601
  * Use this method to set a custom function to batch notifications together into a single tick.
756
602
  * By default React Query will use the batch function provided by ReactDOM or React Native.
757
603
  */
758
-
759
-
760
604
  const setBatchNotifyFunction = fn => {
761
605
  batchNotifyFn = fn;
762
606
  };
763
-
764
607
  return {
765
608
  batch,
766
609
  batchCalls,
@@ -768,288 +611,253 @@
768
611
  setNotifyFunction,
769
612
  setBatchNotifyFunction
770
613
  };
771
- } // SINGLETON
614
+ }
772
615
 
616
+ // SINGLETON
773
617
  const notifyManager = createNotifyManager();
774
618
 
775
619
  class Removable {
620
+ #gcTimeout;
776
621
  destroy() {
777
622
  this.clearGcTimeout();
778
623
  }
779
-
780
624
  scheduleGc() {
781
625
  this.clearGcTimeout();
782
-
783
- if (isValidTimeout(this.cacheTime)) {
784
- this.gcTimeout = setTimeout(() => {
626
+ if (isValidTimeout(this.gcTime)) {
627
+ this.#gcTimeout = setTimeout(() => {
785
628
  this.optionalRemove();
786
- }, this.cacheTime);
629
+ }, this.gcTime);
787
630
  }
788
631
  }
789
-
790
- updateCacheTime(newCacheTime) {
791
- // Default to 5 minutes (Infinity for server-side) if no cache time is set
792
- this.cacheTime = Math.max(this.cacheTime || 0, newCacheTime != null ? newCacheTime : isServer ? Infinity : 5 * 60 * 1000);
632
+ updateGcTime(newGcTime) {
633
+ // Default to 5 minutes (Infinity for server-side) if no gcTime is set
634
+ this.gcTime = Math.max(this.gcTime || 0, newGcTime ?? (isServer ? Infinity : 5 * 60 * 1000));
793
635
  }
794
-
795
636
  clearGcTimeout() {
796
- if (this.gcTimeout) {
797
- clearTimeout(this.gcTimeout);
798
- this.gcTimeout = undefined;
637
+ if (this.#gcTimeout) {
638
+ clearTimeout(this.#gcTimeout);
639
+ this.#gcTimeout = undefined;
799
640
  }
800
641
  }
801
-
802
642
  }
803
643
 
644
+ // TYPES
645
+
804
646
  // CLASS
647
+
805
648
  class Query extends Removable {
649
+ #initialState;
650
+ #revertState;
651
+ #cache;
652
+ #promise;
653
+ #retryer;
654
+ #observers;
655
+ #defaultOptions;
656
+ #abortSignalConsumed;
806
657
  constructor(config) {
807
658
  super();
808
- this.abortSignalConsumed = false;
809
- this.defaultOptions = config.defaultOptions;
810
- this.setOptions(config.options);
811
- this.observers = [];
812
- this.cache = config.cache;
813
- this.logger = config.logger || defaultLogger;
659
+ this.#abortSignalConsumed = false;
660
+ this.#defaultOptions = config.defaultOptions;
661
+ this.#setOptions(config.options);
662
+ this.#observers = [];
663
+ this.#cache = config.cache;
814
664
  this.queryKey = config.queryKey;
815
665
  this.queryHash = config.queryHash;
816
- this.initialState = config.state || getDefaultState$1(this.options);
817
- this.state = this.initialState;
666
+ this.#initialState = config.state || getDefaultState$1(this.options);
667
+ this.state = this.#initialState;
818
668
  this.scheduleGc();
819
669
  }
820
-
821
670
  get meta() {
822
671
  return this.options.meta;
823
672
  }
824
-
825
- setOptions(options) {
826
- this.options = { ...this.defaultOptions,
673
+ #setOptions(options) {
674
+ this.options = {
675
+ ...this.#defaultOptions,
827
676
  ...options
828
677
  };
829
- this.updateCacheTime(this.options.cacheTime);
678
+ this.updateGcTime(this.options.gcTime);
830
679
  }
831
-
832
680
  optionalRemove() {
833
- if (!this.observers.length && this.state.fetchStatus === 'idle') {
834
- this.cache.remove(this);
681
+ if (!this.#observers.length && this.state.fetchStatus === 'idle') {
682
+ this.#cache.remove(this);
835
683
  }
836
684
  }
837
-
838
685
  setData(newData, options) {
839
- const data = replaceData(this.state.data, newData, this.options); // Set data and mark it as cached
686
+ const data = replaceData(this.state.data, newData, this.options);
840
687
 
841
- this.dispatch({
688
+ // Set data and mark it as cached
689
+ this.#dispatch({
842
690
  data,
843
691
  type: 'success',
844
- dataUpdatedAt: options == null ? void 0 : options.updatedAt,
845
- manual: options == null ? void 0 : options.manual
692
+ dataUpdatedAt: options?.updatedAt,
693
+ manual: options?.manual
846
694
  });
847
695
  return data;
848
696
  }
849
-
850
697
  setState(state, setStateOptions) {
851
- this.dispatch({
698
+ this.#dispatch({
852
699
  type: 'setState',
853
700
  state,
854
701
  setStateOptions
855
702
  });
856
703
  }
857
-
858
704
  cancel(options) {
859
- var _this$retryer;
860
-
861
- const promise = this.promise;
862
- (_this$retryer = this.retryer) == null ? void 0 : _this$retryer.cancel(options);
705
+ const promise = this.#promise;
706
+ this.#retryer?.cancel(options);
863
707
  return promise ? promise.then(noop).catch(noop) : Promise.resolve();
864
708
  }
865
-
866
709
  destroy() {
867
710
  super.destroy();
868
711
  this.cancel({
869
712
  silent: true
870
713
  });
871
714
  }
872
-
873
715
  reset() {
874
716
  this.destroy();
875
- this.setState(this.initialState);
717
+ this.setState(this.#initialState);
876
718
  }
877
-
878
719
  isActive() {
879
- return this.observers.some(observer => observer.options.enabled !== false);
720
+ return this.#observers.some(observer => observer.options.enabled !== false);
880
721
  }
881
-
882
722
  isDisabled() {
883
723
  return this.getObserversCount() > 0 && !this.isActive();
884
724
  }
885
-
886
725
  isStale() {
887
- return this.state.isInvalidated || !this.state.dataUpdatedAt || this.observers.some(observer => observer.getCurrentResult().isStale);
726
+ return this.state.isInvalidated || !this.state.dataUpdatedAt || this.#observers.some(observer => observer.getCurrentResult().isStale);
888
727
  }
889
-
890
728
  isStaleByTime(staleTime = 0) {
891
729
  return this.state.isInvalidated || !this.state.dataUpdatedAt || !timeUntilStale(this.state.dataUpdatedAt, staleTime);
892
730
  }
893
-
894
731
  onFocus() {
895
- var _this$retryer2;
896
-
897
- const observer = this.observers.find(x => x.shouldFetchOnWindowFocus());
898
-
899
- if (observer) {
900
- observer.refetch({
901
- cancelRefetch: false
902
- });
903
- } // Continue fetch if currently paused
904
-
732
+ const observer = this.#observers.find(x => x.shouldFetchOnWindowFocus());
733
+ observer?.refetch({
734
+ cancelRefetch: false
735
+ });
905
736
 
906
- (_this$retryer2 = this.retryer) == null ? void 0 : _this$retryer2.continue();
737
+ // Continue fetch if currently paused
738
+ this.#retryer?.continue();
907
739
  }
908
-
909
740
  onOnline() {
910
- var _this$retryer3;
911
-
912
- const observer = this.observers.find(x => x.shouldFetchOnReconnect());
913
-
914
- if (observer) {
915
- observer.refetch({
916
- cancelRefetch: false
917
- });
918
- } // Continue fetch if currently paused
919
-
741
+ const observer = this.#observers.find(x => x.shouldFetchOnReconnect());
742
+ observer?.refetch({
743
+ cancelRefetch: false
744
+ });
920
745
 
921
- (_this$retryer3 = this.retryer) == null ? void 0 : _this$retryer3.continue();
746
+ // Continue fetch if currently paused
747
+ this.#retryer?.continue();
922
748
  }
923
-
924
749
  addObserver(observer) {
925
- if (this.observers.indexOf(observer) === -1) {
926
- this.observers.push(observer); // Stop the query from being garbage collected
750
+ if (this.#observers.indexOf(observer) === -1) {
751
+ this.#observers.push(observer);
927
752
 
753
+ // Stop the query from being garbage collected
928
754
  this.clearGcTimeout();
929
- this.cache.notify({
755
+ this.#cache.notify({
930
756
  type: 'observerAdded',
931
757
  query: this,
932
758
  observer
933
759
  });
934
760
  }
935
761
  }
936
-
937
762
  removeObserver(observer) {
938
- if (this.observers.indexOf(observer) !== -1) {
939
- this.observers = this.observers.filter(x => x !== observer);
940
-
941
- if (!this.observers.length) {
763
+ if (this.#observers.indexOf(observer) !== -1) {
764
+ this.#observers = this.#observers.filter(x => x !== observer);
765
+ if (!this.#observers.length) {
942
766
  // If the transport layer does not support cancellation
943
767
  // we'll let the query continue so the result can be cached
944
- if (this.retryer) {
945
- if (this.abortSignalConsumed) {
946
- this.retryer.cancel({
768
+ if (this.#retryer) {
769
+ if (this.#abortSignalConsumed) {
770
+ this.#retryer.cancel({
947
771
  revert: true
948
772
  });
949
773
  } else {
950
- this.retryer.cancelRetry();
774
+ this.#retryer.cancelRetry();
951
775
  }
952
776
  }
953
-
954
777
  this.scheduleGc();
955
778
  }
956
-
957
- this.cache.notify({
779
+ this.#cache.notify({
958
780
  type: 'observerRemoved',
959
781
  query: this,
960
782
  observer
961
783
  });
962
784
  }
963
785
  }
964
-
965
786
  getObserversCount() {
966
- return this.observers.length;
787
+ return this.#observers.length;
967
788
  }
968
-
969
789
  invalidate() {
970
790
  if (!this.state.isInvalidated) {
971
- this.dispatch({
791
+ this.#dispatch({
972
792
  type: 'invalidate'
973
793
  });
974
794
  }
975
795
  }
976
-
977
796
  fetch(options, fetchOptions) {
978
- var _this$options$behavio, _context$fetchOptions;
979
-
980
797
  if (this.state.fetchStatus !== 'idle') {
981
- if (this.state.dataUpdatedAt && fetchOptions != null && fetchOptions.cancelRefetch) {
798
+ if (this.state.dataUpdatedAt && fetchOptions?.cancelRefetch) {
982
799
  // Silently cancel current fetch if the user wants to cancel refetches
983
800
  this.cancel({
984
801
  silent: true
985
802
  });
986
- } else if (this.promise) {
987
- var _this$retryer4;
988
-
803
+ } else if (this.#promise) {
989
804
  // make sure that retries that were potentially cancelled due to unmounts can continue
990
- (_this$retryer4 = this.retryer) == null ? void 0 : _this$retryer4.continueRetry(); // Return current promise if we are already fetching
991
-
992
- return this.promise;
805
+ this.#retryer?.continueRetry();
806
+ // Return current promise if we are already fetching
807
+ return this.#promise;
993
808
  }
994
- } // Update config if passed, otherwise the config from the last execution is used
995
-
809
+ }
996
810
 
811
+ // Update config if passed, otherwise the config from the last execution is used
997
812
  if (options) {
998
- this.setOptions(options);
999
- } // Use the options from the first observer with a query function if no function is found.
1000
- // This can happen when the query is hydrated or created with setQueryData.
1001
-
813
+ this.#setOptions(options);
814
+ }
1002
815
 
816
+ // Use the options from the first observer with a query function if no function is found.
817
+ // This can happen when the query is hydrated or created with setQueryData.
1003
818
  if (!this.options.queryFn) {
1004
- const observer = this.observers.find(x => x.options.queryFn);
1005
-
819
+ const observer = this.#observers.find(x => x.options.queryFn);
1006
820
  if (observer) {
1007
- this.setOptions(observer.options);
821
+ this.#setOptions(observer.options);
1008
822
  }
1009
823
  }
1010
-
1011
- if (!Array.isArray(this.options.queryKey)) {
1012
- {
1013
- this.logger.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']");
824
+ {
825
+ if (!Array.isArray(this.options.queryKey)) {
826
+ console.error(`As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`);
1014
827
  }
1015
828
  }
829
+ const abortController = new AbortController();
1016
830
 
1017
- const abortController = getAbortController(); // Create query function context
1018
-
831
+ // Create query function context
1019
832
  const queryFnContext = {
1020
833
  queryKey: this.queryKey,
1021
- pageParam: undefined,
1022
834
  meta: this.meta
1023
- }; // Adds an enumerable signal property to the object that
835
+ };
836
+
837
+ // Adds an enumerable signal property to the object that
1024
838
  // which sets abortSignalConsumed to true when the signal
1025
839
  // is read.
1026
-
1027
840
  const addSignalProperty = object => {
1028
841
  Object.defineProperty(object, 'signal', {
1029
842
  enumerable: true,
1030
843
  get: () => {
1031
- if (abortController) {
1032
- this.abortSignalConsumed = true;
1033
- return abortController.signal;
1034
- }
1035
-
1036
- return undefined;
844
+ this.#abortSignalConsumed = true;
845
+ return abortController.signal;
1037
846
  }
1038
847
  });
1039
848
  };
849
+ addSignalProperty(queryFnContext);
1040
850
 
1041
- addSignalProperty(queryFnContext); // Create fetch function
1042
-
851
+ // Create fetch function
1043
852
  const fetchFn = () => {
1044
853
  if (!this.options.queryFn) {
1045
- return Promise.reject('Missing queryFn');
854
+ return Promise.reject(new Error('Missing queryFn'));
1046
855
  }
1047
-
1048
- this.abortSignalConsumed = false;
856
+ this.#abortSignalConsumed = false;
1049
857
  return this.options.queryFn(queryFnContext);
1050
- }; // Trigger behavior hook
1051
-
858
+ };
1052
859
 
860
+ // Trigger behavior hook
1053
861
  const context = {
1054
862
  fetchOptions,
1055
863
  options: this.options,
@@ -1058,89 +866,74 @@
1058
866
  fetchFn
1059
867
  };
1060
868
  addSignalProperty(context);
1061
- (_this$options$behavio = this.options.behavior) == null ? void 0 : _this$options$behavio.onFetch(context); // Store state in case the current fetch needs to be reverted
1062
-
1063
- this.revertState = this.state; // Set to fetching state if not already in it
869
+ this.options.behavior?.onFetch(context);
1064
870
 
1065
- if (this.state.fetchStatus === 'idle' || this.state.fetchMeta !== ((_context$fetchOptions = context.fetchOptions) == null ? void 0 : _context$fetchOptions.meta)) {
1066
- var _context$fetchOptions2;
871
+ // Store state in case the current fetch needs to be reverted
872
+ this.#revertState = this.state;
1067
873
 
1068
- this.dispatch({
874
+ // Set to fetching state if not already in it
875
+ if (this.state.fetchStatus === 'idle' || this.state.fetchMeta !== context.fetchOptions?.meta) {
876
+ this.#dispatch({
1069
877
  type: 'fetch',
1070
- meta: (_context$fetchOptions2 = context.fetchOptions) == null ? void 0 : _context$fetchOptions2.meta
878
+ meta: context.fetchOptions?.meta
1071
879
  });
1072
880
  }
1073
-
1074
881
  const onError = error => {
1075
882
  // Optimistically update state if needed
1076
883
  if (!(isCancelledError(error) && error.silent)) {
1077
- this.dispatch({
884
+ this.#dispatch({
1078
885
  type: 'error',
1079
886
  error: error
1080
887
  });
1081
888
  }
1082
-
1083
889
  if (!isCancelledError(error)) {
1084
- var _this$cache$config$on, _this$cache$config;
1085
-
1086
890
  // Notify cache callback
1087
- (_this$cache$config$on = (_this$cache$config = this.cache.config).onError) == null ? void 0 : _this$cache$config$on.call(_this$cache$config, error, this);
1088
-
1089
- {
1090
- this.logger.error(error);
1091
- }
891
+ this.#cache.config.onError?.(error, this);
1092
892
  }
1093
-
1094
893
  if (!this.isFetchingOptimistic) {
1095
894
  // Schedule query gc after fetching
1096
895
  this.scheduleGc();
1097
896
  }
1098
-
1099
897
  this.isFetchingOptimistic = false;
1100
- }; // Try to fetch the data
1101
-
898
+ };
1102
899
 
1103
- this.retryer = createRetryer({
900
+ // Try to fetch the data
901
+ this.#retryer = createRetryer({
1104
902
  fn: context.fetchFn,
1105
- abort: abortController == null ? void 0 : abortController.abort.bind(abortController),
903
+ abort: abortController.abort.bind(abortController),
1106
904
  onSuccess: data => {
1107
- var _this$cache$config$on2, _this$cache$config2;
1108
-
1109
905
  if (typeof data === 'undefined') {
1110
906
  {
1111
- this.logger.error("Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: " + this.queryHash);
907
+ console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`);
1112
908
  }
1113
-
1114
909
  onError(new Error('undefined'));
1115
910
  return;
1116
911
  }
912
+ this.setData(data);
1117
913
 
1118
- this.setData(data); // Notify cache callback
1119
-
1120
- (_this$cache$config$on2 = (_this$cache$config2 = this.cache.config).onSuccess) == null ? void 0 : _this$cache$config$on2.call(_this$cache$config2, data, this);
1121
-
914
+ // Notify cache callback
915
+ this.#cache.config.onSuccess?.(data, this);
1122
916
  if (!this.isFetchingOptimistic) {
1123
917
  // Schedule query gc after fetching
1124
918
  this.scheduleGc();
1125
919
  }
1126
-
1127
920
  this.isFetchingOptimistic = false;
1128
921
  },
1129
922
  onError,
1130
923
  onFail: (failureCount, error) => {
1131
- this.dispatch({
924
+ this.#dispatch({
1132
925
  type: 'failed',
1133
926
  failureCount,
1134
927
  error
1135
928
  });
1136
929
  },
1137
930
  onPause: () => {
1138
- this.dispatch({
931
+ this.#dispatch({
1139
932
  type: 'pause'
1140
933
  });
1141
934
  },
1142
935
  onContinue: () => {
1143
- this.dispatch({
936
+ this.#dispatch({
1144
937
  type: 'continue'
1145
938
  });
1146
939
  },
@@ -1148,48 +941,46 @@
1148
941
  retryDelay: context.options.retryDelay,
1149
942
  networkMode: context.options.networkMode
1150
943
  });
1151
- this.promise = this.retryer.promise;
1152
- return this.promise;
944
+ this.#promise = this.#retryer.promise;
945
+ return this.#promise;
1153
946
  }
1154
-
1155
- dispatch(action) {
947
+ #dispatch(action) {
1156
948
  const reducer = state => {
1157
- var _action$meta, _action$dataUpdatedAt;
1158
-
1159
949
  switch (action.type) {
1160
950
  case 'failed':
1161
- return { ...state,
951
+ return {
952
+ ...state,
1162
953
  fetchFailureCount: action.failureCount,
1163
954
  fetchFailureReason: action.error
1164
955
  };
1165
-
1166
956
  case 'pause':
1167
- return { ...state,
957
+ return {
958
+ ...state,
1168
959
  fetchStatus: 'paused'
1169
960
  };
1170
-
1171
961
  case 'continue':
1172
- return { ...state,
962
+ return {
963
+ ...state,
1173
964
  fetchStatus: 'fetching'
1174
965
  };
1175
-
1176
966
  case 'fetch':
1177
- return { ...state,
967
+ return {
968
+ ...state,
1178
969
  fetchFailureCount: 0,
1179
970
  fetchFailureReason: null,
1180
- fetchMeta: (_action$meta = action.meta) != null ? _action$meta : null,
971
+ fetchMeta: action.meta ?? null,
1181
972
  fetchStatus: canFetch(this.options.networkMode) ? 'fetching' : 'paused',
1182
973
  ...(!state.dataUpdatedAt && {
1183
974
  error: null,
1184
- status: 'loading'
975
+ status: 'pending'
1185
976
  })
1186
977
  };
1187
-
1188
978
  case 'success':
1189
- return { ...state,
979
+ return {
980
+ ...state,
1190
981
  data: action.data,
1191
982
  dataUpdateCount: state.dataUpdateCount + 1,
1192
- dataUpdatedAt: (_action$dataUpdatedAt = action.dataUpdatedAt) != null ? _action$dataUpdatedAt : Date.now(),
983
+ dataUpdatedAt: action.dataUpdatedAt ?? Date.now(),
1193
984
  error: null,
1194
985
  isInvalidated: false,
1195
986
  status: 'success',
@@ -1199,16 +990,15 @@
1199
990
  fetchFailureReason: null
1200
991
  })
1201
992
  };
1202
-
1203
993
  case 'error':
1204
994
  const error = action.error;
1205
-
1206
- if (isCancelledError(error) && error.revert && this.revertState) {
1207
- return { ...this.revertState
995
+ if (isCancelledError(error) && error.revert && this.#revertState) {
996
+ return {
997
+ ...this.#revertState
1208
998
  };
1209
999
  }
1210
-
1211
- return { ...state,
1000
+ return {
1001
+ ...state,
1212
1002
  error: error,
1213
1003
  errorUpdateCount: state.errorUpdateCount + 1,
1214
1004
  errorUpdatedAt: Date.now(),
@@ -1217,34 +1007,31 @@
1217
1007
  fetchStatus: 'idle',
1218
1008
  status: 'error'
1219
1009
  };
1220
-
1221
1010
  case 'invalidate':
1222
- return { ...state,
1011
+ return {
1012
+ ...state,
1223
1013
  isInvalidated: true
1224
1014
  };
1225
-
1226
1015
  case 'setState':
1227
- return { ...state,
1016
+ return {
1017
+ ...state,
1228
1018
  ...action.state
1229
1019
  };
1230
1020
  }
1231
1021
  };
1232
-
1233
1022
  this.state = reducer(this.state);
1234
1023
  notifyManager.batch(() => {
1235
- this.observers.forEach(observer => {
1024
+ this.#observers.forEach(observer => {
1236
1025
  observer.onQueryUpdate(action);
1237
1026
  });
1238
- this.cache.notify({
1027
+ this.#cache.notify({
1239
1028
  query: this,
1240
1029
  type: 'updated',
1241
1030
  action
1242
1031
  });
1243
1032
  });
1244
1033
  }
1245
-
1246
1034
  }
1247
-
1248
1035
  function getDefaultState$1(options) {
1249
1036
  const data = typeof options.initialData === 'function' ? options.initialData() : options.initialData;
1250
1037
  const hasData = typeof data !== 'undefined';
@@ -1252,7 +1039,7 @@
1252
1039
  return {
1253
1040
  data,
1254
1041
  dataUpdateCount: 0,
1255
- dataUpdatedAt: hasData ? initialDataUpdatedAt != null ? initialDataUpdatedAt : Date.now() : 0,
1042
+ dataUpdatedAt: hasData ? initialDataUpdatedAt ?? Date.now() : 0,
1256
1043
  error: null,
1257
1044
  errorUpdateCount: 0,
1258
1045
  errorUpdatedAt: 0,
@@ -1260,31 +1047,27 @@
1260
1047
  fetchFailureReason: null,
1261
1048
  fetchMeta: null,
1262
1049
  isInvalidated: false,
1263
- status: hasData ? 'success' : 'loading',
1050
+ status: hasData ? 'success' : 'pending',
1264
1051
  fetchStatus: 'idle'
1265
1052
  };
1266
1053
  }
1267
1054
 
1268
1055
  // CLASS
1056
+
1269
1057
  class QueryCache extends Subscribable {
1270
- constructor(config) {
1058
+ #queries;
1059
+ constructor(config = {}) {
1271
1060
  super();
1272
- this.config = config || {};
1273
- this.queries = [];
1274
- this.queriesMap = {};
1061
+ this.config = config;
1062
+ this.#queries = config.createStore?.() ?? new Map();
1275
1063
  }
1276
-
1277
1064
  build(client, options, state) {
1278
- var _options$queryHash;
1279
-
1280
1065
  const queryKey = options.queryKey;
1281
- const queryHash = (_options$queryHash = options.queryHash) != null ? _options$queryHash : hashQueryKeyByOptions(queryKey, options);
1066
+ const queryHash = options.queryHash ?? hashQueryKeyByOptions(queryKey, options);
1282
1067
  let query = this.get(queryHash);
1283
-
1284
1068
  if (!query) {
1285
1069
  query = new Query({
1286
1070
  cache: this,
1287
- logger: client.getLogger(),
1288
1071
  queryKey,
1289
1072
  queryHash,
1290
1073
  options: client.defaultQueryOptions(options),
@@ -1293,70 +1076,53 @@
1293
1076
  });
1294
1077
  this.add(query);
1295
1078
  }
1296
-
1297
1079
  return query;
1298
1080
  }
1299
-
1300
1081
  add(query) {
1301
- if (!this.queriesMap[query.queryHash]) {
1302
- this.queriesMap[query.queryHash] = query;
1303
- this.queries.push(query);
1082
+ if (!this.#queries.has(query.queryHash)) {
1083
+ this.#queries.set(query.queryHash, query);
1304
1084
  this.notify({
1305
1085
  type: 'added',
1306
1086
  query
1307
1087
  });
1308
1088
  }
1309
1089
  }
1310
-
1311
1090
  remove(query) {
1312
- const queryInMap = this.queriesMap[query.queryHash];
1313
-
1091
+ const queryInMap = this.#queries.get(query.queryHash);
1314
1092
  if (queryInMap) {
1315
1093
  query.destroy();
1316
- this.queries = this.queries.filter(x => x !== query);
1317
-
1318
1094
  if (queryInMap === query) {
1319
- delete this.queriesMap[query.queryHash];
1095
+ this.#queries.delete(query.queryHash);
1320
1096
  }
1321
-
1322
1097
  this.notify({
1323
1098
  type: 'removed',
1324
1099
  query
1325
1100
  });
1326
1101
  }
1327
1102
  }
1328
-
1329
1103
  clear() {
1330
1104
  notifyManager.batch(() => {
1331
- this.queries.forEach(query => {
1105
+ this.getAll().forEach(query => {
1332
1106
  this.remove(query);
1333
1107
  });
1334
1108
  });
1335
1109
  }
1336
-
1337
1110
  get(queryHash) {
1338
- return this.queriesMap[queryHash];
1111
+ return this.#queries.get(queryHash);
1339
1112
  }
1340
-
1341
1113
  getAll() {
1342
- return this.queries;
1114
+ return [...this.#queries.values()];
1343
1115
  }
1344
-
1345
- find(arg1, arg2) {
1346
- const [filters] = parseFilterArgs(arg1, arg2);
1347
-
1116
+ find(filters) {
1348
1117
  if (typeof filters.exact === 'undefined') {
1349
1118
  filters.exact = true;
1350
1119
  }
1351
-
1352
- return this.queries.find(query => matchQuery(filters, query));
1120
+ return this.getAll().find(query => matchQuery(filters, query));
1353
1121
  }
1354
-
1355
- findAll(arg1, arg2) {
1356
- const [filters] = parseFilterArgs(arg1, arg2);
1357
- return Object.keys(filters).length > 0 ? this.queries.filter(query => matchQuery(filters, query)) : this.queries;
1122
+ findAll(filters = {}) {
1123
+ const queries = this.getAll();
1124
+ return Object.keys(filters).length > 0 ? queries.filter(query => matchQuery(filters, query)) : queries;
1358
1125
  }
1359
-
1360
1126
  notify(event) {
1361
1127
  notifyManager.batch(() => {
1362
1128
  this.listeners.forEach(listener => {
@@ -1364,218 +1130,190 @@
1364
1130
  });
1365
1131
  });
1366
1132
  }
1367
-
1368
1133
  onFocus() {
1369
1134
  notifyManager.batch(() => {
1370
- this.queries.forEach(query => {
1135
+ this.getAll().forEach(query => {
1371
1136
  query.onFocus();
1372
1137
  });
1373
1138
  });
1374
1139
  }
1375
-
1376
1140
  onOnline() {
1377
1141
  notifyManager.batch(() => {
1378
- this.queries.forEach(query => {
1142
+ this.getAll().forEach(query => {
1379
1143
  query.onOnline();
1380
1144
  });
1381
1145
  });
1382
1146
  }
1383
-
1384
1147
  }
1385
1148
 
1149
+ // TYPES
1150
+
1386
1151
  // CLASS
1152
+
1387
1153
  class Mutation extends Removable {
1154
+ #observers;
1155
+ #mutationCache;
1156
+ #retryer;
1388
1157
  constructor(config) {
1389
1158
  super();
1390
- this.options = { ...config.defaultOptions,
1391
- ...config.options
1392
- };
1159
+ this.options = config.options;
1393
1160
  this.mutationId = config.mutationId;
1394
- this.mutationCache = config.mutationCache;
1395
- this.logger = config.logger || defaultLogger;
1396
- this.observers = [];
1161
+ this.#mutationCache = config.mutationCache;
1162
+ this.#observers = [];
1397
1163
  this.state = config.state || getDefaultState();
1398
- this.updateCacheTime(this.options.cacheTime);
1164
+ this.updateGcTime(this.options.gcTime);
1399
1165
  this.scheduleGc();
1400
1166
  }
1401
-
1402
1167
  get meta() {
1403
1168
  return this.options.meta;
1404
1169
  }
1405
-
1406
- setState(state) {
1407
- this.dispatch({
1408
- type: 'setState',
1409
- state
1410
- });
1411
- }
1412
-
1413
1170
  addObserver(observer) {
1414
- if (this.observers.indexOf(observer) === -1) {
1415
- this.observers.push(observer); // Stop the mutation from being garbage collected
1171
+ if (this.#observers.indexOf(observer) === -1) {
1172
+ this.#observers.push(observer);
1416
1173
 
1174
+ // Stop the mutation from being garbage collected
1417
1175
  this.clearGcTimeout();
1418
- this.mutationCache.notify({
1176
+ this.#mutationCache.notify({
1419
1177
  type: 'observerAdded',
1420
1178
  mutation: this,
1421
1179
  observer
1422
1180
  });
1423
1181
  }
1424
1182
  }
1425
-
1426
1183
  removeObserver(observer) {
1427
- this.observers = this.observers.filter(x => x !== observer);
1184
+ this.#observers = this.#observers.filter(x => x !== observer);
1428
1185
  this.scheduleGc();
1429
- this.mutationCache.notify({
1186
+ this.#mutationCache.notify({
1430
1187
  type: 'observerRemoved',
1431
1188
  mutation: this,
1432
1189
  observer
1433
1190
  });
1434
1191
  }
1435
-
1436
1192
  optionalRemove() {
1437
- if (!this.observers.length) {
1438
- if (this.state.status === 'loading') {
1193
+ if (!this.#observers.length) {
1194
+ if (this.state.status === 'pending') {
1439
1195
  this.scheduleGc();
1440
1196
  } else {
1441
- this.mutationCache.remove(this);
1197
+ this.#mutationCache.remove(this);
1442
1198
  }
1443
1199
  }
1444
1200
  }
1445
-
1446
1201
  continue() {
1447
- var _this$retryer$continu, _this$retryer;
1448
-
1449
- return (_this$retryer$continu = (_this$retryer = this.retryer) == null ? void 0 : _this$retryer.continue()) != null ? _this$retryer$continu : this.execute();
1202
+ return this.#retryer?.continue() ??
1203
+ // continuing a mutation assumes that variables are set, mutation must have been dehydrated before
1204
+ this.execute(this.state.variables);
1450
1205
  }
1451
-
1452
- async execute() {
1206
+ async execute(variables) {
1453
1207
  const executeMutation = () => {
1454
- var _this$options$retry;
1455
-
1456
- this.retryer = createRetryer({
1208
+ this.#retryer = createRetryer({
1457
1209
  fn: () => {
1458
1210
  if (!this.options.mutationFn) {
1459
- return Promise.reject('No mutationFn found');
1211
+ return Promise.reject(new Error('No mutationFn found'));
1460
1212
  }
1461
-
1462
- return this.options.mutationFn(this.state.variables);
1213
+ return this.options.mutationFn(variables);
1463
1214
  },
1464
1215
  onFail: (failureCount, error) => {
1465
- this.dispatch({
1216
+ this.#dispatch({
1466
1217
  type: 'failed',
1467
1218
  failureCount,
1468
1219
  error
1469
1220
  });
1470
1221
  },
1471
1222
  onPause: () => {
1472
- this.dispatch({
1223
+ this.#dispatch({
1473
1224
  type: 'pause'
1474
1225
  });
1475
1226
  },
1476
1227
  onContinue: () => {
1477
- this.dispatch({
1228
+ this.#dispatch({
1478
1229
  type: 'continue'
1479
1230
  });
1480
1231
  },
1481
- retry: (_this$options$retry = this.options.retry) != null ? _this$options$retry : 0,
1232
+ retry: this.options.retry ?? 0,
1482
1233
  retryDelay: this.options.retryDelay,
1483
1234
  networkMode: this.options.networkMode
1484
1235
  });
1485
- return this.retryer.promise;
1236
+ return this.#retryer.promise;
1486
1237
  };
1487
-
1488
- const restored = this.state.status === 'loading';
1489
-
1238
+ const restored = this.state.status === 'pending';
1490
1239
  try {
1491
- var _this$mutationCache$c3, _this$mutationCache$c4, _this$options$onSucce, _this$options2, _this$options$onSettl, _this$options3;
1492
-
1493
1240
  if (!restored) {
1494
- var _this$mutationCache$c, _this$mutationCache$c2, _this$options$onMutat, _this$options;
1495
-
1496
- this.dispatch({
1497
- type: 'loading',
1498
- variables: this.options.variables
1499
- }); // Notify cache callback
1500
-
1501
- await ((_this$mutationCache$c = (_this$mutationCache$c2 = this.mutationCache.config).onMutate) == null ? void 0 : _this$mutationCache$c.call(_this$mutationCache$c2, this.state.variables, this));
1502
- const context = await ((_this$options$onMutat = (_this$options = this.options).onMutate) == null ? void 0 : _this$options$onMutat.call(_this$options, this.state.variables));
1503
-
1241
+ this.#dispatch({
1242
+ type: 'pending',
1243
+ variables
1244
+ });
1245
+ // Notify cache callback
1246
+ await this.#mutationCache.config.onMutate?.(variables, this);
1247
+ const context = await this.options.onMutate?.(variables);
1504
1248
  if (context !== this.state.context) {
1505
- this.dispatch({
1506
- type: 'loading',
1249
+ this.#dispatch({
1250
+ type: 'pending',
1507
1251
  context,
1508
- variables: this.state.variables
1252
+ variables
1509
1253
  });
1510
1254
  }
1511
1255
  }
1256
+ const data = await executeMutation();
1512
1257
 
1513
- const data = await executeMutation(); // Notify cache callback
1514
-
1515
- await ((_this$mutationCache$c3 = (_this$mutationCache$c4 = this.mutationCache.config).onSuccess) == null ? void 0 : _this$mutationCache$c3.call(_this$mutationCache$c4, data, this.state.variables, this.state.context, this));
1516
- await ((_this$options$onSucce = (_this$options2 = this.options).onSuccess) == null ? void 0 : _this$options$onSucce.call(_this$options2, data, this.state.variables, this.state.context));
1517
- await ((_this$options$onSettl = (_this$options3 = this.options).onSettled) == null ? void 0 : _this$options$onSettl.call(_this$options3, data, null, this.state.variables, this.state.context));
1518
- this.dispatch({
1258
+ // Notify cache callback
1259
+ await this.#mutationCache.config.onSuccess?.(data, variables, this.state.context, this);
1260
+ await this.options.onSuccess?.(data, variables, this.state.context);
1261
+ await this.options.onSettled?.(data, null, variables, this.state.context);
1262
+ this.#dispatch({
1519
1263
  type: 'success',
1520
1264
  data
1521
1265
  });
1522
1266
  return data;
1523
1267
  } catch (error) {
1524
1268
  try {
1525
- var _this$mutationCache$c5, _this$mutationCache$c6, _this$options$onError, _this$options4, _this$options$onSettl2, _this$options5;
1526
-
1527
1269
  // Notify cache callback
1528
- await ((_this$mutationCache$c5 = (_this$mutationCache$c6 = this.mutationCache.config).onError) == null ? void 0 : _this$mutationCache$c5.call(_this$mutationCache$c6, error, this.state.variables, this.state.context, this));
1529
-
1530
- if ("development" !== 'production') {
1531
- this.logger.error(error);
1532
- }
1533
-
1534
- await ((_this$options$onError = (_this$options4 = this.options).onError) == null ? void 0 : _this$options$onError.call(_this$options4, error, this.state.variables, this.state.context));
1535
- await ((_this$options$onSettl2 = (_this$options5 = this.options).onSettled) == null ? void 0 : _this$options$onSettl2.call(_this$options5, undefined, error, this.state.variables, this.state.context));
1270
+ await this.#mutationCache.config.onError?.(error, variables, this.state.context, this);
1271
+ await this.options.onError?.(error, variables, this.state.context);
1272
+ await this.options.onSettled?.(undefined, error, variables, this.state.context);
1536
1273
  throw error;
1537
1274
  } finally {
1538
- this.dispatch({
1275
+ this.#dispatch({
1539
1276
  type: 'error',
1540
1277
  error: error
1541
1278
  });
1542
1279
  }
1543
1280
  }
1544
1281
  }
1545
-
1546
- dispatch(action) {
1282
+ #dispatch(action) {
1547
1283
  const reducer = state => {
1548
1284
  switch (action.type) {
1549
1285
  case 'failed':
1550
- return { ...state,
1286
+ return {
1287
+ ...state,
1551
1288
  failureCount: action.failureCount,
1552
1289
  failureReason: action.error
1553
1290
  };
1554
-
1555
1291
  case 'pause':
1556
- return { ...state,
1292
+ return {
1293
+ ...state,
1557
1294
  isPaused: true
1558
1295
  };
1559
-
1560
1296
  case 'continue':
1561
- return { ...state,
1297
+ return {
1298
+ ...state,
1562
1299
  isPaused: false
1563
1300
  };
1564
-
1565
- case 'loading':
1566
- return { ...state,
1301
+ case 'pending':
1302
+ return {
1303
+ ...state,
1567
1304
  context: action.context,
1568
1305
  data: undefined,
1569
1306
  failureCount: 0,
1570
1307
  failureReason: null,
1571
1308
  error: null,
1572
1309
  isPaused: !canFetch(this.options.networkMode),
1573
- status: 'loading',
1574
- variables: action.variables
1310
+ status: 'pending',
1311
+ variables: action.variables,
1312
+ submittedAt: Date.now()
1575
1313
  };
1576
-
1577
1314
  case 'success':
1578
- return { ...state,
1315
+ return {
1316
+ ...state,
1579
1317
  data: action.data,
1580
1318
  failureCount: 0,
1581
1319
  failureReason: null,
@@ -1583,9 +1321,9 @@
1583
1321
  status: 'success',
1584
1322
  isPaused: false
1585
1323
  };
1586
-
1587
1324
  case 'error':
1588
- return { ...state,
1325
+ return {
1326
+ ...state,
1589
1327
  data: undefined,
1590
1328
  error: action.error,
1591
1329
  failureCount: state.failureCount + 1,
@@ -1593,27 +1331,20 @@
1593
1331
  isPaused: false,
1594
1332
  status: 'error'
1595
1333
  };
1596
-
1597
- case 'setState':
1598
- return { ...state,
1599
- ...action.state
1600
- };
1601
1334
  }
1602
1335
  };
1603
-
1604
1336
  this.state = reducer(this.state);
1605
1337
  notifyManager.batch(() => {
1606
- this.observers.forEach(observer => {
1338
+ this.#observers.forEach(observer => {
1607
1339
  observer.onMutationUpdate(action);
1608
1340
  });
1609
- this.mutationCache.notify({
1341
+ this.#mutationCache.notify({
1610
1342
  mutation: this,
1611
1343
  type: 'updated',
1612
1344
  action
1613
1345
  });
1614
1346
  });
1615
1347
  }
1616
-
1617
1348
  }
1618
1349
  function getDefaultState() {
1619
1350
  return {
@@ -1624,72 +1355,68 @@
1624
1355
  failureReason: null,
1625
1356
  isPaused: false,
1626
1357
  status: 'idle',
1627
- variables: undefined
1358
+ variables: undefined,
1359
+ submittedAt: 0
1628
1360
  };
1629
1361
  }
1630
1362
 
1363
+ // TYPES
1364
+
1631
1365
  // CLASS
1366
+
1632
1367
  class MutationCache extends Subscribable {
1633
- constructor(config) {
1368
+ #mutations;
1369
+ #mutationId;
1370
+ #resuming;
1371
+ constructor(config = {}) {
1634
1372
  super();
1635
- this.config = config || {};
1636
- this.mutations = [];
1637
- this.mutationId = 0;
1373
+ this.config = config;
1374
+ this.#mutations = [];
1375
+ this.#mutationId = 0;
1638
1376
  }
1639
-
1640
1377
  build(client, options, state) {
1641
1378
  const mutation = new Mutation({
1642
1379
  mutationCache: this,
1643
- logger: client.getLogger(),
1644
- mutationId: ++this.mutationId,
1380
+ mutationId: ++this.#mutationId,
1645
1381
  options: client.defaultMutationOptions(options),
1646
- state,
1647
- defaultOptions: options.mutationKey ? client.getMutationDefaults(options.mutationKey) : undefined
1382
+ state
1648
1383
  });
1649
1384
  this.add(mutation);
1650
1385
  return mutation;
1651
1386
  }
1652
-
1653
1387
  add(mutation) {
1654
- this.mutations.push(mutation);
1388
+ this.#mutations.push(mutation);
1655
1389
  this.notify({
1656
1390
  type: 'added',
1657
1391
  mutation
1658
1392
  });
1659
1393
  }
1660
-
1661
1394
  remove(mutation) {
1662
- this.mutations = this.mutations.filter(x => x !== mutation);
1395
+ this.#mutations = this.#mutations.filter(x => x !== mutation);
1663
1396
  this.notify({
1664
1397
  type: 'removed',
1665
1398
  mutation
1666
1399
  });
1667
1400
  }
1668
-
1669
1401
  clear() {
1670
1402
  notifyManager.batch(() => {
1671
- this.mutations.forEach(mutation => {
1403
+ this.#mutations.forEach(mutation => {
1672
1404
  this.remove(mutation);
1673
1405
  });
1674
1406
  });
1675
1407
  }
1676
-
1677
1408
  getAll() {
1678
- return this.mutations;
1409
+ return this.#mutations;
1679
1410
  }
1680
-
1681
1411
  find(filters) {
1682
1412
  if (typeof filters.exact === 'undefined') {
1683
1413
  filters.exact = true;
1684
1414
  }
1685
-
1686
- return this.mutations.find(mutation => matchMutation(filters, mutation));
1415
+ return this.#mutations.find(mutation => matchMutation(filters, mutation));
1687
1416
  }
1688
-
1689
- findAll(filters) {
1690
- return this.mutations.filter(mutation => matchMutation(filters, mutation));
1417
+ findAll(filters = {}) {
1418
+ return this.#mutations.filter(mutation => matchMutation(filters, mutation));
1691
1419
  }
1692
-
1693
1420
  notify(event) {
1694
1421
  notifyManager.batch(() => {
1695
1422
  this.listeners.forEach(listener => {
@@ -1697,76 +1424,65 @@
1697
1424
  });
1698
1425
  });
1699
1426
  }
1700
-
1701
1427
  resumePausedMutations() {
1702
- var _this$resuming;
1703
-
1704
- this.resuming = ((_this$resuming = this.resuming) != null ? _this$resuming : Promise.resolve()).then(() => {
1705
- const pausedMutations = this.mutations.filter(x => x.state.isPaused);
1428
+ this.#resuming = (this.#resuming ?? Promise.resolve()).then(() => {
1429
+ const pausedMutations = this.#mutations.filter(x => x.state.isPaused);
1706
1430
  return notifyManager.batch(() => pausedMutations.reduce((promise, mutation) => promise.then(() => mutation.continue().catch(noop)), Promise.resolve()));
1707
1431
  }).then(() => {
1708
- this.resuming = undefined;
1432
+ this.#resuming = undefined;
1709
1433
  });
1710
- return this.resuming;
1434
+ return this.#resuming;
1711
1435
  }
1712
-
1713
1436
  }
1714
1437
 
1715
1438
  function infiniteQueryBehavior() {
1716
1439
  return {
1717
1440
  onFetch: context => {
1718
1441
  context.fetchFn = () => {
1719
- var _context$fetchOptions, _context$fetchOptions2, _context$fetchOptions3, _context$fetchOptions4, _context$state$data, _context$state$data2;
1720
-
1721
- const refetchPage = (_context$fetchOptions = context.fetchOptions) == null ? void 0 : (_context$fetchOptions2 = _context$fetchOptions.meta) == null ? void 0 : _context$fetchOptions2.refetchPage;
1722
- const fetchMore = (_context$fetchOptions3 = context.fetchOptions) == null ? void 0 : (_context$fetchOptions4 = _context$fetchOptions3.meta) == null ? void 0 : _context$fetchOptions4.fetchMore;
1723
- const pageParam = fetchMore == null ? void 0 : fetchMore.pageParam;
1724
- const isFetchingNextPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'forward';
1725
- const isFetchingPreviousPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'backward';
1726
- const oldPages = ((_context$state$data = context.state.data) == null ? void 0 : _context$state$data.pages) || [];
1727
- const oldPageParams = ((_context$state$data2 = context.state.data) == null ? void 0 : _context$state$data2.pageParams) || [];
1442
+ const options = context.options;
1443
+ const direction = context.fetchOptions?.meta?.fetchMore?.direction;
1444
+ const oldPages = context.state.data?.pages || [];
1445
+ const oldPageParams = context.state.data?.pageParams || [];
1728
1446
  let newPageParams = oldPageParams;
1729
1447
  let cancelled = false;
1730
-
1731
1448
  const addSignalProperty = object => {
1732
1449
  Object.defineProperty(object, 'signal', {
1733
1450
  enumerable: true,
1734
1451
  get: () => {
1735
- var _context$signal;
1736
-
1737
- if ((_context$signal = context.signal) != null && _context$signal.aborted) {
1452
+ if (context.signal.aborted) {
1738
1453
  cancelled = true;
1739
1454
  } else {
1740
- var _context$signal2;
1741
-
1742
- (_context$signal2 = context.signal) == null ? void 0 : _context$signal2.addEventListener('abort', () => {
1455
+ context.signal.addEventListener('abort', () => {
1743
1456
  cancelled = true;
1744
1457
  });
1745
1458
  }
1746
-
1747
1459
  return context.signal;
1748
1460
  }
1749
1461
  });
1750
- }; // Get query function
1751
-
1752
-
1753
- const queryFn = context.options.queryFn || (() => Promise.reject('Missing queryFn'));
1462
+ };
1754
1463
 
1464
+ // Get query function
1465
+ const queryFn = context.options.queryFn || (() => Promise.reject(new Error('Missing queryFn')));
1755
1466
  const buildNewPages = (pages, param, page, previous) => {
1756
- newPageParams = previous ? [param, ...newPageParams] : [...newPageParams, param];
1757
- return previous ? [page, ...pages] : [...pages, page];
1758
- }; // Create function to fetch a page
1759
-
1467
+ const {
1468
+ maxPages
1469
+ } = context.options;
1470
+ if (previous) {
1471
+ newPageParams = addToStart(newPageParams, param, maxPages);
1472
+ return addToStart(pages, page, maxPages);
1473
+ }
1474
+ newPageParams = addToEnd(newPageParams, param, maxPages);
1475
+ return addToEnd(pages, page, maxPages);
1476
+ };
1760
1477
 
1761
- const fetchPage = (pages, manual, param, previous) => {
1478
+ // Create function to fetch a page
1479
+ const fetchPage = (pages, param, previous) => {
1762
1480
  if (cancelled) {
1763
- return Promise.reject('Cancelled');
1481
+ return Promise.reject();
1764
1482
  }
1765
-
1766
- if (typeof param === 'undefined' && !manual && pages.length) {
1483
+ if (typeof param === 'undefined' && pages.length) {
1767
1484
  return Promise.resolve(pages);
1768
1485
  }
1769
-
1770
1486
  const queryFnContext = {
1771
1487
  queryKey: context.queryKey,
1772
1488
  pageParam: param,
@@ -1777,43 +1493,35 @@
1777
1493
  const promise = Promise.resolve(queryFnResult).then(page => buildNewPages(pages, param, page, previous));
1778
1494
  return promise;
1779
1495
  };
1496
+ let promise;
1780
1497
 
1781
- let promise; // Fetch first page?
1782
-
1498
+ // Fetch first page?
1783
1499
  if (!oldPages.length) {
1784
- promise = fetchPage([]);
1785
- } // Fetch next page?
1786
- else if (isFetchingNextPage) {
1787
- const manual = typeof pageParam !== 'undefined';
1788
- const param = manual ? pageParam : getNextPageParam(context.options, oldPages);
1789
- promise = fetchPage(oldPages, manual, param);
1790
- } // Fetch previous page?
1791
- else if (isFetchingPreviousPage) {
1792
- const manual = typeof pageParam !== 'undefined';
1793
- const param = manual ? pageParam : getPreviousPageParam(context.options, oldPages);
1794
- promise = fetchPage(oldPages, manual, param, true);
1795
- } // Refetch pages
1500
+ promise = fetchPage([], options.defaultPageParam);
1501
+ }
1502
+
1503
+ // fetch next / previous page?
1504
+ else if (direction) {
1505
+ const previous = direction === 'backward';
1506
+ const param = previous ? getPreviousPageParam(options, oldPages) : getNextPageParam(options, oldPages);
1507
+ promise = fetchPage(oldPages, param, previous);
1508
+ }
1509
+
1510
+ // Refetch pages
1796
1511
  else {
1797
1512
  newPageParams = [];
1798
- const manual = typeof context.options.getNextPageParam === 'undefined';
1799
- const shouldFetchFirstPage = refetchPage && oldPages[0] ? refetchPage(oldPages[0], 0, oldPages) : true; // Fetch first page
1800
1513
 
1801
- promise = shouldFetchFirstPage ? fetchPage([], manual, oldPageParams[0]) : Promise.resolve(buildNewPages([], oldPageParams[0], oldPages[0])); // Fetch remaining pages
1514
+ // Fetch first page
1515
+ promise = fetchPage([], oldPageParams[0]);
1802
1516
 
1517
+ // Fetch remaining pages
1803
1518
  for (let i = 1; i < oldPages.length; i++) {
1804
1519
  promise = promise.then(pages => {
1805
- const shouldFetchNextPage = refetchPage && oldPages[i] ? refetchPage(oldPages[i], i, oldPages) : true;
1806
-
1807
- if (shouldFetchNextPage) {
1808
- const param = manual ? oldPageParams[i] : getNextPageParam(context.options, pages);
1809
- return fetchPage(pages, manual, param);
1810
- }
1811
-
1812
- return Promise.resolve(buildNewPages(pages, oldPageParams[i], oldPages[i]));
1520
+ const param = getNextPageParam(options, pages);
1521
+ return fetchPage(pages, param);
1813
1522
  });
1814
1523
  }
1815
1524
  }
1816
-
1817
1525
  const finalPromise = promise.then(pages => ({
1818
1526
  pages,
1819
1527
  pageParams: newPageParams
@@ -1824,108 +1532,94 @@
1824
1532
  };
1825
1533
  }
1826
1534
  function getNextPageParam(options, pages) {
1827
- return options.getNextPageParam == null ? void 0 : options.getNextPageParam(pages[pages.length - 1], pages);
1535
+ return options.getNextPageParam(pages[pages.length - 1], pages);
1828
1536
  }
1829
1537
  function getPreviousPageParam(options, pages) {
1830
- return options.getPreviousPageParam == null ? void 0 : options.getPreviousPageParam(pages[0], pages);
1538
+ return options.getPreviousPageParam?.(pages[0], pages);
1831
1539
  }
1540
+
1832
1541
  /**
1833
1542
  * Checks if there is a next page.
1834
- * Returns `undefined` if it cannot be determined.
1835
1543
  */
1836
-
1837
1544
  function hasNextPage(options, pages) {
1838
- if (options.getNextPageParam && Array.isArray(pages)) {
1839
- const nextPageParam = getNextPageParam(options, pages);
1840
- return typeof nextPageParam !== 'undefined' && nextPageParam !== null && nextPageParam !== false;
1841
- }
1842
-
1843
- return;
1545
+ if (!pages) return false;
1546
+ return typeof getNextPageParam(options, pages) !== 'undefined';
1844
1547
  }
1548
+
1845
1549
  /**
1846
1550
  * Checks if there is a previous page.
1847
- * Returns `undefined` if it cannot be determined.
1848
1551
  */
1849
-
1850
1552
  function hasPreviousPage(options, pages) {
1851
- if (options.getPreviousPageParam && Array.isArray(pages)) {
1852
- const previousPageParam = getPreviousPageParam(options, pages);
1853
- return typeof previousPageParam !== 'undefined' && previousPageParam !== null && previousPageParam !== false;
1854
- }
1855
-
1856
- return;
1553
+ if (!pages || !options.getPreviousPageParam) return false;
1554
+ return typeof getPreviousPageParam(options, pages) !== 'undefined';
1857
1555
  }
1858
1556
 
1859
1557
  // CLASS
1558
+
1860
1559
  class QueryClient {
1560
+ #queryCache;
1561
+ #mutationCache;
1562
+ #defaultOptions;
1563
+ #queryDefaults;
1564
+ #mutationDefaults;
1565
+ #mountCount;
1566
+ #unsubscribeFocus;
1567
+ #unsubscribeOnline;
1861
1568
  constructor(config = {}) {
1862
- this.queryCache = config.queryCache || new QueryCache();
1863
- this.mutationCache = config.mutationCache || new MutationCache();
1864
- this.logger = config.logger || defaultLogger;
1865
- this.defaultOptions = config.defaultOptions || {};
1866
- this.queryDefaults = [];
1867
- this.mutationDefaults = [];
1868
- this.mountCount = 0;
1869
-
1870
- if (config.logger) {
1871
- this.logger.error("Passing a custom logger has been deprecated and will be removed in the next major version.");
1872
- }
1569
+ this.#queryCache = config.queryCache || new QueryCache();
1570
+ this.#mutationCache = config.mutationCache || new MutationCache();
1571
+ this.#defaultOptions = config.defaultOptions || {};
1572
+ this.#queryDefaults = new Map();
1573
+ this.#mutationDefaults = new Map();
1574
+ this.#mountCount = 0;
1873
1575
  }
1874
-
1875
1576
  mount() {
1876
- this.mountCount++;
1877
- if (this.mountCount !== 1) return;
1878
- this.unsubscribeFocus = focusManager.subscribe(() => {
1577
+ this.#mountCount++;
1578
+ if (this.#mountCount !== 1) return;
1579
+ this.#unsubscribeFocus = focusManager.subscribe(() => {
1879
1580
  if (focusManager.isFocused()) {
1880
1581
  this.resumePausedMutations();
1881
- this.queryCache.onFocus();
1582
+ this.#queryCache.onFocus();
1882
1583
  }
1883
1584
  });
1884
- this.unsubscribeOnline = onlineManager.subscribe(() => {
1585
+ this.#unsubscribeOnline = onlineManager.subscribe(() => {
1885
1586
  if (onlineManager.isOnline()) {
1886
1587
  this.resumePausedMutations();
1887
- this.queryCache.onOnline();
1588
+ this.#queryCache.onOnline();
1888
1589
  }
1889
1590
  });
1890
1591
  }
1891
-
1892
1592
  unmount() {
1893
- var _this$unsubscribeFocu, _this$unsubscribeOnli;
1894
-
1895
- this.mountCount--;
1896
- if (this.mountCount !== 0) return;
1897
- (_this$unsubscribeFocu = this.unsubscribeFocus) == null ? void 0 : _this$unsubscribeFocu.call(this);
1898
- this.unsubscribeFocus = undefined;
1899
- (_this$unsubscribeOnli = this.unsubscribeOnline) == null ? void 0 : _this$unsubscribeOnli.call(this);
1900
- this.unsubscribeOnline = undefined;
1901
- }
1902
-
1903
- isFetching(arg1, arg2) {
1904
- const [filters] = parseFilterArgs(arg1, arg2);
1905
- filters.fetchStatus = 'fetching';
1906
- return this.queryCache.findAll(filters).length;
1593
+ this.#mountCount--;
1594
+ if (this.#mountCount !== 0) return;
1595
+ this.#unsubscribeFocus?.();
1596
+ this.#unsubscribeFocus = undefined;
1597
+ this.#unsubscribeOnline?.();
1598
+ this.#unsubscribeOnline = undefined;
1599
+ }
1600
+ isFetching(filters) {
1601
+ return this.#queryCache.findAll({
1602
+ ...filters,
1603
+ fetchStatus: 'fetching'
1604
+ }).length;
1907
1605
  }
1908
-
1909
1606
  isMutating(filters) {
1910
- return this.mutationCache.findAll({ ...filters,
1911
- fetching: true
1607
+ return this.#mutationCache.findAll({
1608
+ ...filters,
1609
+ status: 'pending'
1912
1610
  }).length;
1913
1611
  }
1914
-
1915
- getQueryData(queryKey, filters) {
1916
- var _this$queryCache$find;
1917
-
1918
- return (_this$queryCache$find = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find.state.data;
1612
+ getQueryData(queryKey) {
1613
+ return this.#queryCache.find({
1614
+ queryKey
1615
+ })?.state.data;
1919
1616
  }
1920
-
1921
- ensureQueryData(arg1, arg2, arg3) {
1922
- const parsedOptions = parseQueryArgs(arg1, arg2, arg3);
1923
- const cachedData = this.getQueryData(parsedOptions.queryKey);
1924
- return cachedData ? Promise.resolve(cachedData) : this.fetchQuery(parsedOptions);
1617
+ ensureQueryData(options) {
1618
+ const cachedData = this.getQueryData(options.queryKey);
1619
+ return cachedData ? Promise.resolve(cachedData) : this.fetchQuery(options);
1925
1620
  }
1926
-
1927
- getQueriesData(queryKeyOrFilters) {
1928
- return this.getQueryCache().findAll(queryKeyOrFilters).map(({
1621
+ getQueriesData(filters) {
1622
+ return this.getQueryCache().findAll(filters).map(({
1929
1623
  queryKey,
1930
1624
  state
1931
1625
  }) => {
@@ -1933,48 +1627,43 @@
1933
1627
  return [queryKey, data];
1934
1628
  });
1935
1629
  }
1936
-
1937
1630
  setQueryData(queryKey, updater, options) {
1938
- const query = this.queryCache.find(queryKey);
1939
- const prevData = query == null ? void 0 : query.state.data;
1631
+ const query = this.#queryCache.find({
1632
+ queryKey
1633
+ });
1634
+ const prevData = query?.state.data;
1940
1635
  const data = functionalUpdate(updater, prevData);
1941
-
1942
1636
  if (typeof data === 'undefined') {
1943
1637
  return undefined;
1944
1638
  }
1945
-
1946
- const parsedOptions = parseQueryArgs(queryKey);
1947
- const defaultedOptions = this.defaultQueryOptions(parsedOptions);
1948
- return this.queryCache.build(this, defaultedOptions).setData(data, { ...options,
1639
+ const defaultedOptions = this.defaultQueryOptions({
1640
+ queryKey
1641
+ });
1642
+ return this.#queryCache.build(this, defaultedOptions).setData(data, {
1643
+ ...options,
1949
1644
  manual: true
1950
1645
  });
1951
1646
  }
1952
-
1953
- setQueriesData(queryKeyOrFilters, updater, options) {
1954
- return notifyManager.batch(() => this.getQueryCache().findAll(queryKeyOrFilters).map(({
1647
+ setQueriesData(filters, updater, options) {
1648
+ return notifyManager.batch(() => this.getQueryCache().findAll(filters).map(({
1955
1649
  queryKey
1956
1650
  }) => [queryKey, this.setQueryData(queryKey, updater, options)]));
1957
1651
  }
1958
-
1959
- getQueryState(queryKey, filters) {
1960
- var _this$queryCache$find2;
1961
-
1962
- return (_this$queryCache$find2 = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find2.state;
1652
+ getQueryState(queryKey) {
1653
+ return this.#queryCache.find({
1654
+ queryKey
1655
+ })?.state;
1963
1656
  }
1964
-
1965
- removeQueries(arg1, arg2) {
1966
- const [filters] = parseFilterArgs(arg1, arg2);
1967
- const queryCache = this.queryCache;
1657
+ removeQueries(filters) {
1658
+ const queryCache = this.#queryCache;
1968
1659
  notifyManager.batch(() => {
1969
1660
  queryCache.findAll(filters).forEach(query => {
1970
1661
  queryCache.remove(query);
1971
1662
  });
1972
1663
  });
1973
1664
  }
1974
-
1975
- resetQueries(arg1, arg2, arg3) {
1976
- const [filters, options] = parseFilterArgs(arg1, arg2, arg3);
1977
- const queryCache = this.queryCache;
1665
+ resetQueries(filters, options) {
1666
+ const queryCache = this.#queryCache;
1978
1667
  const refetchFilters = {
1979
1668
  type: 'active',
1980
1669
  ...filters
@@ -1986,326 +1675,252 @@
1986
1675
  return this.refetchQueries(refetchFilters, options);
1987
1676
  });
1988
1677
  }
1989
-
1990
- cancelQueries(arg1, arg2, arg3) {
1991
- const [filters, cancelOptions = {}] = parseFilterArgs(arg1, arg2, arg3);
1992
-
1678
+ cancelQueries(filters = {}, cancelOptions = {}) {
1993
1679
  if (typeof cancelOptions.revert === 'undefined') {
1994
1680
  cancelOptions.revert = true;
1995
1681
  }
1996
-
1997
- const promises = notifyManager.batch(() => this.queryCache.findAll(filters).map(query => query.cancel(cancelOptions)));
1682
+ const promises = notifyManager.batch(() => this.#queryCache.findAll(filters).map(query => query.cancel(cancelOptions)));
1998
1683
  return Promise.all(promises).then(noop).catch(noop);
1999
1684
  }
2000
-
2001
- invalidateQueries(arg1, arg2, arg3) {
2002
- const [filters, options] = parseFilterArgs(arg1, arg2, arg3);
1685
+ invalidateQueries(filters = {}, options = {}) {
2003
1686
  return notifyManager.batch(() => {
2004
- var _ref, _filters$refetchType;
2005
-
2006
- this.queryCache.findAll(filters).forEach(query => {
1687
+ this.#queryCache.findAll(filters).forEach(query => {
2007
1688
  query.invalidate();
2008
1689
  });
2009
-
2010
1690
  if (filters.refetchType === 'none') {
2011
1691
  return Promise.resolve();
2012
1692
  }
2013
-
2014
- const refetchFilters = { ...filters,
2015
- type: (_ref = (_filters$refetchType = filters.refetchType) != null ? _filters$refetchType : filters.type) != null ? _ref : 'active'
1693
+ const refetchFilters = {
1694
+ ...filters,
1695
+ type: filters.refetchType ?? filters.type ?? 'active'
2016
1696
  };
2017
1697
  return this.refetchQueries(refetchFilters, options);
2018
1698
  });
2019
1699
  }
2020
-
2021
- refetchQueries(arg1, arg2, arg3) {
2022
- const [filters, options] = parseFilterArgs(arg1, arg2, arg3);
2023
- const promises = notifyManager.batch(() => this.queryCache.findAll(filters).filter(query => !query.isDisabled()).map(query => {
2024
- var _options$cancelRefetc;
2025
-
2026
- return query.fetch(undefined, { ...options,
2027
- cancelRefetch: (_options$cancelRefetc = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc : true,
2028
- meta: {
2029
- refetchPage: filters.refetchPage
2030
- }
2031
- });
2032
- }));
1700
+ refetchQueries(filters = {}, options) {
1701
+ const promises = notifyManager.batch(() => this.#queryCache.findAll(filters).filter(query => !query.isDisabled()).map(query => query.fetch(undefined, {
1702
+ ...options,
1703
+ cancelRefetch: options?.cancelRefetch ?? true
1704
+ })));
2033
1705
  let promise = Promise.all(promises).then(noop);
2034
-
2035
- if (!(options != null && options.throwOnError)) {
1706
+ if (!options?.throwOnError) {
2036
1707
  promise = promise.catch(noop);
2037
1708
  }
2038
-
2039
1709
  return promise;
2040
1710
  }
1711
+ fetchQuery(options) {
1712
+ const defaultedOptions = this.defaultQueryOptions(options);
2041
1713
 
2042
- fetchQuery(arg1, arg2, arg3) {
2043
- const parsedOptions = parseQueryArgs(arg1, arg2, arg3);
2044
- const defaultedOptions = this.defaultQueryOptions(parsedOptions); // https://github.com/tannerlinsley/react-query/issues/652
2045
-
1714
+ // https://github.com/tannerlinsley/react-query/issues/652
2046
1715
  if (typeof defaultedOptions.retry === 'undefined') {
2047
1716
  defaultedOptions.retry = false;
2048
1717
  }
2049
-
2050
- const query = this.queryCache.build(this, defaultedOptions);
1718
+ const query = this.#queryCache.build(this, defaultedOptions);
2051
1719
  return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
2052
1720
  }
2053
-
2054
- prefetchQuery(arg1, arg2, arg3) {
2055
- return this.fetchQuery(arg1, arg2, arg3).then(noop).catch(noop);
1721
+ prefetchQuery(options) {
1722
+ return this.fetchQuery(options).then(noop).catch(noop);
2056
1723
  }
2057
-
2058
- fetchInfiniteQuery(arg1, arg2, arg3) {
2059
- const parsedOptions = parseQueryArgs(arg1, arg2, arg3);
2060
- parsedOptions.behavior = infiniteQueryBehavior();
2061
- return this.fetchQuery(parsedOptions);
1724
+ fetchInfiniteQuery(options) {
1725
+ options.behavior = infiniteQueryBehavior();
1726
+ return this.fetchQuery(options);
2062
1727
  }
2063
-
2064
- prefetchInfiniteQuery(arg1, arg2, arg3) {
2065
- return this.fetchInfiniteQuery(arg1, arg2, arg3).then(noop).catch(noop);
1728
+ prefetchInfiniteQuery(options) {
1729
+ return this.fetchInfiniteQuery(options).then(noop).catch(noop);
2066
1730
  }
2067
-
2068
1731
  resumePausedMutations() {
2069
- return this.mutationCache.resumePausedMutations();
1732
+ return this.#mutationCache.resumePausedMutations();
2070
1733
  }
2071
-
2072
1734
  getQueryCache() {
2073
- return this.queryCache;
1735
+ return this.#queryCache;
2074
1736
  }
2075
-
2076
1737
  getMutationCache() {
2077
- return this.mutationCache;
2078
- }
2079
-
2080
- getLogger() {
2081
- return this.logger;
1738
+ return this.#mutationCache;
2082
1739
  }
2083
-
2084
1740
  getDefaultOptions() {
2085
- return this.defaultOptions;
1741
+ return this.#defaultOptions;
2086
1742
  }
2087
-
2088
1743
  setDefaultOptions(options) {
2089
- this.defaultOptions = options;
1744
+ this.#defaultOptions = options;
2090
1745
  }
2091
-
2092
1746
  setQueryDefaults(queryKey, options) {
2093
- const result = this.queryDefaults.find(x => hashQueryKey(queryKey) === hashQueryKey(x.queryKey));
2094
-
2095
- if (result) {
2096
- result.defaultOptions = options;
2097
- } else {
2098
- this.queryDefaults.push({
2099
- queryKey,
2100
- defaultOptions: options
2101
- });
2102
- }
1747
+ this.#queryDefaults.set(hashKey(queryKey), {
1748
+ queryKey,
1749
+ defaultOptions: options
1750
+ });
2103
1751
  }
2104
-
2105
1752
  getQueryDefaults(queryKey) {
2106
- if (!queryKey) {
2107
- return undefined;
2108
- } // Get the first matching defaults
2109
-
2110
-
2111
- const firstMatchingDefaults = this.queryDefaults.find(x => partialMatchKey(queryKey, x.queryKey)); // Additional checks and error in dev mode
2112
-
2113
- {
2114
- // Retrieve all matching defaults for the given key
2115
- const matchingDefaults = this.queryDefaults.filter(x => partialMatchKey(queryKey, x.queryKey)); // It is ok not having defaults, but it is error prone to have more than 1 default for a given key
2116
-
2117
- if (matchingDefaults.length > 1) {
2118
- this.logger.error("[QueryClient] Several query defaults match with key '" + JSON.stringify(queryKey) + "'. The first matching query defaults are used. Please check how query defaults are registered. Order does matter here. cf. https://react-query.tanstack.com/reference/QueryClient#queryclientsetquerydefaults.");
1753
+ const defaults = [...this.#queryDefaults.values()];
1754
+ let result = {};
1755
+ defaults.forEach(queryDefault => {
1756
+ if (partialMatchKey(queryKey, queryDefault.queryKey)) {
1757
+ result = {
1758
+ ...result,
1759
+ ...queryDefault.defaultOptions
1760
+ };
2119
1761
  }
2120
- }
2121
-
2122
- return firstMatchingDefaults == null ? void 0 : firstMatchingDefaults.defaultOptions;
1762
+ });
1763
+ return result;
2123
1764
  }
2124
-
2125
1765
  setMutationDefaults(mutationKey, options) {
2126
- const result = this.mutationDefaults.find(x => hashQueryKey(mutationKey) === hashQueryKey(x.mutationKey));
2127
-
2128
- if (result) {
2129
- result.defaultOptions = options;
2130
- } else {
2131
- this.mutationDefaults.push({
2132
- mutationKey,
2133
- defaultOptions: options
2134
- });
2135
- }
1766
+ this.#mutationDefaults.set(hashKey(mutationKey), {
1767
+ mutationKey,
1768
+ defaultOptions: options
1769
+ });
2136
1770
  }
2137
-
2138
1771
  getMutationDefaults(mutationKey) {
2139
- if (!mutationKey) {
2140
- return undefined;
2141
- } // Get the first matching defaults
2142
-
2143
-
2144
- const firstMatchingDefaults = this.mutationDefaults.find(x => partialMatchKey(mutationKey, x.mutationKey)); // Additional checks and error in dev mode
2145
-
2146
- {
2147
- // Retrieve all matching defaults for the given key
2148
- const matchingDefaults = this.mutationDefaults.filter(x => partialMatchKey(mutationKey, x.mutationKey)); // It is ok not having defaults, but it is error prone to have more than 1 default for a given key
2149
-
2150
- if (matchingDefaults.length > 1) {
2151
- this.logger.error("[QueryClient] Several mutation defaults match with key '" + JSON.stringify(mutationKey) + "'. The first matching mutation defaults are used. Please check how mutation defaults are registered. Order does matter here. cf. https://react-query.tanstack.com/reference/QueryClient#queryclientsetmutationdefaults.");
1772
+ const defaults = [...this.#mutationDefaults.values()];
1773
+ let result = {};
1774
+ defaults.forEach(queryDefault => {
1775
+ if (partialMatchKey(mutationKey, queryDefault.mutationKey)) {
1776
+ result = {
1777
+ ...result,
1778
+ ...queryDefault.defaultOptions
1779
+ };
2152
1780
  }
2153
- }
2154
-
2155
- return firstMatchingDefaults == null ? void 0 : firstMatchingDefaults.defaultOptions;
1781
+ });
1782
+ return result;
2156
1783
  }
2157
-
2158
1784
  defaultQueryOptions(options) {
2159
- if (options != null && options._defaulted) {
1785
+ if (options?._defaulted) {
2160
1786
  return options;
2161
1787
  }
2162
-
2163
- const defaultedOptions = { ...this.defaultOptions.queries,
2164
- ...this.getQueryDefaults(options == null ? void 0 : options.queryKey),
1788
+ const defaultedOptions = {
1789
+ ...this.#defaultOptions.queries,
1790
+ ...(options?.queryKey && this.getQueryDefaults(options.queryKey)),
2165
1791
  ...options,
2166
1792
  _defaulted: true
2167
1793
  };
2168
-
2169
- if (!defaultedOptions.queryHash && defaultedOptions.queryKey) {
1794
+ if (!defaultedOptions.queryHash) {
2170
1795
  defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions);
2171
- } // dependent default values
2172
-
1796
+ }
2173
1797
 
1798
+ // dependent default values
2174
1799
  if (typeof defaultedOptions.refetchOnReconnect === 'undefined') {
2175
1800
  defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== 'always';
2176
1801
  }
2177
-
2178
- if (typeof defaultedOptions.useErrorBoundary === 'undefined') {
2179
- defaultedOptions.useErrorBoundary = !!defaultedOptions.suspense;
1802
+ if (typeof defaultedOptions.throwErrors === 'undefined') {
1803
+ defaultedOptions.throwErrors = !!defaultedOptions.suspense;
2180
1804
  }
2181
-
2182
1805
  return defaultedOptions;
2183
1806
  }
2184
-
2185
1807
  defaultMutationOptions(options) {
2186
- if (options != null && options._defaulted) {
1808
+ if (options?._defaulted) {
2187
1809
  return options;
2188
1810
  }
2189
-
2190
- return { ...this.defaultOptions.mutations,
2191
- ...this.getMutationDefaults(options == null ? void 0 : options.mutationKey),
1811
+ return {
1812
+ ...this.#defaultOptions.mutations,
1813
+ ...(options?.mutationKey && this.getMutationDefaults(options.mutationKey)),
2192
1814
  ...options,
2193
1815
  _defaulted: true
2194
1816
  };
2195
1817
  }
2196
-
2197
1818
  clear() {
2198
- this.queryCache.clear();
2199
- this.mutationCache.clear();
1819
+ this.#queryCache.clear();
1820
+ this.#mutationCache.clear();
2200
1821
  }
2201
-
2202
1822
  }
2203
1823
 
2204
1824
  class QueryObserver extends Subscribable {
1825
+ #client;
1826
+ #currentQuery = undefined;
1827
+ #currentQueryInitialState = undefined;
1828
+ #currentResult = undefined;
1829
+ #currentResultState;
1830
+ #currentResultOptions;
1831
+ #previousQueryResult;
1832
+ #selectError;
1833
+ #selectFn;
1834
+ #selectResult;
1835
+ #staleTimeoutId;
1836
+ #refetchIntervalId;
1837
+ #currentRefetchInterval;
1838
+ #trackedProps = new Set();
2205
1839
  constructor(client, options) {
2206
1840
  super();
2207
- this.client = client;
1841
+ this.#client = client;
2208
1842
  this.options = options;
2209
- this.trackedProps = new Set();
2210
- this.selectError = null;
1843
+ this.#selectError = null;
2211
1844
  this.bindMethods();
2212
1845
  this.setOptions(options);
2213
1846
  }
2214
-
2215
1847
  bindMethods() {
2216
- this.remove = this.remove.bind(this);
2217
1848
  this.refetch = this.refetch.bind(this);
2218
1849
  }
2219
-
2220
1850
  onSubscribe() {
2221
1851
  if (this.listeners.length === 1) {
2222
- this.currentQuery.addObserver(this);
2223
-
2224
- if (shouldFetchOnMount(this.currentQuery, this.options)) {
2225
- this.executeFetch();
1852
+ this.#currentQuery.addObserver(this);
1853
+ if (shouldFetchOnMount(this.#currentQuery, this.options)) {
1854
+ this.#executeFetch();
2226
1855
  }
2227
-
2228
- this.updateTimers();
1856
+ this.#updateTimers();
2229
1857
  }
2230
1858
  }
2231
-
2232
1859
  onUnsubscribe() {
2233
1860
  if (!this.listeners.length) {
2234
1861
  this.destroy();
2235
1862
  }
2236
1863
  }
2237
-
2238
1864
  shouldFetchOnReconnect() {
2239
- return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnReconnect);
1865
+ return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnReconnect);
2240
1866
  }
2241
-
2242
1867
  shouldFetchOnWindowFocus() {
2243
- return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnWindowFocus);
1868
+ return shouldFetchOn(this.#currentQuery, this.options, this.options.refetchOnWindowFocus);
2244
1869
  }
2245
-
2246
1870
  destroy() {
2247
1871
  this.listeners = [];
2248
- this.clearStaleTimeout();
2249
- this.clearRefetchInterval();
2250
- this.currentQuery.removeObserver(this);
1872
+ this.#clearStaleTimeout();
1873
+ this.#clearRefetchInterval();
1874
+ this.#currentQuery.removeObserver(this);
2251
1875
  }
2252
-
2253
1876
  setOptions(options, notifyOptions) {
2254
1877
  const prevOptions = this.options;
2255
- const prevQuery = this.currentQuery;
2256
- this.options = this.client.defaultQueryOptions(options);
2257
-
2258
- if (typeof (options == null ? void 0 : options.isDataEqual) !== 'undefined') {
2259
- this.client.getLogger().error("The isDataEqual option has been deprecated and will be removed in the next major version. You can achieve the same functionality by passing a function as the structuralSharing option");
2260
- }
2261
-
1878
+ const prevQuery = this.#currentQuery;
1879
+ this.options = this.#client.defaultQueryOptions(options);
2262
1880
  if (!shallowEqualObjects(prevOptions, this.options)) {
2263
- this.client.getQueryCache().notify({
1881
+ this.#client.getQueryCache().notify({
2264
1882
  type: 'observerOptionsUpdated',
2265
- query: this.currentQuery,
1883
+ query: this.#currentQuery,
2266
1884
  observer: this
2267
1885
  });
2268
1886
  }
2269
-
2270
1887
  if (typeof this.options.enabled !== 'undefined' && typeof this.options.enabled !== 'boolean') {
2271
1888
  throw new Error('Expected enabled to be a boolean');
2272
- } // Keep previous query key if the user does not supply one
2273
-
1889
+ }
2274
1890
 
1891
+ // Keep previous query key if the user does not supply one
2275
1892
  if (!this.options.queryKey) {
2276
1893
  this.options.queryKey = prevOptions.queryKey;
2277
1894
  }
1895
+ this.#updateQuery();
1896
+ const mounted = this.hasListeners();
2278
1897
 
2279
- this.updateQuery();
2280
- const mounted = this.hasListeners(); // Fetch if there are subscribers
2281
-
2282
- if (mounted && shouldFetchOptionally(this.currentQuery, prevQuery, this.options, prevOptions)) {
2283
- this.executeFetch();
2284
- } // Update result
2285
-
1898
+ // Fetch if there are subscribers
1899
+ if (mounted && shouldFetchOptionally(this.#currentQuery, prevQuery, this.options, prevOptions)) {
1900
+ this.#executeFetch();
1901
+ }
2286
1902
 
2287
- this.updateResult(notifyOptions); // Update stale interval if needed
1903
+ // Update result
1904
+ this.#updateResult(notifyOptions);
2288
1905
 
2289
- if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) {
2290
- this.updateStaleTimeout();
1906
+ // Update stale interval if needed
1907
+ if (mounted && (this.#currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) {
1908
+ this.#updateStaleTimeout();
2291
1909
  }
1910
+ const nextRefetchInterval = this.#computeRefetchInterval();
2292
1911
 
2293
- const nextRefetchInterval = this.computeRefetchInterval(); // Update refetch interval if needed
2294
-
2295
- if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.currentRefetchInterval)) {
2296
- this.updateRefetchInterval(nextRefetchInterval);
1912
+ // Update refetch interval if needed
1913
+ if (mounted && (this.#currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.#currentRefetchInterval)) {
1914
+ this.#updateRefetchInterval(nextRefetchInterval);
2297
1915
  }
2298
1916
  }
2299
-
2300
1917
  getOptimisticResult(options) {
2301
- const query = this.client.getQueryCache().build(this.client, options);
1918
+ const query = this.#client.getQueryCache().build(this.#client, options);
2302
1919
  return this.createResult(query, options);
2303
1920
  }
2304
-
2305
1921
  getCurrentResult() {
2306
- return this.currentResult;
1922
+ return this.#currentResult;
2307
1923
  }
2308
-
2309
1924
  trackResult(result) {
2310
1925
  const trackedResult = {};
2311
1926
  Object.keys(result).forEach(key => {
@@ -2313,243 +1928,199 @@
2313
1928
  configurable: false,
2314
1929
  enumerable: true,
2315
1930
  get: () => {
2316
- this.trackedProps.add(key);
1931
+ this.#trackedProps.add(key);
2317
1932
  return result[key];
2318
1933
  }
2319
1934
  });
2320
1935
  });
2321
1936
  return trackedResult;
2322
1937
  }
2323
-
2324
1938
  getCurrentQuery() {
2325
- return this.currentQuery;
1939
+ return this.#currentQuery;
2326
1940
  }
2327
-
2328
- remove() {
2329
- this.client.getQueryCache().remove(this.currentQuery);
2330
- }
2331
-
2332
1941
  refetch({
2333
- refetchPage,
2334
1942
  ...options
2335
1943
  } = {}) {
2336
- return this.fetch({ ...options,
2337
- meta: {
2338
- refetchPage
2339
- }
1944
+ return this.fetch({
1945
+ ...options
2340
1946
  });
2341
1947
  }
2342
-
2343
1948
  fetchOptimistic(options) {
2344
- const defaultedOptions = this.client.defaultQueryOptions(options);
2345
- const query = this.client.getQueryCache().build(this.client, defaultedOptions);
1949
+ const defaultedOptions = this.#client.defaultQueryOptions(options);
1950
+ const query = this.#client.getQueryCache().build(this.#client, defaultedOptions);
2346
1951
  query.isFetchingOptimistic = true;
2347
1952
  return query.fetch().then(() => this.createResult(query, defaultedOptions));
2348
1953
  }
2349
-
2350
1954
  fetch(fetchOptions) {
2351
- var _fetchOptions$cancelR;
2352
-
2353
- return this.executeFetch({ ...fetchOptions,
2354
- cancelRefetch: (_fetchOptions$cancelR = fetchOptions.cancelRefetch) != null ? _fetchOptions$cancelR : true
1955
+ return this.#executeFetch({
1956
+ ...fetchOptions,
1957
+ cancelRefetch: fetchOptions.cancelRefetch ?? true
2355
1958
  }).then(() => {
2356
- this.updateResult();
2357
- return this.currentResult;
1959
+ this.#updateResult();
1960
+ return this.#currentResult;
2358
1961
  });
2359
1962
  }
2360
-
2361
- executeFetch(fetchOptions) {
1963
+ #executeFetch(fetchOptions) {
2362
1964
  // Make sure we reference the latest query as the current one might have been removed
2363
- this.updateQuery(); // Fetch
2364
-
2365
- let promise = this.currentQuery.fetch(this.options, fetchOptions);
1965
+ this.#updateQuery();
2366
1966
 
2367
- if (!(fetchOptions != null && fetchOptions.throwOnError)) {
1967
+ // Fetch
1968
+ let promise = this.#currentQuery.fetch(this.options, fetchOptions);
1969
+ if (!fetchOptions?.throwOnError) {
2368
1970
  promise = promise.catch(noop);
2369
1971
  }
2370
-
2371
1972
  return promise;
2372
1973
  }
2373
-
2374
- updateStaleTimeout() {
2375
- this.clearStaleTimeout();
2376
-
2377
- if (isServer || this.currentResult.isStale || !isValidTimeout(this.options.staleTime)) {
1974
+ #updateStaleTimeout() {
1975
+ this.#clearStaleTimeout();
1976
+ if (isServer || this.#currentResult.isStale || !isValidTimeout(this.options.staleTime)) {
2378
1977
  return;
2379
1978
  }
1979
+ const time = timeUntilStale(this.#currentResult.dataUpdatedAt, this.options.staleTime);
2380
1980
 
2381
- const time = timeUntilStale(this.currentResult.dataUpdatedAt, this.options.staleTime); // The timeout is sometimes triggered 1 ms before the stale time expiration.
1981
+ // The timeout is sometimes triggered 1 ms before the stale time expiration.
2382
1982
  // To mitigate this issue we always add 1 ms to the timeout.
2383
-
2384
1983
  const timeout = time + 1;
2385
- this.staleTimeoutId = setTimeout(() => {
2386
- if (!this.currentResult.isStale) {
2387
- this.updateResult();
1984
+ this.#staleTimeoutId = setTimeout(() => {
1985
+ if (!this.#currentResult.isStale) {
1986
+ this.#updateResult();
2388
1987
  }
2389
1988
  }, timeout);
2390
1989
  }
2391
-
2392
- computeRefetchInterval() {
2393
- var _this$options$refetch;
2394
-
2395
- return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(this.currentResult.data, this.currentQuery) : (_this$options$refetch = this.options.refetchInterval) != null ? _this$options$refetch : false;
1990
+ #computeRefetchInterval() {
1991
+ return typeof this.options.refetchInterval === 'function' ? this.options.refetchInterval(this.#currentResult.data, this.#currentQuery) : this.options.refetchInterval ?? false;
2396
1992
  }
2397
-
2398
- updateRefetchInterval(nextInterval) {
2399
- this.clearRefetchInterval();
2400
- this.currentRefetchInterval = nextInterval;
2401
-
2402
- if (isServer || this.options.enabled === false || !isValidTimeout(this.currentRefetchInterval) || this.currentRefetchInterval === 0) {
1993
+ #updateRefetchInterval(nextInterval) {
1994
+ this.#clearRefetchInterval();
1995
+ this.#currentRefetchInterval = nextInterval;
1996
+ if (isServer || this.options.enabled === false || !isValidTimeout(this.#currentRefetchInterval) || this.#currentRefetchInterval === 0) {
2403
1997
  return;
2404
1998
  }
2405
-
2406
- this.refetchIntervalId = setInterval(() => {
1999
+ this.#refetchIntervalId = setInterval(() => {
2407
2000
  if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
2408
- this.executeFetch();
2001
+ this.#executeFetch();
2409
2002
  }
2410
- }, this.currentRefetchInterval);
2003
+ }, this.#currentRefetchInterval);
2411
2004
  }
2412
-
2413
- updateTimers() {
2414
- this.updateStaleTimeout();
2415
- this.updateRefetchInterval(this.computeRefetchInterval());
2005
+ #updateTimers() {
2006
+ this.#updateStaleTimeout();
2007
+ this.#updateRefetchInterval(this.#computeRefetchInterval());
2416
2008
  }
2417
-
2418
- clearStaleTimeout() {
2419
- if (this.staleTimeoutId) {
2420
- clearTimeout(this.staleTimeoutId);
2421
- this.staleTimeoutId = undefined;
2009
+ #clearStaleTimeout() {
2010
+ if (this.#staleTimeoutId) {
2011
+ clearTimeout(this.#staleTimeoutId);
2012
+ this.#staleTimeoutId = undefined;
2422
2013
  }
2423
2014
  }
2424
-
2425
- clearRefetchInterval() {
2426
- if (this.refetchIntervalId) {
2427
- clearInterval(this.refetchIntervalId);
2428
- this.refetchIntervalId = undefined;
2015
+ #clearRefetchInterval() {
2016
+ if (this.#refetchIntervalId) {
2017
+ clearInterval(this.#refetchIntervalId);
2018
+ this.#refetchIntervalId = undefined;
2429
2019
  }
2430
2020
  }
2431
-
2432
2021
  createResult(query, options) {
2433
- const prevQuery = this.currentQuery;
2022
+ const prevQuery = this.#currentQuery;
2434
2023
  const prevOptions = this.options;
2435
- const prevResult = this.currentResult;
2436
- const prevResultState = this.currentResultState;
2437
- const prevResultOptions = this.currentResultOptions;
2024
+ const prevResult = this.#currentResult;
2025
+ const prevResultState = this.#currentResultState;
2026
+ const prevResultOptions = this.#currentResultOptions;
2438
2027
  const queryChange = query !== prevQuery;
2439
- const queryInitialState = queryChange ? query.state : this.currentQueryInitialState;
2440
- const prevQueryResult = queryChange ? this.currentResult : this.previousQueryResult;
2028
+ const queryInitialState = queryChange ? query.state : this.#currentQueryInitialState;
2029
+ const prevQueryResult = queryChange ? this.#currentResult : this.#previousQueryResult;
2441
2030
  const {
2442
2031
  state
2443
2032
  } = query;
2444
2033
  let {
2445
- dataUpdatedAt,
2446
2034
  error,
2447
2035
  errorUpdatedAt,
2448
2036
  fetchStatus,
2449
2037
  status
2450
2038
  } = state;
2451
- let isPreviousData = false;
2452
2039
  let isPlaceholderData = false;
2453
- let data; // Optimistically set result in fetching state if needed
2040
+ let data;
2454
2041
 
2042
+ // Optimistically set result in fetching state if needed
2455
2043
  if (options._optimisticResults) {
2456
2044
  const mounted = this.hasListeners();
2457
2045
  const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
2458
2046
  const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
2459
-
2460
2047
  if (fetchOnMount || fetchOptionally) {
2461
2048
  fetchStatus = canFetch(query.options.networkMode) ? 'fetching' : 'paused';
2462
-
2463
- if (!dataUpdatedAt) {
2464
- status = 'loading';
2049
+ if (!state.dataUpdatedAt) {
2050
+ status = 'pending';
2465
2051
  }
2466
2052
  }
2467
-
2468
2053
  if (options._optimisticResults === 'isRestoring') {
2469
2054
  fetchStatus = 'idle';
2470
2055
  }
2471
- } // Keep previous data if needed
2472
-
2056
+ }
2473
2057
 
2474
- if (options.keepPreviousData && !state.dataUpdatedAt && prevQueryResult != null && prevQueryResult.isSuccess && status !== 'error') {
2475
- data = prevQueryResult.data;
2476
- dataUpdatedAt = prevQueryResult.dataUpdatedAt;
2477
- status = prevQueryResult.status;
2478
- isPreviousData = true;
2479
- } // Select data if needed
2480
- else if (options.select && typeof state.data !== 'undefined') {
2058
+ // Select data if needed
2059
+ if (options.select && typeof state.data !== 'undefined') {
2481
2060
  // Memoize select result
2482
- if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === this.selectFn) {
2483
- data = this.selectResult;
2061
+ if (prevResult && state.data === prevResultState?.data && options.select === this.#selectFn) {
2062
+ data = this.#selectResult;
2484
2063
  } else {
2485
2064
  try {
2486
- this.selectFn = options.select;
2065
+ this.#selectFn = options.select;
2487
2066
  data = options.select(state.data);
2488
- data = replaceData(prevResult == null ? void 0 : prevResult.data, data, options);
2489
- this.selectResult = data;
2490
- this.selectError = null;
2067
+ data = replaceData(prevResult?.data, data, options);
2068
+ this.#selectResult = data;
2069
+ this.#selectError = null;
2491
2070
  } catch (selectError) {
2492
- {
2493
- this.client.getLogger().error(selectError);
2494
- }
2495
-
2496
- this.selectError = selectError;
2071
+ this.#selectError = selectError;
2497
2072
  }
2498
2073
  }
2499
- } // Use query data
2074
+ }
2075
+ // Use query data
2500
2076
  else {
2501
2077
  data = state.data;
2502
- } // Show placeholder data if needed
2503
-
2078
+ }
2504
2079
 
2505
- if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && status === 'loading') {
2506
- let placeholderData; // Memoize placeholder data
2080
+ // Show placeholder data if needed
2081
+ if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && status === 'pending') {
2082
+ let placeholderData;
2507
2083
 
2508
- if (prevResult != null && prevResult.isPlaceholderData && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
2084
+ // Memoize placeholder data
2085
+ if (prevResult?.isPlaceholderData && options.placeholderData === prevResultOptions?.placeholderData) {
2509
2086
  placeholderData = prevResult.data;
2510
2087
  } else {
2511
- placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData() : options.placeholderData;
2512
-
2088
+ placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData(prevQueryResult?.data) : options.placeholderData;
2513
2089
  if (options.select && typeof placeholderData !== 'undefined') {
2514
2090
  try {
2515
2091
  placeholderData = options.select(placeholderData);
2516
- this.selectError = null;
2092
+ this.#selectError = null;
2517
2093
  } catch (selectError) {
2518
- {
2519
- this.client.getLogger().error(selectError);
2520
- }
2521
-
2522
- this.selectError = selectError;
2094
+ this.#selectError = selectError;
2523
2095
  }
2524
2096
  }
2525
2097
  }
2526
-
2527
2098
  if (typeof placeholderData !== 'undefined') {
2528
2099
  status = 'success';
2529
- data = replaceData(prevResult == null ? void 0 : prevResult.data, placeholderData, options);
2100
+ data = replaceData(prevResult?.data, placeholderData, options);
2530
2101
  isPlaceholderData = true;
2531
2102
  }
2532
2103
  }
2533
-
2534
- if (this.selectError) {
2535
- error = this.selectError;
2536
- data = this.selectResult;
2104
+ if (this.#selectError) {
2105
+ error = this.#selectError;
2106
+ data = this.#selectResult;
2537
2107
  errorUpdatedAt = Date.now();
2538
2108
  status = 'error';
2539
2109
  }
2540
-
2541
2110
  const isFetching = fetchStatus === 'fetching';
2542
- const isLoading = status === 'loading';
2111
+ const isPending = status === 'pending';
2543
2112
  const isError = status === 'error';
2113
+ const isLoading = isPending && isFetching;
2544
2114
  const result = {
2545
2115
  status,
2546
2116
  fetchStatus,
2547
- isLoading,
2117
+ isPending,
2548
2118
  isSuccess: status === 'success',
2549
2119
  isError,
2550
- isInitialLoading: isLoading && isFetching,
2120
+ isInitialLoading: isLoading,
2121
+ isLoading,
2551
2122
  data,
2552
- dataUpdatedAt,
2123
+ dataUpdatedAt: state.dataUpdatedAt,
2553
2124
  error,
2554
2125
  errorUpdatedAt,
2555
2126
  failureCount: state.fetchFailureCount,
@@ -2558,377 +2129,313 @@
2558
2129
  isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
2559
2130
  isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
2560
2131
  isFetching,
2561
- isRefetching: isFetching && !isLoading,
2132
+ isRefetching: isFetching && !isPending,
2562
2133
  isLoadingError: isError && state.dataUpdatedAt === 0,
2563
2134
  isPaused: fetchStatus === 'paused',
2564
2135
  isPlaceholderData,
2565
- isPreviousData,
2566
2136
  isRefetchError: isError && state.dataUpdatedAt !== 0,
2567
2137
  isStale: isStale(query, options),
2568
- refetch: this.refetch,
2569
- remove: this.remove
2138
+ refetch: this.refetch
2570
2139
  };
2571
2140
  return result;
2572
2141
  }
2142
+ #updateResult(notifyOptions) {
2143
+ const prevResult = this.#currentResult;
2144
+ const nextResult = this.createResult(this.#currentQuery, this.options);
2145
+ this.#currentResultState = this.#currentQuery.state;
2146
+ this.#currentResultOptions = this.options;
2573
2147
 
2574
- updateResult(notifyOptions) {
2575
- const prevResult = this.currentResult;
2576
- const nextResult = this.createResult(this.currentQuery, this.options);
2577
- this.currentResultState = this.currentQuery.state;
2578
- this.currentResultOptions = this.options; // Only notify and update result if something has changed
2579
-
2148
+ // Only notify and update result if something has changed
2580
2149
  if (shallowEqualObjects(nextResult, prevResult)) {
2581
2150
  return;
2582
2151
  }
2152
+ this.#currentResult = nextResult;
2583
2153
 
2584
- this.currentResult = nextResult; // Determine which callbacks to trigger
2585
-
2586
- const defaultNotifyOptions = {
2587
- cache: true
2588
- };
2589
-
2154
+ // Determine which callbacks to trigger
2155
+ const defaultNotifyOptions = {};
2590
2156
  const shouldNotifyListeners = () => {
2591
2157
  if (!prevResult) {
2592
2158
  return true;
2593
2159
  }
2594
-
2595
2160
  const {
2596
2161
  notifyOnChangeProps
2597
2162
  } = this.options;
2598
-
2599
- if (notifyOnChangeProps === 'all' || !notifyOnChangeProps && !this.trackedProps.size) {
2163
+ if (notifyOnChangeProps === 'all' || !notifyOnChangeProps && !this.#trackedProps.size) {
2600
2164
  return true;
2601
2165
  }
2602
-
2603
- const includedProps = new Set(notifyOnChangeProps != null ? notifyOnChangeProps : this.trackedProps);
2604
-
2605
- if (this.options.useErrorBoundary) {
2166
+ const includedProps = new Set(notifyOnChangeProps ?? this.#trackedProps);
2167
+ if (this.options.throwErrors) {
2606
2168
  includedProps.add('error');
2607
2169
  }
2608
-
2609
- return Object.keys(this.currentResult).some(key => {
2170
+ return Object.keys(this.#currentResult).some(key => {
2610
2171
  const typedKey = key;
2611
- const changed = this.currentResult[typedKey] !== prevResult[typedKey];
2172
+ const changed = this.#currentResult[typedKey] !== prevResult[typedKey];
2612
2173
  return changed && includedProps.has(typedKey);
2613
2174
  });
2614
2175
  };
2615
-
2616
- if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && shouldNotifyListeners()) {
2176
+ if (notifyOptions?.listeners !== false && shouldNotifyListeners()) {
2617
2177
  defaultNotifyOptions.listeners = true;
2618
2178
  }
2619
-
2620
- this.notify({ ...defaultNotifyOptions,
2179
+ this.#notify({
2180
+ ...defaultNotifyOptions,
2621
2181
  ...notifyOptions
2622
2182
  });
2623
2183
  }
2624
-
2625
- updateQuery() {
2626
- const query = this.client.getQueryCache().build(this.client, this.options);
2627
-
2628
- if (query === this.currentQuery) {
2184
+ #updateQuery() {
2185
+ const query = this.#client.getQueryCache().build(this.#client, this.options);
2186
+ if (query === this.#currentQuery) {
2629
2187
  return;
2630
2188
  }
2631
-
2632
- const prevQuery = this.currentQuery;
2633
- this.currentQuery = query;
2634
- this.currentQueryInitialState = query.state;
2635
- this.previousQueryResult = this.currentResult;
2636
-
2189
+ const prevQuery = this.#currentQuery;
2190
+ this.#currentQuery = query;
2191
+ this.#currentQueryInitialState = query.state;
2192
+ this.#previousQueryResult = this.#currentResult;
2637
2193
  if (this.hasListeners()) {
2638
- prevQuery == null ? void 0 : prevQuery.removeObserver(this);
2194
+ prevQuery?.removeObserver(this);
2639
2195
  query.addObserver(this);
2640
2196
  }
2641
2197
  }
2642
-
2643
2198
  onQueryUpdate(action) {
2644
2199
  const notifyOptions = {};
2645
-
2646
2200
  if (action.type === 'success') {
2647
2201
  notifyOptions.onSuccess = !action.manual;
2648
2202
  } else if (action.type === 'error' && !isCancelledError(action.error)) {
2649
2203
  notifyOptions.onError = true;
2650
2204
  }
2651
-
2652
- this.updateResult(notifyOptions);
2653
-
2205
+ this.#updateResult(notifyOptions);
2654
2206
  if (this.hasListeners()) {
2655
- this.updateTimers();
2207
+ this.#updateTimers();
2656
2208
  }
2657
2209
  }
2658
-
2659
- notify(notifyOptions) {
2210
+ #notify(notifyOptions) {
2660
2211
  notifyManager.batch(() => {
2661
2212
  // First trigger the configuration callbacks
2662
2213
  if (notifyOptions.onSuccess) {
2663
- var _this$options$onSucce, _this$options, _this$options$onSettl, _this$options2;
2664
-
2665
- (_this$options$onSucce = (_this$options = this.options).onSuccess) == null ? void 0 : _this$options$onSucce.call(_this$options, this.currentResult.data);
2666
- (_this$options$onSettl = (_this$options2 = this.options).onSettled) == null ? void 0 : _this$options$onSettl.call(_this$options2, this.currentResult.data, null);
2214
+ this.options.onSuccess?.(this.#currentResult.data);
2215
+ this.options.onSettled?.(this.#currentResult.data, null);
2667
2216
  } else if (notifyOptions.onError) {
2668
- var _this$options$onError, _this$options3, _this$options$onSettl2, _this$options4;
2669
-
2670
- (_this$options$onError = (_this$options3 = this.options).onError) == null ? void 0 : _this$options$onError.call(_this$options3, this.currentResult.error);
2671
- (_this$options$onSettl2 = (_this$options4 = this.options).onSettled) == null ? void 0 : _this$options$onSettl2.call(_this$options4, undefined, this.currentResult.error);
2672
- } // Then trigger the listeners
2673
-
2217
+ this.options.onError?.(this.#currentResult.error);
2218
+ this.options.onSettled?.(undefined, this.#currentResult.error);
2219
+ }
2674
2220
 
2221
+ // Then trigger the listeners
2675
2222
  if (notifyOptions.listeners) {
2676
2223
  this.listeners.forEach(listener => {
2677
- listener(this.currentResult);
2678
- });
2679
- } // Then the cache listeners
2680
-
2681
-
2682
- if (notifyOptions.cache) {
2683
- this.client.getQueryCache().notify({
2684
- query: this.currentQuery,
2685
- type: 'observerResultsUpdated'
2224
+ listener(this.#currentResult);
2686
2225
  });
2687
2226
  }
2227
+
2228
+ // Then the cache listeners
2229
+ this.#client.getQueryCache().notify({
2230
+ query: this.#currentQuery,
2231
+ type: 'observerResultsUpdated'
2232
+ });
2688
2233
  });
2689
2234
  }
2690
-
2691
2235
  }
2692
-
2693
2236
  function shouldLoadOnMount(query, options) {
2694
2237
  return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false);
2695
2238
  }
2696
-
2697
2239
  function shouldFetchOnMount(query, options) {
2698
2240
  return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
2699
2241
  }
2700
-
2701
2242
  function shouldFetchOn(query, options, field) {
2702
2243
  if (options.enabled !== false) {
2703
2244
  const value = typeof field === 'function' ? field(query) : field;
2704
2245
  return value === 'always' || value !== false && isStale(query, options);
2705
2246
  }
2706
-
2707
2247
  return false;
2708
2248
  }
2709
-
2710
2249
  function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
2711
2250
  return options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options);
2712
2251
  }
2713
-
2714
2252
  function isStale(query, options) {
2715
2253
  return query.isStaleByTime(options.staleTime);
2716
2254
  }
2717
2255
 
2256
+ function difference(array1, array2) {
2257
+ return array1.filter(x => array2.indexOf(x) === -1);
2258
+ }
2259
+ function replaceAt(array, index, value) {
2260
+ const copy = array.slice(0);
2261
+ copy[index] = value;
2262
+ return copy;
2263
+ }
2718
2264
  class QueriesObserver extends Subscribable {
2265
+ #client;
2266
+ #result;
2267
+ #queries;
2268
+ #observers;
2269
+ #observersMap;
2719
2270
  constructor(client, queries) {
2720
2271
  super();
2721
- this.client = client;
2722
- this.queries = [];
2723
- this.result = [];
2724
- this.observers = [];
2725
- this.observersMap = {};
2726
-
2272
+ this.#client = client;
2273
+ this.#queries = [];
2274
+ this.#result = [];
2275
+ this.#observers = [];
2276
+ this.#observersMap = {};
2727
2277
  if (queries) {
2728
2278
  this.setQueries(queries);
2729
2279
  }
2730
2280
  }
2731
-
2732
2281
  onSubscribe() {
2733
2282
  if (this.listeners.length === 1) {
2734
- this.observers.forEach(observer => {
2283
+ this.#observers.forEach(observer => {
2735
2284
  observer.subscribe(result => {
2736
- this.onUpdate(observer, result);
2285
+ this.#onUpdate(observer, result);
2737
2286
  });
2738
2287
  });
2739
2288
  }
2740
2289
  }
2741
-
2742
2290
  onUnsubscribe() {
2743
2291
  if (!this.listeners.length) {
2744
2292
  this.destroy();
2745
2293
  }
2746
2294
  }
2747
-
2748
2295
  destroy() {
2749
2296
  this.listeners = [];
2750
- this.observers.forEach(observer => {
2297
+ this.#observers.forEach(observer => {
2751
2298
  observer.destroy();
2752
2299
  });
2753
2300
  }
2754
-
2755
2301
  setQueries(queries, notifyOptions) {
2756
- this.queries = queries;
2302
+ this.#queries = queries;
2757
2303
  notifyManager.batch(() => {
2758
- const prevObservers = this.observers;
2759
- const newObserverMatches = this.findMatchingObservers(this.queries); // set options for the new observers to notify of changes
2304
+ const prevObservers = this.#observers;
2305
+ const newObserverMatches = this.#findMatchingObservers(this.#queries);
2760
2306
 
2307
+ // set options for the new observers to notify of changes
2761
2308
  newObserverMatches.forEach(match => match.observer.setOptions(match.defaultedQueryOptions, notifyOptions));
2762
2309
  const newObservers = newObserverMatches.map(match => match.observer);
2763
2310
  const newObserversMap = Object.fromEntries(newObservers.map(observer => [observer.options.queryHash, observer]));
2764
2311
  const newResult = newObservers.map(observer => observer.getCurrentResult());
2765
2312
  const hasIndexChange = newObservers.some((observer, index) => observer !== prevObservers[index]);
2766
-
2767
2313
  if (prevObservers.length === newObservers.length && !hasIndexChange) {
2768
2314
  return;
2769
2315
  }
2770
-
2771
- this.observers = newObservers;
2772
- this.observersMap = newObserversMap;
2773
- this.result = newResult;
2774
-
2316
+ this.#observers = newObservers;
2317
+ this.#observersMap = newObserversMap;
2318
+ this.#result = newResult;
2775
2319
  if (!this.hasListeners()) {
2776
2320
  return;
2777
2321
  }
2778
-
2779
2322
  difference(prevObservers, newObservers).forEach(observer => {
2780
2323
  observer.destroy();
2781
2324
  });
2782
2325
  difference(newObservers, prevObservers).forEach(observer => {
2783
2326
  observer.subscribe(result => {
2784
- this.onUpdate(observer, result);
2327
+ this.#onUpdate(observer, result);
2785
2328
  });
2786
2329
  });
2787
- this.notify();
2330
+ this.#notify();
2788
2331
  });
2789
2332
  }
2790
-
2791
2333
  getCurrentResult() {
2792
- return this.result;
2334
+ return this.#result;
2793
2335
  }
2794
-
2795
2336
  getQueries() {
2796
- return this.observers.map(observer => observer.getCurrentQuery());
2337
+ return this.#observers.map(observer => observer.getCurrentQuery());
2797
2338
  }
2798
-
2799
2339
  getObservers() {
2800
- return this.observers;
2340
+ return this.#observers;
2801
2341
  }
2802
-
2803
2342
  getOptimisticResult(queries) {
2804
- return this.findMatchingObservers(queries).map(match => match.observer.getOptimisticResult(match.defaultedQueryOptions));
2343
+ return this.#findMatchingObservers(queries).map(match => match.observer.getOptimisticResult(match.defaultedQueryOptions));
2805
2344
  }
2806
-
2807
- findMatchingObservers(queries) {
2808
- const prevObservers = this.observers;
2809
- const defaultedQueryOptions = queries.map(options => this.client.defaultQueryOptions(options));
2345
+ #findMatchingObservers(queries) {
2346
+ const prevObservers = this.#observers;
2347
+ const defaultedQueryOptions = queries.map(options => this.#client.defaultQueryOptions(options));
2810
2348
  const matchingObservers = defaultedQueryOptions.flatMap(defaultedOptions => {
2811
2349
  const match = prevObservers.find(observer => observer.options.queryHash === defaultedOptions.queryHash);
2812
-
2813
2350
  if (match != null) {
2814
2351
  return [{
2815
2352
  defaultedQueryOptions: defaultedOptions,
2816
2353
  observer: match
2817
2354
  }];
2818
2355
  }
2819
-
2820
2356
  return [];
2821
2357
  });
2822
2358
  const matchedQueryHashes = matchingObservers.map(match => match.defaultedQueryOptions.queryHash);
2823
2359
  const unmatchedQueries = defaultedQueryOptions.filter(defaultedOptions => !matchedQueryHashes.includes(defaultedOptions.queryHash));
2824
- const unmatchedObservers = prevObservers.filter(prevObserver => !matchingObservers.some(match => match.observer === prevObserver));
2825
-
2826
2360
  const getObserver = options => {
2827
- const defaultedOptions = this.client.defaultQueryOptions(options);
2828
- const currentObserver = this.observersMap[defaultedOptions.queryHash];
2829
- return currentObserver != null ? currentObserver : new QueryObserver(this.client, defaultedOptions);
2361
+ const defaultedOptions = this.#client.defaultQueryOptions(options);
2362
+ const currentObserver = this.#observersMap[defaultedOptions.queryHash];
2363
+ return currentObserver ?? new QueryObserver(this.#client, defaultedOptions);
2830
2364
  };
2831
-
2832
- const newOrReusedObservers = unmatchedQueries.map((options, index) => {
2833
- if (options.keepPreviousData) {
2834
- // return previous data from one of the observers that no longer match
2835
- const previouslyUsedObserver = unmatchedObservers[index];
2836
-
2837
- if (previouslyUsedObserver !== undefined) {
2838
- return {
2839
- defaultedQueryOptions: options,
2840
- observer: previouslyUsedObserver
2841
- };
2842
- }
2843
- }
2844
-
2365
+ const newOrReusedObservers = unmatchedQueries.map(options => {
2845
2366
  return {
2846
2367
  defaultedQueryOptions: options,
2847
2368
  observer: getObserver(options)
2848
2369
  };
2849
2370
  });
2850
-
2851
2371
  const sortMatchesByOrderOfQueries = (a, b) => defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions);
2852
-
2853
2372
  return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries);
2854
2373
  }
2855
-
2856
- onUpdate(observer, result) {
2857
- const index = this.observers.indexOf(observer);
2858
-
2374
+ #onUpdate(observer, result) {
2375
+ const index = this.#observers.indexOf(observer);
2859
2376
  if (index !== -1) {
2860
- this.result = replaceAt(this.result, index, result);
2861
- this.notify();
2377
+ this.#result = replaceAt(this.#result, index, result);
2378
+ this.#notify();
2862
2379
  }
2863
2380
  }
2864
-
2865
- notify() {
2381
+ #notify() {
2866
2382
  notifyManager.batch(() => {
2867
2383
  this.listeners.forEach(listener => {
2868
- listener(this.result);
2384
+ listener(this.#result);
2869
2385
  });
2870
2386
  });
2871
2387
  }
2872
-
2873
2388
  }
2874
2389
 
2875
2390
  class InfiniteQueryObserver extends QueryObserver {
2876
2391
  // Type override
2392
+
2877
2393
  // Type override
2394
+
2878
2395
  // Type override
2396
+
2879
2397
  // eslint-disable-next-line @typescript-eslint/no-useless-constructor
2880
2398
  constructor(client, options) {
2881
2399
  super(client, options);
2882
2400
  }
2883
-
2884
2401
  bindMethods() {
2885
2402
  super.bindMethods();
2886
2403
  this.fetchNextPage = this.fetchNextPage.bind(this);
2887
2404
  this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
2888
2405
  }
2889
-
2890
2406
  setOptions(options, notifyOptions) {
2891
- super.setOptions({ ...options,
2407
+ super.setOptions({
2408
+ ...options,
2892
2409
  behavior: infiniteQueryBehavior()
2893
2410
  }, notifyOptions);
2894
2411
  }
2895
-
2896
2412
  getOptimisticResult(options) {
2897
2413
  options.behavior = infiniteQueryBehavior();
2898
2414
  return super.getOptimisticResult(options);
2899
2415
  }
2900
-
2901
- fetchNextPage({
2902
- pageParam,
2903
- ...options
2904
- } = {}) {
2905
- return this.fetch({ ...options,
2416
+ fetchNextPage(options = {}) {
2417
+ return this.fetch({
2418
+ ...options,
2906
2419
  meta: {
2907
2420
  fetchMore: {
2908
- direction: 'forward',
2909
- pageParam
2421
+ direction: 'forward'
2910
2422
  }
2911
2423
  }
2912
2424
  });
2913
2425
  }
2914
-
2915
2426
  fetchPreviousPage({
2916
- pageParam,
2917
2427
  ...options
2918
2428
  } = {}) {
2919
- return this.fetch({ ...options,
2429
+ return this.fetch({
2430
+ ...options,
2920
2431
  meta: {
2921
2432
  fetchMore: {
2922
- direction: 'backward',
2923
- pageParam
2433
+ direction: 'backward'
2924
2434
  }
2925
2435
  }
2926
2436
  });
2927
2437
  }
2928
-
2929
2438
  createResult(query, options) {
2930
- var _state$fetchMeta, _state$fetchMeta$fetc, _state$fetchMeta2, _state$fetchMeta2$fet, _state$data, _state$data2;
2931
-
2932
2439
  const {
2933
2440
  state
2934
2441
  } = query;
@@ -2937,153 +2444,126 @@
2937
2444
  isFetching,
2938
2445
  isRefetching
2939
2446
  } = result;
2940
- const isFetchingNextPage = isFetching && ((_state$fetchMeta = state.fetchMeta) == null ? void 0 : (_state$fetchMeta$fetc = _state$fetchMeta.fetchMore) == null ? void 0 : _state$fetchMeta$fetc.direction) === 'forward';
2941
- const isFetchingPreviousPage = isFetching && ((_state$fetchMeta2 = state.fetchMeta) == null ? void 0 : (_state$fetchMeta2$fet = _state$fetchMeta2.fetchMore) == null ? void 0 : _state$fetchMeta2$fet.direction) === 'backward';
2942
- return { ...result,
2447
+ const isFetchingNextPage = isFetching && state.fetchMeta?.fetchMore?.direction === 'forward';
2448
+ const isFetchingPreviousPage = isFetching && state.fetchMeta?.fetchMore?.direction === 'backward';
2449
+ return {
2450
+ ...result,
2943
2451
  fetchNextPage: this.fetchNextPage,
2944
2452
  fetchPreviousPage: this.fetchPreviousPage,
2945
- hasNextPage: hasNextPage(options, (_state$data = state.data) == null ? void 0 : _state$data.pages),
2946
- hasPreviousPage: hasPreviousPage(options, (_state$data2 = state.data) == null ? void 0 : _state$data2.pages),
2453
+ hasNextPage: hasNextPage(options, state.data?.pages),
2454
+ hasPreviousPage: hasPreviousPage(options, state.data?.pages),
2947
2455
  isFetchingNextPage,
2948
2456
  isFetchingPreviousPage,
2949
2457
  isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage
2950
2458
  };
2951
2459
  }
2952
-
2953
2460
  }
2954
2461
 
2462
+ // TYPES
2463
+
2955
2464
  // CLASS
2465
+
2956
2466
  class MutationObserver extends Subscribable {
2467
+ #client;
2468
+ #currentResult = undefined;
2469
+ #currentMutation;
2470
+ #mutateOptions;
2957
2471
  constructor(client, options) {
2958
2472
  super();
2959
- this.client = client;
2473
+ this.#client = client;
2960
2474
  this.setOptions(options);
2961
2475
  this.bindMethods();
2962
- this.updateResult();
2476
+ this.#updateResult();
2963
2477
  }
2964
-
2965
2478
  bindMethods() {
2966
2479
  this.mutate = this.mutate.bind(this);
2967
2480
  this.reset = this.reset.bind(this);
2968
2481
  }
2969
-
2970
2482
  setOptions(options) {
2971
2483
  const prevOptions = this.options;
2972
- this.options = this.client.defaultMutationOptions(options);
2973
-
2484
+ this.options = this.#client.defaultMutationOptions(options);
2974
2485
  if (!shallowEqualObjects(prevOptions, this.options)) {
2975
- this.client.getMutationCache().notify({
2486
+ this.#client.getMutationCache().notify({
2976
2487
  type: 'observerOptionsUpdated',
2977
- mutation: this.currentMutation,
2488
+ mutation: this.#currentMutation,
2978
2489
  observer: this
2979
2490
  });
2980
2491
  }
2981
2492
  }
2982
-
2983
2493
  onUnsubscribe() {
2984
2494
  if (!this.listeners.length) {
2985
- var _this$currentMutation;
2986
-
2987
- (_this$currentMutation = this.currentMutation) == null ? void 0 : _this$currentMutation.removeObserver(this);
2495
+ this.#currentMutation?.removeObserver(this);
2988
2496
  }
2989
2497
  }
2990
-
2991
2498
  onMutationUpdate(action) {
2992
- this.updateResult(); // Determine which callbacks to trigger
2993
-
2994
- const notifyOptions = {
2995
- listeners: true
2996
- };
2997
-
2998
- if (action.type === 'success') {
2999
- notifyOptions.onSuccess = true;
3000
- } else if (action.type === 'error') {
3001
- notifyOptions.onError = true;
3002
- }
3003
-
3004
- this.notify(notifyOptions);
2499
+ this.#updateResult();
2500
+ this.#notify(action);
3005
2501
  }
3006
-
3007
2502
  getCurrentResult() {
3008
- return this.currentResult;
2503
+ return this.#currentResult;
3009
2504
  }
3010
-
3011
2505
  reset() {
3012
- this.currentMutation = undefined;
3013
- this.updateResult();
3014
- this.notify({
3015
- listeners: true
3016
- });
2506
+ this.#currentMutation = undefined;
2507
+ this.#updateResult();
2508
+ this.#notify();
3017
2509
  }
3018
-
3019
2510
  mutate(variables, options) {
3020
- this.mutateOptions = options;
3021
-
3022
- if (this.currentMutation) {
3023
- this.currentMutation.removeObserver(this);
3024
- }
3025
-
3026
- this.currentMutation = this.client.getMutationCache().build(this.client, { ...this.options,
3027
- variables: typeof variables !== 'undefined' ? variables : this.options.variables
2511
+ this.#mutateOptions = options;
2512
+ this.#currentMutation?.removeObserver(this);
2513
+ this.#currentMutation = this.#client.getMutationCache().build(this.#client, {
2514
+ ...this.options
3028
2515
  });
3029
- this.currentMutation.addObserver(this);
3030
- return this.currentMutation.execute();
3031
- }
3032
-
3033
- updateResult() {
3034
- const state = this.currentMutation ? this.currentMutation.state : getDefaultState();
3035
- const result = { ...state,
3036
- isLoading: state.status === 'loading',
2516
+ this.#currentMutation.addObserver(this);
2517
+ return this.#currentMutation.execute(variables);
2518
+ }
2519
+ #updateResult() {
2520
+ const state = this.#currentMutation?.state ?? getDefaultState();
2521
+ this.#currentResult = {
2522
+ ...state,
2523
+ isPending: state.status === 'pending',
3037
2524
  isSuccess: state.status === 'success',
3038
2525
  isError: state.status === 'error',
3039
2526
  isIdle: state.status === 'idle',
3040
2527
  mutate: this.mutate,
3041
2528
  reset: this.reset
3042
2529
  };
3043
- this.currentResult = result;
3044
2530
  }
3045
-
3046
- notify(options) {
2531
+ #notify(action) {
3047
2532
  notifyManager.batch(() => {
3048
2533
  // First trigger the mutate callbacks
3049
- if (this.mutateOptions && this.hasListeners()) {
3050
- if (options.onSuccess) {
3051
- var _this$mutateOptions$o, _this$mutateOptions, _this$mutateOptions$o2, _this$mutateOptions2;
3052
-
3053
- (_this$mutateOptions$o = (_this$mutateOptions = this.mutateOptions).onSuccess) == null ? void 0 : _this$mutateOptions$o.call(_this$mutateOptions, this.currentResult.data, this.currentResult.variables, this.currentResult.context);
3054
- (_this$mutateOptions$o2 = (_this$mutateOptions2 = this.mutateOptions).onSettled) == null ? void 0 : _this$mutateOptions$o2.call(_this$mutateOptions2, this.currentResult.data, null, this.currentResult.variables, this.currentResult.context);
3055
- } else if (options.onError) {
3056
- var _this$mutateOptions$o3, _this$mutateOptions3, _this$mutateOptions$o4, _this$mutateOptions4;
3057
-
3058
- (_this$mutateOptions$o3 = (_this$mutateOptions3 = this.mutateOptions).onError) == null ? void 0 : _this$mutateOptions$o3.call(_this$mutateOptions3, this.currentResult.error, this.currentResult.variables, this.currentResult.context);
3059
- (_this$mutateOptions$o4 = (_this$mutateOptions4 = this.mutateOptions).onSettled) == null ? void 0 : _this$mutateOptions$o4.call(_this$mutateOptions4, undefined, this.currentResult.error, this.currentResult.variables, this.currentResult.context);
2534
+ if (this.#mutateOptions && this.hasListeners()) {
2535
+ if (action?.type === 'success') {
2536
+ this.#mutateOptions.onSuccess?.(action.data, this.#currentResult.variables, this.#currentResult.context);
2537
+ this.#mutateOptions.onSettled?.(action.data, null, this.#currentResult.variables, this.#currentResult.context);
2538
+ } else if (action?.type === 'error') {
2539
+ this.#mutateOptions.onError?.(action.error, this.#currentResult.variables, this.#currentResult.context);
2540
+ this.#mutateOptions.onSettled?.(undefined, action.error, this.#currentResult.variables, this.#currentResult.context);
3060
2541
  }
3061
- } // Then trigger the listeners
3062
-
3063
-
3064
- if (options.listeners) {
3065
- this.listeners.forEach(listener => {
3066
- listener(this.currentResult);
3067
- });
3068
2542
  }
2543
+
2544
+ // Then trigger the listeners
2545
+ this.listeners.forEach(listener => {
2546
+ listener(this.#currentResult);
2547
+ });
3069
2548
  });
3070
2549
  }
3071
-
3072
2550
  }
3073
2551
 
3074
2552
  // TYPES
2553
+
3075
2554
  // FUNCTIONS
2555
+
3076
2556
  function dehydrateMutation(mutation) {
3077
2557
  return {
3078
2558
  mutationKey: mutation.options.mutationKey,
3079
2559
  state: mutation.state
3080
2560
  };
3081
- } // Most config is not dehydrated but instead meant to configure again when
2561
+ }
2562
+
2563
+ // Most config is not dehydrated but instead meant to configure again when
3082
2564
  // consuming the de/rehydrated data, typically with useQuery on the client.
3083
2565
  // Sometimes it might make sense to prefetch data on the server and include
3084
2566
  // in the html-payload, but not consume it on the initial render.
3085
-
3086
-
3087
2567
  function dehydrateQuery(query) {
3088
2568
  return {
3089
2569
  state: query.state,
@@ -3091,7 +2571,6 @@
3091
2571
  queryHash: query.queryHash
3092
2572
  };
3093
2573
  }
3094
-
3095
2574
  function defaultShouldDehydrateMutation(mutation) {
3096
2575
  return mutation.state.isPaused;
3097
2576
  }
@@ -3101,7 +2580,6 @@
3101
2580
  function dehydrate(client, options = {}) {
3102
2581
  const mutations = [];
3103
2582
  const queries = [];
3104
-
3105
2583
  if (options.dehydrateMutations !== false) {
3106
2584
  const shouldDehydrateMutation = options.shouldDehydrateMutation || defaultShouldDehydrateMutation;
3107
2585
  client.getMutationCache().getAll().forEach(mutation => {
@@ -3110,7 +2588,6 @@
3110
2588
  }
3111
2589
  });
3112
2590
  }
3113
-
3114
2591
  if (options.dehydrateQueries !== false) {
3115
2592
  const shouldDehydrateQuery = options.shouldDehydrateQuery || defaultShouldDehydrateQuery;
3116
2593
  client.getQueryCache().getAll().forEach(query => {
@@ -3119,7 +2596,6 @@
3119
2596
  }
3120
2597
  });
3121
2598
  }
3122
-
3123
2599
  return {
3124
2600
  mutations,
3125
2601
  queries
@@ -3129,40 +2605,40 @@
3129
2605
  if (typeof dehydratedState !== 'object' || dehydratedState === null) {
3130
2606
  return;
3131
2607
  }
3132
-
3133
2608
  const mutationCache = client.getMutationCache();
3134
- const queryCache = client.getQueryCache(); // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3135
-
3136
- const mutations = dehydratedState.mutations || []; // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2609
+ const queryCache = client.getQueryCache();
3137
2610
 
2611
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
2612
+ const mutations = dehydratedState.mutations || [];
2613
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3138
2614
  const queries = dehydratedState.queries || [];
3139
2615
  mutations.forEach(dehydratedMutation => {
3140
- var _options$defaultOptio;
3141
-
3142
- mutationCache.build(client, { ...(options == null ? void 0 : (_options$defaultOptio = options.defaultOptions) == null ? void 0 : _options$defaultOptio.mutations),
2616
+ mutationCache.build(client, {
2617
+ ...options?.defaultOptions?.mutations,
3143
2618
  mutationKey: dehydratedMutation.mutationKey
3144
2619
  }, dehydratedMutation.state);
3145
2620
  });
3146
2621
  queries.forEach(dehydratedQuery => {
3147
- var _options$defaultOptio2;
2622
+ const query = queryCache.get(dehydratedQuery.queryHash);
3148
2623
 
3149
- const query = queryCache.get(dehydratedQuery.queryHash); // Reset fetch status to idle in the dehydrated state to avoid
2624
+ // Reset fetch status to idle in the dehydrated state to avoid
3150
2625
  // query being stuck in fetching state upon hydration
3151
-
3152
- const dehydratedQueryState = { ...dehydratedQuery.state,
2626
+ const dehydratedQueryState = {
2627
+ ...dehydratedQuery.state,
3153
2628
  fetchStatus: 'idle'
3154
- }; // Do not hydrate if an existing query exists with newer data
2629
+ };
3155
2630
 
2631
+ // Do not hydrate if an existing query exists with newer data
3156
2632
  if (query) {
3157
2633
  if (query.state.dataUpdatedAt < dehydratedQueryState.dataUpdatedAt) {
3158
2634
  query.setState(dehydratedQueryState);
3159
2635
  }
3160
-
3161
2636
  return;
3162
- } // Restore query
3163
-
2637
+ }
3164
2638
 
3165
- queryCache.build(client, { ...(options == null ? void 0 : (_options$defaultOptio2 = options.defaultOptions) == null ? void 0 : _options$defaultOptio2.queries),
2639
+ // Restore query
2640
+ queryCache.build(client, {
2641
+ ...options?.defaultOptions?.queries,
3166
2642
  queryKey: dehydratedQuery.queryKey,
3167
2643
  queryHash: dehydratedQuery.queryHash
3168
2644
  }, dehydratedQueryState);
@@ -3181,20 +2657,14 @@
3181
2657
  exports.defaultShouldDehydrateQuery = defaultShouldDehydrateQuery;
3182
2658
  exports.dehydrate = dehydrate;
3183
2659
  exports.focusManager = focusManager;
3184
- exports.hashQueryKey = hashQueryKey;
2660
+ exports.hashKey = hashKey;
3185
2661
  exports.hydrate = hydrate;
3186
2662
  exports.isCancelledError = isCancelledError;
3187
- exports.isError = isError;
3188
2663
  exports.isServer = isServer;
2664
+ exports.keepPreviousData = keepPreviousData;
3189
2665
  exports.notifyManager = notifyManager;
3190
2666
  exports.onlineManager = onlineManager;
3191
- exports.parseFilterArgs = parseFilterArgs;
3192
- exports.parseMutationArgs = parseMutationArgs;
3193
- exports.parseMutationFilterArgs = parseMutationFilterArgs;
3194
- exports.parseQueryArgs = parseQueryArgs;
3195
2667
  exports.replaceEqualDeep = replaceEqualDeep;
3196
2668
 
3197
- Object.defineProperty(exports, '__esModule', { value: true });
3198
-
3199
2669
  }));
3200
2670
  //# sourceMappingURL=index.development.js.map