@tanstack/react-query 4.0.5

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