@tanstack/react-query 4.39.0 → 4.39.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/build/lib/Hydrate.esm.js +32 -0
  2. package/build/lib/Hydrate.esm.js.map +1 -0
  3. package/build/lib/Hydrate.js +57 -0
  4. package/build/lib/Hydrate.js.map +1 -0
  5. package/build/lib/Hydrate.mjs +32 -0
  6. package/build/lib/Hydrate.mjs.map +1 -0
  7. package/build/lib/QueryClientProvider.esm.js +66 -0
  8. package/build/lib/QueryClientProvider.esm.js.map +1 -0
  9. package/build/lib/QueryClientProvider.js +92 -0
  10. package/build/lib/QueryClientProvider.js.map +1 -0
  11. package/build/lib/QueryClientProvider.mjs +66 -0
  12. package/build/lib/QueryClientProvider.mjs.map +1 -0
  13. package/build/lib/QueryErrorResetBoundary.esm.js +33 -0
  14. package/build/lib/QueryErrorResetBoundary.esm.js.map +1 -0
  15. package/build/lib/QueryErrorResetBoundary.js +58 -0
  16. package/build/lib/QueryErrorResetBoundary.js.map +1 -0
  17. package/build/lib/QueryErrorResetBoundary.mjs +33 -0
  18. package/build/lib/QueryErrorResetBoundary.mjs.map +1 -0
  19. package/build/lib/errorBoundaryUtils.esm.js +28 -0
  20. package/build/lib/errorBoundaryUtils.esm.js.map +1 -0
  21. package/build/lib/errorBoundaryUtils.js +54 -0
  22. package/build/lib/errorBoundaryUtils.js.map +1 -0
  23. package/build/lib/errorBoundaryUtils.mjs +28 -0
  24. package/build/lib/errorBoundaryUtils.mjs.map +1 -0
  25. package/build/lib/index.esm.js +16 -0
  26. package/build/lib/index.esm.js.map +1 -0
  27. package/build/lib/index.js +47 -0
  28. package/build/lib/index.js.map +1 -0
  29. package/build/lib/index.mjs +16 -0
  30. package/build/lib/index.mjs.map +1 -0
  31. package/build/lib/isRestoring.esm.js +9 -0
  32. package/build/lib/isRestoring.esm.js.map +1 -0
  33. package/build/lib/isRestoring.js +34 -0
  34. package/build/lib/isRestoring.js.map +1 -0
  35. package/build/lib/isRestoring.mjs +9 -0
  36. package/build/lib/isRestoring.mjs.map +1 -0
  37. package/build/lib/queryOptions.esm.js +6 -0
  38. package/build/lib/queryOptions.esm.js.map +1 -0
  39. package/build/lib/queryOptions.js +10 -0
  40. package/build/lib/queryOptions.js.map +1 -0
  41. package/build/lib/queryOptions.mjs +6 -0
  42. package/build/lib/queryOptions.mjs.map +1 -0
  43. package/build/lib/reactBatchedUpdates.esm.js +7 -0
  44. package/build/lib/reactBatchedUpdates.esm.js.map +1 -0
  45. package/build/lib/reactBatchedUpdates.js +31 -0
  46. package/build/lib/reactBatchedUpdates.js.map +1 -0
  47. package/build/lib/reactBatchedUpdates.mjs +7 -0
  48. package/build/lib/reactBatchedUpdates.mjs.map +1 -0
  49. package/build/lib/reactBatchedUpdates.native.esm.js +2 -0
  50. package/build/lib/reactBatchedUpdates.native.esm.js.map +1 -0
  51. package/build/lib/reactBatchedUpdates.native.js +13 -0
  52. package/build/lib/reactBatchedUpdates.native.js.map +1 -0
  53. package/build/lib/reactBatchedUpdates.native.mjs +2 -0
  54. package/build/lib/reactBatchedUpdates.native.mjs.map +1 -0
  55. package/build/lib/setBatchUpdatesFn.esm.js +5 -0
  56. package/build/lib/setBatchUpdatesFn.esm.js.map +1 -0
  57. package/build/lib/setBatchUpdatesFn.js +7 -0
  58. package/build/lib/setBatchUpdatesFn.js.map +1 -0
  59. package/build/lib/setBatchUpdatesFn.mjs +5 -0
  60. package/build/lib/setBatchUpdatesFn.mjs.map +1 -0
  61. package/build/lib/suspense.esm.js +24 -0
  62. package/build/lib/suspense.esm.js.map +1 -0
  63. package/build/lib/suspense.js +31 -0
  64. package/build/lib/suspense.js.map +1 -0
  65. package/build/lib/suspense.mjs +24 -0
  66. package/build/lib/suspense.mjs.map +1 -0
  67. package/build/lib/useBaseQuery.esm.js +72 -0
  68. package/build/lib/useBaseQuery.esm.js.map +1 -0
  69. package/build/lib/useBaseQuery.js +96 -0
  70. package/build/lib/useBaseQuery.js.map +1 -0
  71. package/build/lib/useBaseQuery.mjs +72 -0
  72. package/build/lib/useBaseQuery.mjs.map +1 -0
  73. package/build/lib/useInfiniteQuery.esm.js +11 -0
  74. package/build/lib/useInfiniteQuery.esm.js.map +1 -0
  75. package/build/lib/useInfiniteQuery.js +15 -0
  76. package/build/lib/useInfiniteQuery.js.map +1 -0
  77. package/build/lib/useInfiniteQuery.mjs +11 -0
  78. package/build/lib/useInfiniteQuery.mjs.map +1 -0
  79. package/build/lib/useIsFetching.esm.js +17 -0
  80. package/build/lib/useIsFetching.esm.js.map +1 -0
  81. package/build/lib/useIsFetching.js +41 -0
  82. package/build/lib/useIsFetching.js.map +1 -0
  83. package/build/lib/useIsFetching.mjs +17 -0
  84. package/build/lib/useIsFetching.mjs.map +1 -0
  85. package/build/lib/useIsMutating.esm.js +17 -0
  86. package/build/lib/useIsMutating.esm.js.map +1 -0
  87. package/build/lib/useIsMutating.js +41 -0
  88. package/build/lib/useIsMutating.js.map +1 -0
  89. package/build/lib/useIsMutating.mjs +17 -0
  90. package/build/lib/useIsMutating.mjs.map +1 -0
  91. package/build/lib/useMutation.esm.js +35 -0
  92. package/build/lib/useMutation.esm.js.map +1 -0
  93. package/build/lib/useMutation.js +59 -0
  94. package/build/lib/useMutation.js.map +1 -0
  95. package/build/lib/useMutation.mjs +35 -0
  96. package/build/lib/useMutation.mjs.map +1 -0
  97. package/build/lib/useQueries.esm.js +81 -0
  98. package/build/lib/useQueries.esm.js.map +1 -0
  99. package/build/lib/useQueries.js +105 -0
  100. package/build/lib/useQueries.js.map +1 -0
  101. package/build/lib/useQueries.mjs +81 -0
  102. package/build/lib/useQueries.mjs.map +1 -0
  103. package/build/lib/useQuery.esm.js +12 -0
  104. package/build/lib/useQuery.esm.js.map +1 -0
  105. package/build/lib/useQuery.js +16 -0
  106. package/build/lib/useQuery.js.map +1 -0
  107. package/build/lib/useQuery.mjs +12 -0
  108. package/build/lib/useQuery.mjs.map +1 -0
  109. package/build/lib/useSuspenseQueries.esm.js +20 -0
  110. package/build/lib/useSuspenseQueries.esm.js.map +1 -0
  111. package/build/lib/useSuspenseQueries.js +24 -0
  112. package/build/lib/useSuspenseQueries.js.map +1 -0
  113. package/build/lib/useSuspenseQueries.mjs +20 -0
  114. package/build/lib/useSuspenseQueries.mjs.map +1 -0
  115. package/build/lib/useSuspenseQuery.esm.js +15 -0
  116. package/build/lib/useSuspenseQuery.esm.js.map +1 -0
  117. package/build/lib/useSuspenseQuery.js +19 -0
  118. package/build/lib/useSuspenseQuery.js.map +1 -0
  119. package/build/lib/useSuspenseQuery.mjs +15 -0
  120. package/build/lib/useSuspenseQuery.mjs.map +1 -0
  121. package/build/lib/useSyncExternalStore.esm.js +7 -0
  122. package/build/lib/useSyncExternalStore.esm.js.map +1 -0
  123. package/build/lib/useSyncExternalStore.js +11 -0
  124. package/build/lib/useSyncExternalStore.js.map +1 -0
  125. package/build/lib/useSyncExternalStore.mjs +7 -0
  126. package/build/lib/useSyncExternalStore.mjs.map +1 -0
  127. package/build/lib/useSyncExternalStore.native.esm.js +2 -0
  128. package/build/lib/useSyncExternalStore.native.esm.js.map +1 -0
  129. package/build/lib/useSyncExternalStore.native.js +13 -0
  130. package/build/lib/useSyncExternalStore.native.js.map +1 -0
  131. package/build/lib/useSyncExternalStore.native.mjs +2 -0
  132. package/build/lib/useSyncExternalStore.native.mjs.map +1 -0
  133. package/build/lib/utils.esm.js +11 -0
  134. package/build/lib/utils.esm.js.map +1 -0
  135. package/build/lib/utils.js +15 -0
  136. package/build/lib/utils.js.map +1 -0
  137. package/build/lib/utils.mjs +11 -0
  138. package/build/lib/utils.mjs.map +1 -0
  139. package/build/umd/index.development.js +4049 -0
  140. package/build/umd/index.development.js.map +1 -0
  141. package/build/umd/index.production.js +2 -0
  142. package/build/umd/index.production.js.map +1 -0
  143. package/package.json +2 -2
@@ -0,0 +1,4049 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react-dom'), require('react')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'react-dom', 'react'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactQuery = {}, global.ReactDOM, global.React));
5
+ })(this, (function (exports, ReactDOM, React) { 'use strict';
6
+
7
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
+
9
+ function _interopNamespace(e) {
10
+ if (e && e.__esModule) return e;
11
+ var n = Object.create(null);
12
+ if (e) {
13
+ Object.keys(e).forEach(function (k) {
14
+ if (k !== 'default') {
15
+ var d = Object.getOwnPropertyDescriptor(e, k);
16
+ Object.defineProperty(n, k, d.get ? d : {
17
+ enumerable: true,
18
+ get: function () { return e[k]; }
19
+ });
20
+ }
21
+ });
22
+ }
23
+ n["default"] = e;
24
+ return Object.freeze(n);
25
+ }
26
+
27
+ var ReactDOM__namespace = /*#__PURE__*/_interopNamespace(ReactDOM);
28
+ var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
29
+ var React__namespace = /*#__PURE__*/_interopNamespace(React);
30
+
31
+ class Subscribable {
32
+ constructor() {
33
+ this.listeners = new Set();
34
+ this.subscribe = this.subscribe.bind(this);
35
+ }
36
+
37
+ subscribe(listener) {
38
+ const identity = {
39
+ listener
40
+ };
41
+ this.listeners.add(identity);
42
+ this.onSubscribe();
43
+ return () => {
44
+ this.listeners.delete(identity);
45
+ this.onUnsubscribe();
46
+ };
47
+ }
48
+
49
+ hasListeners() {
50
+ return this.listeners.size > 0;
51
+ }
52
+
53
+ onSubscribe() {// Do nothing
54
+ }
55
+
56
+ onUnsubscribe() {// Do nothing
57
+ }
58
+
59
+ }
60
+
61
+ // TYPES
62
+ // UTILS
63
+ const isServer = typeof window === 'undefined' || 'Deno' in window;
64
+ function noop$1() {
65
+ return undefined;
66
+ }
67
+ function functionalUpdate(updater, input) {
68
+ return typeof updater === 'function' ? updater(input) : updater;
69
+ }
70
+ function isValidTimeout(value) {
71
+ return typeof value === 'number' && value >= 0 && value !== Infinity;
72
+ }
73
+ function difference(array1, array2) {
74
+ return array1.filter(x => !array2.includes(x));
75
+ }
76
+ function replaceAt(array, index, value) {
77
+ const copy = array.slice(0);
78
+ copy[index] = value;
79
+ return copy;
80
+ }
81
+ function timeUntilStale(updatedAt, staleTime) {
82
+ return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0);
83
+ }
84
+ function parseQueryArgs(arg1, arg2, arg3) {
85
+ if (!isQueryKey(arg1)) {
86
+ return arg1;
87
+ }
88
+
89
+ if (typeof arg2 === 'function') {
90
+ return { ...arg3,
91
+ queryKey: arg1,
92
+ queryFn: arg2
93
+ };
94
+ }
95
+
96
+ return { ...arg2,
97
+ queryKey: arg1
98
+ };
99
+ }
100
+ function parseMutationArgs(arg1, arg2, arg3) {
101
+ if (isQueryKey(arg1)) {
102
+ if (typeof arg2 === 'function') {
103
+ return { ...arg3,
104
+ mutationKey: arg1,
105
+ mutationFn: arg2
106
+ };
107
+ }
108
+
109
+ return { ...arg2,
110
+ mutationKey: arg1
111
+ };
112
+ }
113
+
114
+ if (typeof arg1 === 'function') {
115
+ return { ...arg2,
116
+ mutationFn: arg1
117
+ };
118
+ }
119
+
120
+ return { ...arg1
121
+ };
122
+ }
123
+ function parseFilterArgs(arg1, arg2, arg3) {
124
+ return isQueryKey(arg1) ? [{ ...arg2,
125
+ queryKey: arg1
126
+ }, arg3] : [arg1 || {}, arg2];
127
+ }
128
+ function parseMutationFilterArgs(arg1, arg2, arg3) {
129
+ return isQueryKey(arg1) ? [{ ...arg2,
130
+ mutationKey: arg1
131
+ }, arg3] : [arg1 || {}, arg2];
132
+ }
133
+ function matchQuery(filters, query) {
134
+ const {
135
+ type = 'all',
136
+ exact,
137
+ fetchStatus,
138
+ predicate,
139
+ queryKey,
140
+ stale
141
+ } = filters;
142
+
143
+ if (isQueryKey(queryKey)) {
144
+ if (exact) {
145
+ if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {
146
+ return false;
147
+ }
148
+ } else if (!partialMatchKey(query.queryKey, queryKey)) {
149
+ return false;
150
+ }
151
+ }
152
+
153
+ if (type !== 'all') {
154
+ const isActive = query.isActive();
155
+
156
+ if (type === 'active' && !isActive) {
157
+ return false;
158
+ }
159
+
160
+ if (type === 'inactive' && isActive) {
161
+ return false;
162
+ }
163
+ }
164
+
165
+ if (typeof stale === 'boolean' && query.isStale() !== stale) {
166
+ return false;
167
+ }
168
+
169
+ if (typeof fetchStatus !== 'undefined' && fetchStatus !== query.state.fetchStatus) {
170
+ return false;
171
+ }
172
+
173
+ if (predicate && !predicate(query)) {
174
+ return false;
175
+ }
176
+
177
+ return true;
178
+ }
179
+ function matchMutation(filters, mutation) {
180
+ const {
181
+ exact,
182
+ fetching,
183
+ predicate,
184
+ mutationKey
185
+ } = filters;
186
+
187
+ if (isQueryKey(mutationKey)) {
188
+ if (!mutation.options.mutationKey) {
189
+ return false;
190
+ }
191
+
192
+ if (exact) {
193
+ if (hashQueryKey(mutation.options.mutationKey) !== hashQueryKey(mutationKey)) {
194
+ return false;
195
+ }
196
+ } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {
197
+ return false;
198
+ }
199
+ }
200
+
201
+ if (typeof fetching === 'boolean' && mutation.state.status === 'loading' !== fetching) {
202
+ return false;
203
+ }
204
+
205
+ if (predicate && !predicate(mutation)) {
206
+ return false;
207
+ }
208
+
209
+ return true;
210
+ }
211
+ function hashQueryKeyByOptions(queryKey, options) {
212
+ const hashFn = (options == null ? void 0 : options.queryKeyHashFn) || hashQueryKey;
213
+ return hashFn(queryKey);
214
+ }
215
+ /**
216
+ * Default query keys hash function.
217
+ * Hashes the value into a stable hash.
218
+ */
219
+
220
+ function hashQueryKey(queryKey) {
221
+ return JSON.stringify(queryKey, (_, val) => isPlainObject(val) ? Object.keys(val).sort().reduce((result, key) => {
222
+ result[key] = val[key];
223
+ return result;
224
+ }, {}) : val);
225
+ }
226
+ /**
227
+ * Checks if key `b` partially matches with key `a`.
228
+ */
229
+
230
+ function partialMatchKey(a, b) {
231
+ return partialDeepEqual(a, b);
232
+ }
233
+ /**
234
+ * Checks if `b` partially matches with `a`.
235
+ */
236
+
237
+ function partialDeepEqual(a, b) {
238
+ if (a === b) {
239
+ return true;
240
+ }
241
+
242
+ if (typeof a !== typeof b) {
243
+ return false;
244
+ }
245
+
246
+ if (a && b && typeof a === 'object' && typeof b === 'object') {
247
+ return !Object.keys(b).some(key => !partialDeepEqual(a[key], b[key]));
248
+ }
249
+
250
+ return false;
251
+ }
252
+ /**
253
+ * This function returns `a` if `b` is deeply equal.
254
+ * If not, it will replace any deeply equal children of `b` with those of `a`.
255
+ * This can be used for structural sharing between JSON values for example.
256
+ */
257
+
258
+ function replaceEqualDeep(a, b) {
259
+ if (a === b) {
260
+ return a;
261
+ }
262
+
263
+ const array = isPlainArray(a) && isPlainArray(b);
264
+
265
+ if (array || isPlainObject(a) && isPlainObject(b)) {
266
+ const aSize = array ? a.length : Object.keys(a).length;
267
+ const bItems = array ? b : Object.keys(b);
268
+ const bSize = bItems.length;
269
+ const copy = array ? [] : {};
270
+ let equalItems = 0;
271
+
272
+ for (let i = 0; i < bSize; i++) {
273
+ const key = array ? i : bItems[i];
274
+ copy[key] = replaceEqualDeep(a[key], b[key]);
275
+
276
+ if (copy[key] === a[key]) {
277
+ equalItems++;
278
+ }
279
+ }
280
+
281
+ return aSize === bSize && equalItems === aSize ? a : copy;
282
+ }
283
+
284
+ return b;
285
+ }
286
+ /**
287
+ * Shallow compare objects. Only works with objects that always have the same properties.
288
+ */
289
+
290
+ function shallowEqualObjects(a, b) {
291
+ if (a && !b || b && !a) {
292
+ return false;
293
+ }
294
+
295
+ for (const key in a) {
296
+ if (a[key] !== b[key]) {
297
+ return false;
298
+ }
299
+ }
300
+
301
+ return true;
302
+ }
303
+ function isPlainArray(value) {
304
+ return Array.isArray(value) && value.length === Object.keys(value).length;
305
+ } // Copied from: https://github.com/jonschlinkert/is-plain-object
306
+
307
+ function isPlainObject(o) {
308
+ if (!hasObjectPrototype(o)) {
309
+ return false;
310
+ } // If has modified constructor
311
+
312
+
313
+ const ctor = o.constructor;
314
+
315
+ if (typeof ctor === 'undefined') {
316
+ return true;
317
+ } // If has modified prototype
318
+
319
+
320
+ const prot = ctor.prototype;
321
+
322
+ if (!hasObjectPrototype(prot)) {
323
+ return false;
324
+ } // If constructor does not have an Object-specific method
325
+
326
+
327
+ if (!prot.hasOwnProperty('isPrototypeOf')) {
328
+ return false;
329
+ } // Most likely a plain Object
330
+
331
+
332
+ return true;
333
+ }
334
+
335
+ function hasObjectPrototype(o) {
336
+ return Object.prototype.toString.call(o) === '[object Object]';
337
+ }
338
+
339
+ function isQueryKey(value) {
340
+ return Array.isArray(value);
341
+ }
342
+ function isError(value) {
343
+ return value instanceof Error;
344
+ }
345
+ function sleep(timeout) {
346
+ return new Promise(resolve => {
347
+ setTimeout(resolve, timeout);
348
+ });
349
+ }
350
+ /**
351
+ * Schedules a microtask.
352
+ * This can be useful to schedule state updates after rendering.
353
+ */
354
+
355
+ function scheduleMicrotask(callback) {
356
+ sleep(0).then(callback);
357
+ }
358
+ function getAbortController() {
359
+ if (typeof AbortController === 'function') {
360
+ return new AbortController();
361
+ }
362
+
363
+ return;
364
+ }
365
+ function replaceData(prevData, data, options) {
366
+ // Use prev data if an isDataEqual function is defined and returns `true`
367
+ if (options.isDataEqual != null && options.isDataEqual(prevData, data)) {
368
+ return prevData;
369
+ } else if (typeof options.structuralSharing === 'function') {
370
+ return options.structuralSharing(prevData, data);
371
+ } else if (options.structuralSharing !== false) {
372
+ // Structurally share data between prev and new data if needed
373
+ return replaceEqualDeep(prevData, data);
374
+ }
375
+
376
+ return data;
377
+ }
378
+
379
+ class FocusManager extends Subscribable {
380
+ constructor() {
381
+ super();
382
+
383
+ this.setup = onFocus => {
384
+ // addEventListener does not exist in React Native, but window does
385
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
386
+ if (!isServer && window.addEventListener) {
387
+ const listener = () => onFocus(); // Listen to visibillitychange and focus
388
+
389
+
390
+ window.addEventListener('visibilitychange', listener, false);
391
+ window.addEventListener('focus', listener, false);
392
+ return () => {
393
+ // Be sure to unsubscribe if a new handler is set
394
+ window.removeEventListener('visibilitychange', listener);
395
+ window.removeEventListener('focus', listener);
396
+ };
397
+ }
398
+
399
+ return;
400
+ };
401
+ }
402
+
403
+ onSubscribe() {
404
+ if (!this.cleanup) {
405
+ this.setEventListener(this.setup);
406
+ }
407
+ }
408
+
409
+ onUnsubscribe() {
410
+ if (!this.hasListeners()) {
411
+ var _this$cleanup;
412
+
413
+ (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
414
+ this.cleanup = undefined;
415
+ }
416
+ }
417
+
418
+ setEventListener(setup) {
419
+ var _this$cleanup2;
420
+
421
+ this.setup = setup;
422
+ (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
423
+ this.cleanup = setup(focused => {
424
+ if (typeof focused === 'boolean') {
425
+ this.setFocused(focused);
426
+ } else {
427
+ this.onFocus();
428
+ }
429
+ });
430
+ }
431
+
432
+ setFocused(focused) {
433
+ const changed = this.focused !== focused;
434
+
435
+ if (changed) {
436
+ this.focused = focused;
437
+ this.onFocus();
438
+ }
439
+ }
440
+
441
+ onFocus() {
442
+ this.listeners.forEach(({
443
+ listener
444
+ }) => {
445
+ listener();
446
+ });
447
+ }
448
+
449
+ isFocused() {
450
+ if (typeof this.focused === 'boolean') {
451
+ return this.focused;
452
+ } // document global can be unavailable in react native
453
+
454
+
455
+ if (typeof document === 'undefined') {
456
+ return true;
457
+ }
458
+
459
+ return [undefined, 'visible', 'prerender'].includes(document.visibilityState);
460
+ }
461
+
462
+ }
463
+ const focusManager = new FocusManager();
464
+
465
+ const onlineEvents = ['online', 'offline'];
466
+ class OnlineManager extends Subscribable {
467
+ constructor() {
468
+ super();
469
+
470
+ this.setup = onOnline => {
471
+ // addEventListener does not exist in React Native, but window does
472
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
473
+ if (!isServer && window.addEventListener) {
474
+ const listener = () => onOnline(); // Listen to online
475
+
476
+
477
+ onlineEvents.forEach(event => {
478
+ window.addEventListener(event, listener, false);
479
+ });
480
+ return () => {
481
+ // Be sure to unsubscribe if a new handler is set
482
+ onlineEvents.forEach(event => {
483
+ window.removeEventListener(event, listener);
484
+ });
485
+ };
486
+ }
487
+
488
+ return;
489
+ };
490
+ }
491
+
492
+ onSubscribe() {
493
+ if (!this.cleanup) {
494
+ this.setEventListener(this.setup);
495
+ }
496
+ }
497
+
498
+ onUnsubscribe() {
499
+ if (!this.hasListeners()) {
500
+ var _this$cleanup;
501
+
502
+ (_this$cleanup = this.cleanup) == null ? void 0 : _this$cleanup.call(this);
503
+ this.cleanup = undefined;
504
+ }
505
+ }
506
+
507
+ setEventListener(setup) {
508
+ var _this$cleanup2;
509
+
510
+ this.setup = setup;
511
+ (_this$cleanup2 = this.cleanup) == null ? void 0 : _this$cleanup2.call(this);
512
+ this.cleanup = setup(online => {
513
+ if (typeof online === 'boolean') {
514
+ this.setOnline(online);
515
+ } else {
516
+ this.onOnline();
517
+ }
518
+ });
519
+ }
520
+
521
+ setOnline(online) {
522
+ const changed = this.online !== online;
523
+
524
+ if (changed) {
525
+ this.online = online;
526
+ this.onOnline();
527
+ }
528
+ }
529
+
530
+ onOnline() {
531
+ this.listeners.forEach(({
532
+ listener
533
+ }) => {
534
+ listener();
535
+ });
536
+ }
537
+
538
+ isOnline() {
539
+ if (typeof this.online === 'boolean') {
540
+ return this.online;
541
+ }
542
+
543
+ if (typeof navigator === 'undefined' || typeof navigator.onLine === 'undefined') {
544
+ return true;
545
+ }
546
+
547
+ return navigator.onLine;
548
+ }
549
+
550
+ }
551
+ const onlineManager = new OnlineManager();
552
+
553
+ function defaultRetryDelay(failureCount) {
554
+ return Math.min(1000 * 2 ** failureCount, 30000);
555
+ }
556
+
557
+ function canFetch(networkMode) {
558
+ return (networkMode != null ? networkMode : 'online') === 'online' ? onlineManager.isOnline() : true;
559
+ }
560
+ class CancelledError {
561
+ constructor(options) {
562
+ this.revert = options == null ? void 0 : options.revert;
563
+ this.silent = options == null ? void 0 : options.silent;
564
+ }
565
+
566
+ }
567
+ function isCancelledError(value) {
568
+ return value instanceof CancelledError;
569
+ }
570
+ function createRetryer(config) {
571
+ let isRetryCancelled = false;
572
+ let failureCount = 0;
573
+ let isResolved = false;
574
+ let continueFn;
575
+ let promiseResolve;
576
+ let promiseReject;
577
+ const promise = new Promise((outerResolve, outerReject) => {
578
+ promiseResolve = outerResolve;
579
+ promiseReject = outerReject;
580
+ });
581
+
582
+ const cancel = cancelOptions => {
583
+ if (!isResolved) {
584
+ reject(new CancelledError(cancelOptions));
585
+ config.abort == null ? void 0 : config.abort();
586
+ }
587
+ };
588
+
589
+ const cancelRetry = () => {
590
+ isRetryCancelled = true;
591
+ };
592
+
593
+ const continueRetry = () => {
594
+ isRetryCancelled = false;
595
+ };
596
+
597
+ const shouldPause = () => !focusManager.isFocused() || config.networkMode !== 'always' && !onlineManager.isOnline();
598
+
599
+ const resolve = value => {
600
+ if (!isResolved) {
601
+ isResolved = true;
602
+ config.onSuccess == null ? void 0 : config.onSuccess(value);
603
+ continueFn == null ? void 0 : continueFn();
604
+ promiseResolve(value);
605
+ }
606
+ };
607
+
608
+ const reject = value => {
609
+ if (!isResolved) {
610
+ isResolved = true;
611
+ config.onError == null ? void 0 : config.onError(value);
612
+ continueFn == null ? void 0 : continueFn();
613
+ promiseReject(value);
614
+ }
615
+ };
616
+
617
+ const pause = () => {
618
+ return new Promise(continueResolve => {
619
+ continueFn = value => {
620
+ const canContinue = isResolved || !shouldPause();
621
+
622
+ if (canContinue) {
623
+ continueResolve(value);
624
+ }
625
+
626
+ return canContinue;
627
+ };
628
+
629
+ config.onPause == null ? void 0 : config.onPause();
630
+ }).then(() => {
631
+ continueFn = undefined;
632
+
633
+ if (!isResolved) {
634
+ config.onContinue == null ? void 0 : config.onContinue();
635
+ }
636
+ });
637
+ }; // Create loop function
638
+
639
+
640
+ const run = () => {
641
+ // Do nothing if already resolved
642
+ if (isResolved) {
643
+ return;
644
+ }
645
+
646
+ let promiseOrValue; // Execute query
647
+
648
+ try {
649
+ promiseOrValue = config.fn();
650
+ } catch (error) {
651
+ promiseOrValue = Promise.reject(error);
652
+ }
653
+
654
+ Promise.resolve(promiseOrValue).then(resolve).catch(error => {
655
+ var _config$retry, _config$retryDelay;
656
+
657
+ // Stop if the fetch is already resolved
658
+ if (isResolved) {
659
+ return;
660
+ } // Do we need to retry the request?
661
+
662
+
663
+ const retry = (_config$retry = config.retry) != null ? _config$retry : 3;
664
+ const retryDelay = (_config$retryDelay = config.retryDelay) != null ? _config$retryDelay : defaultRetryDelay;
665
+ const delay = typeof retryDelay === 'function' ? retryDelay(failureCount, error) : retryDelay;
666
+ const shouldRetry = retry === true || typeof retry === 'number' && failureCount < retry || typeof retry === 'function' && retry(failureCount, error);
667
+
668
+ if (isRetryCancelled || !shouldRetry) {
669
+ // We are done if the query does not need to be retried
670
+ reject(error);
671
+ return;
672
+ }
673
+
674
+ failureCount++; // Notify on fail
675
+
676
+ config.onFail == null ? void 0 : config.onFail(failureCount, error); // Delay
677
+
678
+ sleep(delay) // Pause if the document is not visible or when the device is offline
679
+ .then(() => {
680
+ if (shouldPause()) {
681
+ return pause();
682
+ }
683
+
684
+ return;
685
+ }).then(() => {
686
+ if (isRetryCancelled) {
687
+ reject(error);
688
+ } else {
689
+ run();
690
+ }
691
+ });
692
+ });
693
+ }; // Start loop
694
+
695
+
696
+ if (canFetch(config.networkMode)) {
697
+ run();
698
+ } else {
699
+ pause().then(run);
700
+ }
701
+
702
+ return {
703
+ promise,
704
+ cancel,
705
+ continue: () => {
706
+ const didContinue = continueFn == null ? void 0 : continueFn();
707
+ return didContinue ? promise : Promise.resolve();
708
+ },
709
+ cancelRetry,
710
+ continueRetry
711
+ };
712
+ }
713
+
714
+ const defaultLogger = console;
715
+
716
+ function createNotifyManager() {
717
+ let queue = [];
718
+ let transactions = 0;
719
+
720
+ let notifyFn = callback => {
721
+ callback();
722
+ };
723
+
724
+ let batchNotifyFn = callback => {
725
+ callback();
726
+ };
727
+
728
+ const batch = callback => {
729
+ let result;
730
+ transactions++;
731
+
732
+ try {
733
+ result = callback();
734
+ } finally {
735
+ transactions--;
736
+
737
+ if (!transactions) {
738
+ flush();
739
+ }
740
+ }
741
+
742
+ return result;
743
+ };
744
+
745
+ const schedule = callback => {
746
+ if (transactions) {
747
+ queue.push(callback);
748
+ } else {
749
+ scheduleMicrotask(() => {
750
+ notifyFn(callback);
751
+ });
752
+ }
753
+ };
754
+ /**
755
+ * All calls to the wrapped function will be batched.
756
+ */
757
+
758
+
759
+ const batchCalls = callback => {
760
+ return (...args) => {
761
+ schedule(() => {
762
+ callback(...args);
763
+ });
764
+ };
765
+ };
766
+
767
+ const flush = () => {
768
+ const originalQueue = queue;
769
+ queue = [];
770
+
771
+ if (originalQueue.length) {
772
+ scheduleMicrotask(() => {
773
+ batchNotifyFn(() => {
774
+ originalQueue.forEach(callback => {
775
+ notifyFn(callback);
776
+ });
777
+ });
778
+ });
779
+ }
780
+ };
781
+ /**
782
+ * Use this method to set a custom notify function.
783
+ * This can be used to for example wrap notifications with `React.act` while running tests.
784
+ */
785
+
786
+
787
+ const setNotifyFunction = fn => {
788
+ notifyFn = fn;
789
+ };
790
+ /**
791
+ * Use this method to set a custom function to batch notifications together into a single tick.
792
+ * By default React Query will use the batch function provided by ReactDOM or React Native.
793
+ */
794
+
795
+
796
+ const setBatchNotifyFunction = fn => {
797
+ batchNotifyFn = fn;
798
+ };
799
+
800
+ return {
801
+ batch,
802
+ batchCalls,
803
+ schedule,
804
+ setNotifyFunction,
805
+ setBatchNotifyFunction
806
+ };
807
+ } // SINGLETON
808
+
809
+ const notifyManager = createNotifyManager();
810
+
811
+ class Removable {
812
+ destroy() {
813
+ this.clearGcTimeout();
814
+ }
815
+
816
+ scheduleGc() {
817
+ this.clearGcTimeout();
818
+
819
+ if (isValidTimeout(this.cacheTime)) {
820
+ this.gcTimeout = setTimeout(() => {
821
+ this.optionalRemove();
822
+ }, this.cacheTime);
823
+ }
824
+ }
825
+
826
+ updateCacheTime(newCacheTime) {
827
+ // Default to 5 minutes (Infinity for server-side) if no cache time is set
828
+ this.cacheTime = Math.max(this.cacheTime || 0, newCacheTime != null ? newCacheTime : isServer ? Infinity : 5 * 60 * 1000);
829
+ }
830
+
831
+ clearGcTimeout() {
832
+ if (this.gcTimeout) {
833
+ clearTimeout(this.gcTimeout);
834
+ this.gcTimeout = undefined;
835
+ }
836
+ }
837
+
838
+ }
839
+
840
+ // CLASS
841
+ class Query extends Removable {
842
+ constructor(config) {
843
+ super();
844
+ this.abortSignalConsumed = false;
845
+ this.defaultOptions = config.defaultOptions;
846
+ this.setOptions(config.options);
847
+ this.observers = [];
848
+ this.cache = config.cache;
849
+ this.logger = config.logger || defaultLogger;
850
+ this.queryKey = config.queryKey;
851
+ this.queryHash = config.queryHash;
852
+ this.initialState = config.state || getDefaultState$1(this.options);
853
+ this.state = this.initialState;
854
+ this.scheduleGc();
855
+ }
856
+
857
+ get meta() {
858
+ return this.options.meta;
859
+ }
860
+
861
+ setOptions(options) {
862
+ this.options = { ...this.defaultOptions,
863
+ ...options
864
+ };
865
+ this.updateCacheTime(this.options.cacheTime);
866
+ }
867
+
868
+ optionalRemove() {
869
+ if (!this.observers.length && this.state.fetchStatus === 'idle') {
870
+ this.cache.remove(this);
871
+ }
872
+ }
873
+
874
+ setData(newData, options) {
875
+ const data = replaceData(this.state.data, newData, this.options); // Set data and mark it as cached
876
+
877
+ this.dispatch({
878
+ data,
879
+ type: 'success',
880
+ dataUpdatedAt: options == null ? void 0 : options.updatedAt,
881
+ manual: options == null ? void 0 : options.manual
882
+ });
883
+ return data;
884
+ }
885
+
886
+ setState(state, setStateOptions) {
887
+ this.dispatch({
888
+ type: 'setState',
889
+ state,
890
+ setStateOptions
891
+ });
892
+ }
893
+
894
+ cancel(options) {
895
+ var _this$retryer;
896
+
897
+ const promise = this.promise;
898
+ (_this$retryer = this.retryer) == null ? void 0 : _this$retryer.cancel(options);
899
+ return promise ? promise.then(noop$1).catch(noop$1) : Promise.resolve();
900
+ }
901
+
902
+ destroy() {
903
+ super.destroy();
904
+ this.cancel({
905
+ silent: true
906
+ });
907
+ }
908
+
909
+ reset() {
910
+ this.destroy();
911
+ this.setState(this.initialState);
912
+ }
913
+
914
+ isActive() {
915
+ return this.observers.some(observer => observer.options.enabled !== false);
916
+ }
917
+
918
+ isDisabled() {
919
+ return this.getObserversCount() > 0 && !this.isActive();
920
+ }
921
+
922
+ isStale() {
923
+ return this.state.isInvalidated || !this.state.dataUpdatedAt || this.observers.some(observer => observer.getCurrentResult().isStale);
924
+ }
925
+
926
+ isStaleByTime(staleTime = 0) {
927
+ return this.state.isInvalidated || !this.state.dataUpdatedAt || !timeUntilStale(this.state.dataUpdatedAt, staleTime);
928
+ }
929
+
930
+ onFocus() {
931
+ var _this$retryer2;
932
+
933
+ const observer = this.observers.find(x => x.shouldFetchOnWindowFocus());
934
+
935
+ if (observer) {
936
+ observer.refetch({
937
+ cancelRefetch: false
938
+ });
939
+ } // Continue fetch if currently paused
940
+
941
+
942
+ (_this$retryer2 = this.retryer) == null ? void 0 : _this$retryer2.continue();
943
+ }
944
+
945
+ onOnline() {
946
+ var _this$retryer3;
947
+
948
+ const observer = this.observers.find(x => x.shouldFetchOnReconnect());
949
+
950
+ if (observer) {
951
+ observer.refetch({
952
+ cancelRefetch: false
953
+ });
954
+ } // Continue fetch if currently paused
955
+
956
+
957
+ (_this$retryer3 = this.retryer) == null ? void 0 : _this$retryer3.continue();
958
+ }
959
+
960
+ addObserver(observer) {
961
+ if (!this.observers.includes(observer)) {
962
+ this.observers.push(observer); // Stop the query from being garbage collected
963
+
964
+ this.clearGcTimeout();
965
+ this.cache.notify({
966
+ type: 'observerAdded',
967
+ query: this,
968
+ observer
969
+ });
970
+ }
971
+ }
972
+
973
+ removeObserver(observer) {
974
+ if (this.observers.includes(observer)) {
975
+ this.observers = this.observers.filter(x => x !== observer);
976
+
977
+ if (!this.observers.length) {
978
+ // If the transport layer does not support cancellation
979
+ // we'll let the query continue so the result can be cached
980
+ if (this.retryer) {
981
+ if (this.abortSignalConsumed) {
982
+ this.retryer.cancel({
983
+ revert: true
984
+ });
985
+ } else {
986
+ this.retryer.cancelRetry();
987
+ }
988
+ }
989
+
990
+ this.scheduleGc();
991
+ }
992
+
993
+ this.cache.notify({
994
+ type: 'observerRemoved',
995
+ query: this,
996
+ observer
997
+ });
998
+ }
999
+ }
1000
+
1001
+ getObserversCount() {
1002
+ return this.observers.length;
1003
+ }
1004
+
1005
+ invalidate() {
1006
+ if (!this.state.isInvalidated) {
1007
+ this.dispatch({
1008
+ type: 'invalidate'
1009
+ });
1010
+ }
1011
+ }
1012
+
1013
+ fetch(options, fetchOptions) {
1014
+ var _this$options$behavio, _context$fetchOptions;
1015
+
1016
+ if (this.state.fetchStatus !== 'idle') {
1017
+ if (this.state.dataUpdatedAt && fetchOptions != null && fetchOptions.cancelRefetch) {
1018
+ // Silently cancel current fetch if the user wants to cancel refetches
1019
+ this.cancel({
1020
+ silent: true
1021
+ });
1022
+ } else if (this.promise) {
1023
+ var _this$retryer4;
1024
+
1025
+ // make sure that retries that were potentially cancelled due to unmounts can continue
1026
+ (_this$retryer4 = this.retryer) == null ? void 0 : _this$retryer4.continueRetry(); // Return current promise if we are already fetching
1027
+
1028
+ return this.promise;
1029
+ }
1030
+ } // Update config if passed, otherwise the config from the last execution is used
1031
+
1032
+
1033
+ if (options) {
1034
+ this.setOptions(options);
1035
+ } // Use the options from the first observer with a query function if no function is found.
1036
+ // This can happen when the query is hydrated or created with setQueryData.
1037
+
1038
+
1039
+ if (!this.options.queryFn) {
1040
+ const observer = this.observers.find(x => x.options.queryFn);
1041
+
1042
+ if (observer) {
1043
+ this.setOptions(observer.options);
1044
+ }
1045
+ }
1046
+
1047
+ {
1048
+ if (!Array.isArray(this.options.queryKey)) {
1049
+ 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']");
1050
+ }
1051
+ }
1052
+
1053
+ const abortController = getAbortController(); // Create query function context
1054
+
1055
+ const queryFnContext = {
1056
+ queryKey: this.queryKey,
1057
+ pageParam: undefined,
1058
+ meta: this.meta
1059
+ }; // Adds an enumerable signal property to the object that
1060
+ // which sets abortSignalConsumed to true when the signal
1061
+ // is read.
1062
+
1063
+ const addSignalProperty = object => {
1064
+ Object.defineProperty(object, 'signal', {
1065
+ enumerable: true,
1066
+ get: () => {
1067
+ if (abortController) {
1068
+ this.abortSignalConsumed = true;
1069
+ return abortController.signal;
1070
+ }
1071
+
1072
+ return undefined;
1073
+ }
1074
+ });
1075
+ };
1076
+
1077
+ addSignalProperty(queryFnContext); // Create fetch function
1078
+
1079
+ const fetchFn = () => {
1080
+ if (!this.options.queryFn) {
1081
+ return Promise.reject("Missing queryFn for queryKey '" + this.options.queryHash + "'");
1082
+ }
1083
+
1084
+ this.abortSignalConsumed = false;
1085
+ return this.options.queryFn(queryFnContext);
1086
+ }; // Trigger behavior hook
1087
+
1088
+
1089
+ const context = {
1090
+ fetchOptions,
1091
+ options: this.options,
1092
+ queryKey: this.queryKey,
1093
+ state: this.state,
1094
+ fetchFn
1095
+ };
1096
+ addSignalProperty(context);
1097
+ (_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
1098
+
1099
+ this.revertState = this.state; // Set to fetching state if not already in it
1100
+
1101
+ if (this.state.fetchStatus === 'idle' || this.state.fetchMeta !== ((_context$fetchOptions = context.fetchOptions) == null ? void 0 : _context$fetchOptions.meta)) {
1102
+ var _context$fetchOptions2;
1103
+
1104
+ this.dispatch({
1105
+ type: 'fetch',
1106
+ meta: (_context$fetchOptions2 = context.fetchOptions) == null ? void 0 : _context$fetchOptions2.meta
1107
+ });
1108
+ }
1109
+
1110
+ const onError = error => {
1111
+ // Optimistically update state if needed
1112
+ if (!(isCancelledError(error) && error.silent)) {
1113
+ this.dispatch({
1114
+ type: 'error',
1115
+ error: error
1116
+ });
1117
+ }
1118
+
1119
+ if (!isCancelledError(error)) {
1120
+ var _this$cache$config$on, _this$cache$config, _this$cache$config$on2, _this$cache$config2;
1121
+
1122
+ // Notify cache callback
1123
+ (_this$cache$config$on = (_this$cache$config = this.cache.config).onError) == null ? void 0 : _this$cache$config$on.call(_this$cache$config, error, this);
1124
+ (_this$cache$config$on2 = (_this$cache$config2 = this.cache.config).onSettled) == null ? void 0 : _this$cache$config$on2.call(_this$cache$config2, this.state.data, error, this);
1125
+
1126
+ {
1127
+ this.logger.error(error);
1128
+ }
1129
+ }
1130
+
1131
+ if (!this.isFetchingOptimistic) {
1132
+ // Schedule query gc after fetching
1133
+ this.scheduleGc();
1134
+ }
1135
+
1136
+ this.isFetchingOptimistic = false;
1137
+ }; // Try to fetch the data
1138
+
1139
+
1140
+ this.retryer = createRetryer({
1141
+ fn: context.fetchFn,
1142
+ abort: abortController == null ? void 0 : abortController.abort.bind(abortController),
1143
+ onSuccess: data => {
1144
+ var _this$cache$config$on3, _this$cache$config3, _this$cache$config$on4, _this$cache$config4;
1145
+
1146
+ if (typeof data === 'undefined') {
1147
+ {
1148
+ this.logger.error("Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: " + this.queryHash);
1149
+ }
1150
+
1151
+ onError(new Error(this.queryHash + " data is undefined"));
1152
+ return;
1153
+ }
1154
+
1155
+ this.setData(data); // Notify cache callback
1156
+
1157
+ (_this$cache$config$on3 = (_this$cache$config3 = this.cache.config).onSuccess) == null ? void 0 : _this$cache$config$on3.call(_this$cache$config3, data, this);
1158
+ (_this$cache$config$on4 = (_this$cache$config4 = this.cache.config).onSettled) == null ? void 0 : _this$cache$config$on4.call(_this$cache$config4, data, this.state.error, this);
1159
+
1160
+ if (!this.isFetchingOptimistic) {
1161
+ // Schedule query gc after fetching
1162
+ this.scheduleGc();
1163
+ }
1164
+
1165
+ this.isFetchingOptimistic = false;
1166
+ },
1167
+ onError,
1168
+ onFail: (failureCount, error) => {
1169
+ this.dispatch({
1170
+ type: 'failed',
1171
+ failureCount,
1172
+ error
1173
+ });
1174
+ },
1175
+ onPause: () => {
1176
+ this.dispatch({
1177
+ type: 'pause'
1178
+ });
1179
+ },
1180
+ onContinue: () => {
1181
+ this.dispatch({
1182
+ type: 'continue'
1183
+ });
1184
+ },
1185
+ retry: context.options.retry,
1186
+ retryDelay: context.options.retryDelay,
1187
+ networkMode: context.options.networkMode
1188
+ });
1189
+ this.promise = this.retryer.promise;
1190
+ return this.promise;
1191
+ }
1192
+
1193
+ dispatch(action) {
1194
+ const reducer = state => {
1195
+ var _action$meta, _action$dataUpdatedAt;
1196
+
1197
+ switch (action.type) {
1198
+ case 'failed':
1199
+ return { ...state,
1200
+ fetchFailureCount: action.failureCount,
1201
+ fetchFailureReason: action.error
1202
+ };
1203
+
1204
+ case 'pause':
1205
+ return { ...state,
1206
+ fetchStatus: 'paused'
1207
+ };
1208
+
1209
+ case 'continue':
1210
+ return { ...state,
1211
+ fetchStatus: 'fetching'
1212
+ };
1213
+
1214
+ case 'fetch':
1215
+ return { ...state,
1216
+ fetchFailureCount: 0,
1217
+ fetchFailureReason: null,
1218
+ fetchMeta: (_action$meta = action.meta) != null ? _action$meta : null,
1219
+ fetchStatus: canFetch(this.options.networkMode) ? 'fetching' : 'paused',
1220
+ ...(!state.dataUpdatedAt && {
1221
+ error: null,
1222
+ status: 'loading'
1223
+ })
1224
+ };
1225
+
1226
+ case 'success':
1227
+ return { ...state,
1228
+ data: action.data,
1229
+ dataUpdateCount: state.dataUpdateCount + 1,
1230
+ dataUpdatedAt: (_action$dataUpdatedAt = action.dataUpdatedAt) != null ? _action$dataUpdatedAt : Date.now(),
1231
+ error: null,
1232
+ isInvalidated: false,
1233
+ status: 'success',
1234
+ ...(!action.manual && {
1235
+ fetchStatus: 'idle',
1236
+ fetchFailureCount: 0,
1237
+ fetchFailureReason: null
1238
+ })
1239
+ };
1240
+
1241
+ case 'error':
1242
+ const error = action.error;
1243
+
1244
+ if (isCancelledError(error) && error.revert && this.revertState) {
1245
+ return { ...this.revertState,
1246
+ fetchStatus: 'idle'
1247
+ };
1248
+ }
1249
+
1250
+ return { ...state,
1251
+ error: error,
1252
+ errorUpdateCount: state.errorUpdateCount + 1,
1253
+ errorUpdatedAt: Date.now(),
1254
+ fetchFailureCount: state.fetchFailureCount + 1,
1255
+ fetchFailureReason: error,
1256
+ fetchStatus: 'idle',
1257
+ status: 'error'
1258
+ };
1259
+
1260
+ case 'invalidate':
1261
+ return { ...state,
1262
+ isInvalidated: true
1263
+ };
1264
+
1265
+ case 'setState':
1266
+ return { ...state,
1267
+ ...action.state
1268
+ };
1269
+ }
1270
+ };
1271
+
1272
+ this.state = reducer(this.state);
1273
+ notifyManager.batch(() => {
1274
+ this.observers.forEach(observer => {
1275
+ observer.onQueryUpdate(action);
1276
+ });
1277
+ this.cache.notify({
1278
+ query: this,
1279
+ type: 'updated',
1280
+ action
1281
+ });
1282
+ });
1283
+ }
1284
+
1285
+ }
1286
+
1287
+ function getDefaultState$1(options) {
1288
+ const data = typeof options.initialData === 'function' ? options.initialData() : options.initialData;
1289
+ const hasData = typeof data !== 'undefined';
1290
+ const initialDataUpdatedAt = hasData ? typeof options.initialDataUpdatedAt === 'function' ? options.initialDataUpdatedAt() : options.initialDataUpdatedAt : 0;
1291
+ return {
1292
+ data,
1293
+ dataUpdateCount: 0,
1294
+ dataUpdatedAt: hasData ? initialDataUpdatedAt != null ? initialDataUpdatedAt : Date.now() : 0,
1295
+ error: null,
1296
+ errorUpdateCount: 0,
1297
+ errorUpdatedAt: 0,
1298
+ fetchFailureCount: 0,
1299
+ fetchFailureReason: null,
1300
+ fetchMeta: null,
1301
+ isInvalidated: false,
1302
+ status: hasData ? 'success' : 'loading',
1303
+ fetchStatus: 'idle'
1304
+ };
1305
+ }
1306
+
1307
+ // CLASS
1308
+ class QueryCache extends Subscribable {
1309
+ constructor(config) {
1310
+ super();
1311
+ this.config = config || {};
1312
+ this.queries = [];
1313
+ this.queriesMap = {};
1314
+ }
1315
+
1316
+ build(client, options, state) {
1317
+ var _options$queryHash;
1318
+
1319
+ const queryKey = options.queryKey;
1320
+ const queryHash = (_options$queryHash = options.queryHash) != null ? _options$queryHash : hashQueryKeyByOptions(queryKey, options);
1321
+ let query = this.get(queryHash);
1322
+
1323
+ if (!query) {
1324
+ query = new Query({
1325
+ cache: this,
1326
+ logger: client.getLogger(),
1327
+ queryKey,
1328
+ queryHash,
1329
+ options: client.defaultQueryOptions(options),
1330
+ state,
1331
+ defaultOptions: client.getQueryDefaults(queryKey)
1332
+ });
1333
+ this.add(query);
1334
+ }
1335
+
1336
+ return query;
1337
+ }
1338
+
1339
+ add(query) {
1340
+ if (!this.queriesMap[query.queryHash]) {
1341
+ this.queriesMap[query.queryHash] = query;
1342
+ this.queries.push(query);
1343
+ this.notify({
1344
+ type: 'added',
1345
+ query
1346
+ });
1347
+ }
1348
+ }
1349
+
1350
+ remove(query) {
1351
+ const queryInMap = this.queriesMap[query.queryHash];
1352
+
1353
+ if (queryInMap) {
1354
+ query.destroy();
1355
+ this.queries = this.queries.filter(x => x !== query);
1356
+
1357
+ if (queryInMap === query) {
1358
+ delete this.queriesMap[query.queryHash];
1359
+ }
1360
+
1361
+ this.notify({
1362
+ type: 'removed',
1363
+ query
1364
+ });
1365
+ }
1366
+ }
1367
+
1368
+ clear() {
1369
+ notifyManager.batch(() => {
1370
+ this.queries.forEach(query => {
1371
+ this.remove(query);
1372
+ });
1373
+ });
1374
+ }
1375
+
1376
+ get(queryHash) {
1377
+ return this.queriesMap[queryHash];
1378
+ }
1379
+
1380
+ getAll() {
1381
+ return this.queries;
1382
+ }
1383
+
1384
+ /**
1385
+ * @deprecated This method should be used with only one object argument.
1386
+ */
1387
+ find(arg1, arg2) {
1388
+ const [filters] = parseFilterArgs(arg1, arg2);
1389
+
1390
+ if (typeof filters.exact === 'undefined') {
1391
+ filters.exact = true;
1392
+ }
1393
+
1394
+ return this.queries.find(query => matchQuery(filters, query));
1395
+ }
1396
+
1397
+ /**
1398
+ * @deprecated This method should be used with only one object argument.
1399
+ */
1400
+ findAll(arg1, arg2) {
1401
+ const [filters] = parseFilterArgs(arg1, arg2);
1402
+ return Object.keys(filters).length > 0 ? this.queries.filter(query => matchQuery(filters, query)) : this.queries;
1403
+ }
1404
+
1405
+ notify(event) {
1406
+ notifyManager.batch(() => {
1407
+ this.listeners.forEach(({
1408
+ listener
1409
+ }) => {
1410
+ listener(event);
1411
+ });
1412
+ });
1413
+ }
1414
+
1415
+ onFocus() {
1416
+ notifyManager.batch(() => {
1417
+ this.queries.forEach(query => {
1418
+ query.onFocus();
1419
+ });
1420
+ });
1421
+ }
1422
+
1423
+ onOnline() {
1424
+ notifyManager.batch(() => {
1425
+ this.queries.forEach(query => {
1426
+ query.onOnline();
1427
+ });
1428
+ });
1429
+ }
1430
+
1431
+ }
1432
+
1433
+ // CLASS
1434
+ class Mutation extends Removable {
1435
+ constructor(config) {
1436
+ super();
1437
+ this.defaultOptions = config.defaultOptions;
1438
+ this.mutationId = config.mutationId;
1439
+ this.mutationCache = config.mutationCache;
1440
+ this.logger = config.logger || defaultLogger;
1441
+ this.observers = [];
1442
+ this.state = config.state || getDefaultState();
1443
+ this.setOptions(config.options);
1444
+ this.scheduleGc();
1445
+ }
1446
+
1447
+ setOptions(options) {
1448
+ this.options = { ...this.defaultOptions,
1449
+ ...options
1450
+ };
1451
+ this.updateCacheTime(this.options.cacheTime);
1452
+ }
1453
+
1454
+ get meta() {
1455
+ return this.options.meta;
1456
+ }
1457
+
1458
+ setState(state) {
1459
+ this.dispatch({
1460
+ type: 'setState',
1461
+ state
1462
+ });
1463
+ }
1464
+
1465
+ addObserver(observer) {
1466
+ if (!this.observers.includes(observer)) {
1467
+ this.observers.push(observer); // Stop the mutation from being garbage collected
1468
+
1469
+ this.clearGcTimeout();
1470
+ this.mutationCache.notify({
1471
+ type: 'observerAdded',
1472
+ mutation: this,
1473
+ observer
1474
+ });
1475
+ }
1476
+ }
1477
+
1478
+ removeObserver(observer) {
1479
+ this.observers = this.observers.filter(x => x !== observer);
1480
+ this.scheduleGc();
1481
+ this.mutationCache.notify({
1482
+ type: 'observerRemoved',
1483
+ mutation: this,
1484
+ observer
1485
+ });
1486
+ }
1487
+
1488
+ optionalRemove() {
1489
+ if (!this.observers.length) {
1490
+ if (this.state.status === 'loading') {
1491
+ this.scheduleGc();
1492
+ } else {
1493
+ this.mutationCache.remove(this);
1494
+ }
1495
+ }
1496
+ }
1497
+
1498
+ continue() {
1499
+ var _this$retryer$continu, _this$retryer;
1500
+
1501
+ return (_this$retryer$continu = (_this$retryer = this.retryer) == null ? void 0 : _this$retryer.continue()) != null ? _this$retryer$continu : this.execute();
1502
+ }
1503
+
1504
+ async execute() {
1505
+ const executeMutation = () => {
1506
+ var _this$options$retry;
1507
+
1508
+ this.retryer = createRetryer({
1509
+ fn: () => {
1510
+ if (!this.options.mutationFn) {
1511
+ return Promise.reject('No mutationFn found');
1512
+ }
1513
+
1514
+ return this.options.mutationFn(this.state.variables);
1515
+ },
1516
+ onFail: (failureCount, error) => {
1517
+ this.dispatch({
1518
+ type: 'failed',
1519
+ failureCount,
1520
+ error
1521
+ });
1522
+ },
1523
+ onPause: () => {
1524
+ this.dispatch({
1525
+ type: 'pause'
1526
+ });
1527
+ },
1528
+ onContinue: () => {
1529
+ this.dispatch({
1530
+ type: 'continue'
1531
+ });
1532
+ },
1533
+ retry: (_this$options$retry = this.options.retry) != null ? _this$options$retry : 0,
1534
+ retryDelay: this.options.retryDelay,
1535
+ networkMode: this.options.networkMode
1536
+ });
1537
+ return this.retryer.promise;
1538
+ };
1539
+
1540
+ const restored = this.state.status === 'loading';
1541
+
1542
+ try {
1543
+ var _this$mutationCache$c3, _this$mutationCache$c4, _this$options$onSucce, _this$options2, _this$mutationCache$c5, _this$mutationCache$c6, _this$options$onSettl, _this$options3;
1544
+
1545
+ if (!restored) {
1546
+ var _this$mutationCache$c, _this$mutationCache$c2, _this$options$onMutat, _this$options;
1547
+
1548
+ this.dispatch({
1549
+ type: 'loading',
1550
+ variables: this.options.variables
1551
+ }); // Notify cache callback
1552
+
1553
+ await ((_this$mutationCache$c = (_this$mutationCache$c2 = this.mutationCache.config).onMutate) == null ? void 0 : _this$mutationCache$c.call(_this$mutationCache$c2, this.state.variables, this));
1554
+ const context = await ((_this$options$onMutat = (_this$options = this.options).onMutate) == null ? void 0 : _this$options$onMutat.call(_this$options, this.state.variables));
1555
+
1556
+ if (context !== this.state.context) {
1557
+ this.dispatch({
1558
+ type: 'loading',
1559
+ context,
1560
+ variables: this.state.variables
1561
+ });
1562
+ }
1563
+ }
1564
+
1565
+ const data = await executeMutation(); // Notify cache callback
1566
+
1567
+ await ((_this$mutationCache$c3 = (_this$mutationCache$c4 = this.mutationCache.config).onSuccess) == null ? void 0 : _this$mutationCache$c3.call(_this$mutationCache$c4, data, this.state.variables, this.state.context, this));
1568
+ 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)); // Notify cache callback
1569
+
1570
+ await ((_this$mutationCache$c5 = (_this$mutationCache$c6 = this.mutationCache.config).onSettled) == null ? void 0 : _this$mutationCache$c5.call(_this$mutationCache$c6, data, null, this.state.variables, this.state.context, this));
1571
+ 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));
1572
+ this.dispatch({
1573
+ type: 'success',
1574
+ data
1575
+ });
1576
+ return data;
1577
+ } catch (error) {
1578
+ try {
1579
+ var _this$mutationCache$c7, _this$mutationCache$c8, _this$options$onError, _this$options4, _this$mutationCache$c9, _this$mutationCache$c10, _this$options$onSettl2, _this$options5;
1580
+
1581
+ // Notify cache callback
1582
+ await ((_this$mutationCache$c7 = (_this$mutationCache$c8 = this.mutationCache.config).onError) == null ? void 0 : _this$mutationCache$c7.call(_this$mutationCache$c8, error, this.state.variables, this.state.context, this));
1583
+
1584
+ if ("development" !== 'production') {
1585
+ this.logger.error(error);
1586
+ }
1587
+
1588
+ 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)); // Notify cache callback
1589
+
1590
+ await ((_this$mutationCache$c9 = (_this$mutationCache$c10 = this.mutationCache.config).onSettled) == null ? void 0 : _this$mutationCache$c9.call(_this$mutationCache$c10, undefined, error, this.state.variables, this.state.context, this));
1591
+ 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));
1592
+ throw error;
1593
+ } finally {
1594
+ this.dispatch({
1595
+ type: 'error',
1596
+ error: error
1597
+ });
1598
+ }
1599
+ }
1600
+ }
1601
+
1602
+ dispatch(action) {
1603
+ const reducer = state => {
1604
+ switch (action.type) {
1605
+ case 'failed':
1606
+ return { ...state,
1607
+ failureCount: action.failureCount,
1608
+ failureReason: action.error
1609
+ };
1610
+
1611
+ case 'pause':
1612
+ return { ...state,
1613
+ isPaused: true
1614
+ };
1615
+
1616
+ case 'continue':
1617
+ return { ...state,
1618
+ isPaused: false
1619
+ };
1620
+
1621
+ case 'loading':
1622
+ return { ...state,
1623
+ context: action.context,
1624
+ data: undefined,
1625
+ failureCount: 0,
1626
+ failureReason: null,
1627
+ error: null,
1628
+ isPaused: !canFetch(this.options.networkMode),
1629
+ status: 'loading',
1630
+ variables: action.variables
1631
+ };
1632
+
1633
+ case 'success':
1634
+ return { ...state,
1635
+ data: action.data,
1636
+ failureCount: 0,
1637
+ failureReason: null,
1638
+ error: null,
1639
+ status: 'success',
1640
+ isPaused: false
1641
+ };
1642
+
1643
+ case 'error':
1644
+ return { ...state,
1645
+ data: undefined,
1646
+ error: action.error,
1647
+ failureCount: state.failureCount + 1,
1648
+ failureReason: action.error,
1649
+ isPaused: false,
1650
+ status: 'error'
1651
+ };
1652
+
1653
+ case 'setState':
1654
+ return { ...state,
1655
+ ...action.state
1656
+ };
1657
+ }
1658
+ };
1659
+
1660
+ this.state = reducer(this.state);
1661
+ notifyManager.batch(() => {
1662
+ this.observers.forEach(observer => {
1663
+ observer.onMutationUpdate(action);
1664
+ });
1665
+ this.mutationCache.notify({
1666
+ mutation: this,
1667
+ type: 'updated',
1668
+ action
1669
+ });
1670
+ });
1671
+ }
1672
+
1673
+ }
1674
+ function getDefaultState() {
1675
+ return {
1676
+ context: undefined,
1677
+ data: undefined,
1678
+ error: null,
1679
+ failureCount: 0,
1680
+ failureReason: null,
1681
+ isPaused: false,
1682
+ status: 'idle',
1683
+ variables: undefined
1684
+ };
1685
+ }
1686
+
1687
+ // CLASS
1688
+ class MutationCache extends Subscribable {
1689
+ constructor(config) {
1690
+ super();
1691
+ this.config = config || {};
1692
+ this.mutations = [];
1693
+ this.mutationId = 0;
1694
+ }
1695
+
1696
+ build(client, options, state) {
1697
+ const mutation = new Mutation({
1698
+ mutationCache: this,
1699
+ logger: client.getLogger(),
1700
+ mutationId: ++this.mutationId,
1701
+ options: client.defaultMutationOptions(options),
1702
+ state,
1703
+ defaultOptions: options.mutationKey ? client.getMutationDefaults(options.mutationKey) : undefined
1704
+ });
1705
+ this.add(mutation);
1706
+ return mutation;
1707
+ }
1708
+
1709
+ add(mutation) {
1710
+ this.mutations.push(mutation);
1711
+ this.notify({
1712
+ type: 'added',
1713
+ mutation
1714
+ });
1715
+ }
1716
+
1717
+ remove(mutation) {
1718
+ this.mutations = this.mutations.filter(x => x !== mutation);
1719
+ this.notify({
1720
+ type: 'removed',
1721
+ mutation
1722
+ });
1723
+ }
1724
+
1725
+ clear() {
1726
+ notifyManager.batch(() => {
1727
+ this.mutations.forEach(mutation => {
1728
+ this.remove(mutation);
1729
+ });
1730
+ });
1731
+ }
1732
+
1733
+ getAll() {
1734
+ return this.mutations;
1735
+ }
1736
+
1737
+ find(filters) {
1738
+ if (typeof filters.exact === 'undefined') {
1739
+ filters.exact = true;
1740
+ }
1741
+
1742
+ return this.mutations.find(mutation => matchMutation(filters, mutation));
1743
+ }
1744
+
1745
+ findAll(filters) {
1746
+ return this.mutations.filter(mutation => matchMutation(filters, mutation));
1747
+ }
1748
+
1749
+ notify(event) {
1750
+ notifyManager.batch(() => {
1751
+ this.listeners.forEach(({
1752
+ listener
1753
+ }) => {
1754
+ listener(event);
1755
+ });
1756
+ });
1757
+ }
1758
+
1759
+ resumePausedMutations() {
1760
+ var _this$resuming;
1761
+
1762
+ this.resuming = ((_this$resuming = this.resuming) != null ? _this$resuming : Promise.resolve()).then(() => {
1763
+ const pausedMutations = this.mutations.filter(x => x.state.isPaused);
1764
+ return notifyManager.batch(() => pausedMutations.reduce((promise, mutation) => promise.then(() => mutation.continue().catch(noop$1)), Promise.resolve()));
1765
+ }).then(() => {
1766
+ this.resuming = undefined;
1767
+ });
1768
+ return this.resuming;
1769
+ }
1770
+
1771
+ }
1772
+
1773
+ function infiniteQueryBehavior() {
1774
+ return {
1775
+ onFetch: context => {
1776
+ context.fetchFn = () => {
1777
+ var _context$fetchOptions, _context$fetchOptions2, _context$fetchOptions3, _context$fetchOptions4, _context$state$data, _context$state$data2;
1778
+
1779
+ const refetchPage = (_context$fetchOptions = context.fetchOptions) == null ? void 0 : (_context$fetchOptions2 = _context$fetchOptions.meta) == null ? void 0 : _context$fetchOptions2.refetchPage;
1780
+ const fetchMore = (_context$fetchOptions3 = context.fetchOptions) == null ? void 0 : (_context$fetchOptions4 = _context$fetchOptions3.meta) == null ? void 0 : _context$fetchOptions4.fetchMore;
1781
+ const pageParam = fetchMore == null ? void 0 : fetchMore.pageParam;
1782
+ const isFetchingNextPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'forward';
1783
+ const isFetchingPreviousPage = (fetchMore == null ? void 0 : fetchMore.direction) === 'backward';
1784
+ const oldPages = ((_context$state$data = context.state.data) == null ? void 0 : _context$state$data.pages) || [];
1785
+ const oldPageParams = ((_context$state$data2 = context.state.data) == null ? void 0 : _context$state$data2.pageParams) || [];
1786
+ let newPageParams = oldPageParams;
1787
+ let cancelled = false;
1788
+
1789
+ const addSignalProperty = object => {
1790
+ Object.defineProperty(object, 'signal', {
1791
+ enumerable: true,
1792
+ get: () => {
1793
+ var _context$signal;
1794
+
1795
+ if ((_context$signal = context.signal) != null && _context$signal.aborted) {
1796
+ cancelled = true;
1797
+ } else {
1798
+ var _context$signal2;
1799
+
1800
+ (_context$signal2 = context.signal) == null ? void 0 : _context$signal2.addEventListener('abort', () => {
1801
+ cancelled = true;
1802
+ });
1803
+ }
1804
+
1805
+ return context.signal;
1806
+ }
1807
+ });
1808
+ }; // Get query function
1809
+
1810
+
1811
+ const queryFn = context.options.queryFn || (() => Promise.reject("Missing queryFn for queryKey '" + context.options.queryHash + "'"));
1812
+
1813
+ const buildNewPages = (pages, param, page, previous) => {
1814
+ newPageParams = previous ? [param, ...newPageParams] : [...newPageParams, param];
1815
+ return previous ? [page, ...pages] : [...pages, page];
1816
+ }; // Create function to fetch a page
1817
+
1818
+
1819
+ const fetchPage = (pages, manual, param, previous) => {
1820
+ if (cancelled) {
1821
+ return Promise.reject('Cancelled');
1822
+ }
1823
+
1824
+ if (typeof param === 'undefined' && !manual && pages.length) {
1825
+ return Promise.resolve(pages);
1826
+ }
1827
+
1828
+ const queryFnContext = {
1829
+ queryKey: context.queryKey,
1830
+ pageParam: param,
1831
+ meta: context.options.meta
1832
+ };
1833
+ addSignalProperty(queryFnContext);
1834
+ const queryFnResult = queryFn(queryFnContext);
1835
+ const promise = Promise.resolve(queryFnResult).then(page => buildNewPages(pages, param, page, previous));
1836
+ return promise;
1837
+ };
1838
+
1839
+ let promise; // Fetch first page?
1840
+
1841
+ if (!oldPages.length) {
1842
+ promise = fetchPage([]);
1843
+ } // Fetch next page?
1844
+ else if (isFetchingNextPage) {
1845
+ const manual = typeof pageParam !== 'undefined';
1846
+ const param = manual ? pageParam : getNextPageParam(context.options, oldPages);
1847
+ promise = fetchPage(oldPages, manual, param);
1848
+ } // Fetch previous page?
1849
+ else if (isFetchingPreviousPage) {
1850
+ const manual = typeof pageParam !== 'undefined';
1851
+ const param = manual ? pageParam : getPreviousPageParam(context.options, oldPages);
1852
+ promise = fetchPage(oldPages, manual, param, true);
1853
+ } // Refetch pages
1854
+ else {
1855
+ newPageParams = [];
1856
+ const manual = typeof context.options.getNextPageParam === 'undefined';
1857
+ const shouldFetchFirstPage = refetchPage && oldPages[0] ? refetchPage(oldPages[0], 0, oldPages) : true; // Fetch first page
1858
+
1859
+ promise = shouldFetchFirstPage ? fetchPage([], manual, oldPageParams[0]) : Promise.resolve(buildNewPages([], oldPageParams[0], oldPages[0])); // Fetch remaining pages
1860
+
1861
+ for (let i = 1; i < oldPages.length; i++) {
1862
+ promise = promise.then(pages => {
1863
+ const shouldFetchNextPage = refetchPage && oldPages[i] ? refetchPage(oldPages[i], i, oldPages) : true;
1864
+
1865
+ if (shouldFetchNextPage) {
1866
+ const param = manual ? oldPageParams[i] : getNextPageParam(context.options, pages);
1867
+ return fetchPage(pages, manual, param);
1868
+ }
1869
+
1870
+ return Promise.resolve(buildNewPages(pages, oldPageParams[i], oldPages[i]));
1871
+ });
1872
+ }
1873
+ }
1874
+
1875
+ const finalPromise = promise.then(pages => ({
1876
+ pages,
1877
+ pageParams: newPageParams
1878
+ }));
1879
+ return finalPromise;
1880
+ };
1881
+ }
1882
+ };
1883
+ }
1884
+ function getNextPageParam(options, pages) {
1885
+ return options.getNextPageParam == null ? void 0 : options.getNextPageParam(pages[pages.length - 1], pages);
1886
+ }
1887
+ function getPreviousPageParam(options, pages) {
1888
+ return options.getPreviousPageParam == null ? void 0 : options.getPreviousPageParam(pages[0], pages);
1889
+ }
1890
+ /**
1891
+ * Checks if there is a next page.
1892
+ * Returns `undefined` if it cannot be determined.
1893
+ */
1894
+
1895
+ function hasNextPage(options, pages) {
1896
+ if (options.getNextPageParam && Array.isArray(pages)) {
1897
+ const nextPageParam = getNextPageParam(options, pages);
1898
+ return typeof nextPageParam !== 'undefined' && nextPageParam !== null && nextPageParam !== false;
1899
+ }
1900
+
1901
+ return;
1902
+ }
1903
+ /**
1904
+ * Checks if there is a previous page.
1905
+ * Returns `undefined` if it cannot be determined.
1906
+ */
1907
+
1908
+ function hasPreviousPage(options, pages) {
1909
+ if (options.getPreviousPageParam && Array.isArray(pages)) {
1910
+ const previousPageParam = getPreviousPageParam(options, pages);
1911
+ return typeof previousPageParam !== 'undefined' && previousPageParam !== null && previousPageParam !== false;
1912
+ }
1913
+
1914
+ return;
1915
+ }
1916
+
1917
+ // CLASS
1918
+ class QueryClient {
1919
+ constructor(config = {}) {
1920
+ this.queryCache = config.queryCache || new QueryCache();
1921
+ this.mutationCache = config.mutationCache || new MutationCache();
1922
+ this.logger = config.logger || defaultLogger;
1923
+ this.defaultOptions = config.defaultOptions || {};
1924
+ this.queryDefaults = [];
1925
+ this.mutationDefaults = [];
1926
+ this.mountCount = 0;
1927
+
1928
+ if (config.logger) {
1929
+ this.logger.error("Passing a custom logger has been deprecated and will be removed in the next major version.");
1930
+ }
1931
+ }
1932
+
1933
+ mount() {
1934
+ this.mountCount++;
1935
+ if (this.mountCount !== 1) return;
1936
+ this.unsubscribeFocus = focusManager.subscribe(() => {
1937
+ if (focusManager.isFocused()) {
1938
+ this.resumePausedMutations();
1939
+ this.queryCache.onFocus();
1940
+ }
1941
+ });
1942
+ this.unsubscribeOnline = onlineManager.subscribe(() => {
1943
+ if (onlineManager.isOnline()) {
1944
+ this.resumePausedMutations();
1945
+ this.queryCache.onOnline();
1946
+ }
1947
+ });
1948
+ }
1949
+
1950
+ unmount() {
1951
+ var _this$unsubscribeFocu, _this$unsubscribeOnli;
1952
+
1953
+ this.mountCount--;
1954
+ if (this.mountCount !== 0) return;
1955
+ (_this$unsubscribeFocu = this.unsubscribeFocus) == null ? void 0 : _this$unsubscribeFocu.call(this);
1956
+ this.unsubscribeFocus = undefined;
1957
+ (_this$unsubscribeOnli = this.unsubscribeOnline) == null ? void 0 : _this$unsubscribeOnli.call(this);
1958
+ this.unsubscribeOnline = undefined;
1959
+ }
1960
+
1961
+ /**
1962
+ * @deprecated This method should be used with only one object argument.
1963
+ */
1964
+ isFetching(arg1, arg2) {
1965
+ const [filters] = parseFilterArgs(arg1, arg2);
1966
+ filters.fetchStatus = 'fetching';
1967
+ return this.queryCache.findAll(filters).length;
1968
+ }
1969
+
1970
+ isMutating(filters) {
1971
+ return this.mutationCache.findAll({ ...filters,
1972
+ fetching: true
1973
+ }).length;
1974
+ }
1975
+
1976
+ /**
1977
+ * @deprecated This method will accept only queryKey in the next major version.
1978
+ */
1979
+ getQueryData(queryKey, filters) {
1980
+ var _this$queryCache$find;
1981
+
1982
+ return (_this$queryCache$find = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find.state.data;
1983
+ }
1984
+
1985
+ /**
1986
+ * @deprecated This method should be used with only one object argument.
1987
+ */
1988
+ ensureQueryData(arg1, arg2, arg3) {
1989
+ const parsedOptions = parseQueryArgs(arg1, arg2, arg3);
1990
+ const cachedData = this.getQueryData(parsedOptions.queryKey);
1991
+ return cachedData ? Promise.resolve(cachedData) : this.fetchQuery(parsedOptions);
1992
+ }
1993
+
1994
+ /**
1995
+ * @deprecated This method should be used with only one object argument.
1996
+ */
1997
+ getQueriesData(queryKeyOrFilters) {
1998
+ return this.getQueryCache().findAll(queryKeyOrFilters).map(({
1999
+ queryKey,
2000
+ state
2001
+ }) => {
2002
+ const data = state.data;
2003
+ return [queryKey, data];
2004
+ });
2005
+ }
2006
+
2007
+ setQueryData(queryKey, updater, options) {
2008
+ const query = this.queryCache.find(queryKey);
2009
+ const prevData = query == null ? void 0 : query.state.data;
2010
+ const data = functionalUpdate(updater, prevData);
2011
+
2012
+ if (typeof data === 'undefined') {
2013
+ return undefined;
2014
+ }
2015
+
2016
+ const parsedOptions = parseQueryArgs(queryKey);
2017
+ const defaultedOptions = this.defaultQueryOptions(parsedOptions);
2018
+ return this.queryCache.build(this, defaultedOptions).setData(data, { ...options,
2019
+ manual: true
2020
+ });
2021
+ }
2022
+
2023
+ /**
2024
+ * @deprecated This method should be used with only one object argument.
2025
+ */
2026
+ setQueriesData(queryKeyOrFilters, updater, options) {
2027
+ return notifyManager.batch(() => this.getQueryCache().findAll(queryKeyOrFilters).map(({
2028
+ queryKey
2029
+ }) => [queryKey, this.setQueryData(queryKey, updater, options)]));
2030
+ }
2031
+
2032
+ getQueryState(queryKey,
2033
+ /**
2034
+ * @deprecated This filters will be removed in the next major version.
2035
+ */
2036
+ filters) {
2037
+ var _this$queryCache$find2;
2038
+
2039
+ return (_this$queryCache$find2 = this.queryCache.find(queryKey, filters)) == null ? void 0 : _this$queryCache$find2.state;
2040
+ }
2041
+
2042
+ /**
2043
+ * @deprecated This method should be used with only one object argument.
2044
+ */
2045
+ removeQueries(arg1, arg2) {
2046
+ const [filters] = parseFilterArgs(arg1, arg2);
2047
+ const queryCache = this.queryCache;
2048
+ notifyManager.batch(() => {
2049
+ queryCache.findAll(filters).forEach(query => {
2050
+ queryCache.remove(query);
2051
+ });
2052
+ });
2053
+ }
2054
+
2055
+ /**
2056
+ * @deprecated This method should be used with only one object argument.
2057
+ */
2058
+ resetQueries(arg1, arg2, arg3) {
2059
+ const [filters, options] = parseFilterArgs(arg1, arg2, arg3);
2060
+ const queryCache = this.queryCache;
2061
+ const refetchFilters = {
2062
+ type: 'active',
2063
+ ...filters
2064
+ };
2065
+ return notifyManager.batch(() => {
2066
+ queryCache.findAll(filters).forEach(query => {
2067
+ query.reset();
2068
+ });
2069
+ return this.refetchQueries(refetchFilters, options);
2070
+ });
2071
+ }
2072
+
2073
+ /**
2074
+ * @deprecated This method should be used with only one object argument.
2075
+ */
2076
+ cancelQueries(arg1, arg2, arg3) {
2077
+ const [filters, cancelOptions = {}] = parseFilterArgs(arg1, arg2, arg3);
2078
+
2079
+ if (typeof cancelOptions.revert === 'undefined') {
2080
+ cancelOptions.revert = true;
2081
+ }
2082
+
2083
+ const promises = notifyManager.batch(() => this.queryCache.findAll(filters).map(query => query.cancel(cancelOptions)));
2084
+ return Promise.all(promises).then(noop$1).catch(noop$1);
2085
+ }
2086
+
2087
+ /**
2088
+ * @deprecated This method should be used with only one object argument.
2089
+ */
2090
+ invalidateQueries(arg1, arg2, arg3) {
2091
+ const [filters, options] = parseFilterArgs(arg1, arg2, arg3);
2092
+ return notifyManager.batch(() => {
2093
+ var _ref, _filters$refetchType;
2094
+
2095
+ this.queryCache.findAll(filters).forEach(query => {
2096
+ query.invalidate();
2097
+ });
2098
+
2099
+ if (filters.refetchType === 'none') {
2100
+ return Promise.resolve();
2101
+ }
2102
+
2103
+ const refetchFilters = { ...filters,
2104
+ type: (_ref = (_filters$refetchType = filters.refetchType) != null ? _filters$refetchType : filters.type) != null ? _ref : 'active'
2105
+ };
2106
+ return this.refetchQueries(refetchFilters, options);
2107
+ });
2108
+ }
2109
+
2110
+ /**
2111
+ * @deprecated This method should be used with only one object argument.
2112
+ */
2113
+ refetchQueries(arg1, arg2, arg3) {
2114
+ const [filters, options] = parseFilterArgs(arg1, arg2, arg3);
2115
+ const promises = notifyManager.batch(() => this.queryCache.findAll(filters).filter(query => !query.isDisabled()).map(query => {
2116
+ var _options$cancelRefetc;
2117
+
2118
+ return query.fetch(undefined, { ...options,
2119
+ cancelRefetch: (_options$cancelRefetc = options == null ? void 0 : options.cancelRefetch) != null ? _options$cancelRefetc : true,
2120
+ meta: {
2121
+ refetchPage: filters.refetchPage
2122
+ }
2123
+ });
2124
+ }));
2125
+ let promise = Promise.all(promises).then(noop$1);
2126
+
2127
+ if (!(options != null && options.throwOnError)) {
2128
+ promise = promise.catch(noop$1);
2129
+ }
2130
+
2131
+ return promise;
2132
+ }
2133
+
2134
+ /**
2135
+ * @deprecated This method should be used with only one object argument.
2136
+ */
2137
+ fetchQuery(arg1, arg2, arg3) {
2138
+ const parsedOptions = parseQueryArgs(arg1, arg2, arg3);
2139
+ const defaultedOptions = this.defaultQueryOptions(parsedOptions); // https://github.com/tannerlinsley/react-query/issues/652
2140
+
2141
+ if (typeof defaultedOptions.retry === 'undefined') {
2142
+ defaultedOptions.retry = false;
2143
+ }
2144
+
2145
+ const query = this.queryCache.build(this, defaultedOptions);
2146
+ return query.isStaleByTime(defaultedOptions.staleTime) ? query.fetch(defaultedOptions) : Promise.resolve(query.state.data);
2147
+ }
2148
+
2149
+ /**
2150
+ * @deprecated This method should be used with only one object argument.
2151
+ */
2152
+ prefetchQuery(arg1, arg2, arg3) {
2153
+ return this.fetchQuery(arg1, arg2, arg3).then(noop$1).catch(noop$1);
2154
+ }
2155
+
2156
+ /**
2157
+ * @deprecated This method should be used with only one object argument.
2158
+ */
2159
+ fetchInfiniteQuery(arg1, arg2, arg3) {
2160
+ const parsedOptions = parseQueryArgs(arg1, arg2, arg3);
2161
+ parsedOptions.behavior = infiniteQueryBehavior();
2162
+ return this.fetchQuery(parsedOptions);
2163
+ }
2164
+
2165
+ /**
2166
+ * @deprecated This method should be used with only one object argument.
2167
+ */
2168
+ prefetchInfiniteQuery(arg1, arg2, arg3) {
2169
+ return this.fetchInfiniteQuery(arg1, arg2, arg3).then(noop$1).catch(noop$1);
2170
+ }
2171
+
2172
+ resumePausedMutations() {
2173
+ return this.mutationCache.resumePausedMutations();
2174
+ }
2175
+
2176
+ getQueryCache() {
2177
+ return this.queryCache;
2178
+ }
2179
+
2180
+ getMutationCache() {
2181
+ return this.mutationCache;
2182
+ }
2183
+
2184
+ getLogger() {
2185
+ return this.logger;
2186
+ }
2187
+
2188
+ getDefaultOptions() {
2189
+ return this.defaultOptions;
2190
+ }
2191
+
2192
+ setDefaultOptions(options) {
2193
+ this.defaultOptions = options;
2194
+ }
2195
+
2196
+ setQueryDefaults(queryKey, options) {
2197
+ const result = this.queryDefaults.find(x => hashQueryKey(queryKey) === hashQueryKey(x.queryKey));
2198
+
2199
+ if (result) {
2200
+ result.defaultOptions = options;
2201
+ } else {
2202
+ this.queryDefaults.push({
2203
+ queryKey,
2204
+ defaultOptions: options
2205
+ });
2206
+ }
2207
+ }
2208
+
2209
+ getQueryDefaults(queryKey) {
2210
+ if (!queryKey) {
2211
+ return undefined;
2212
+ } // Get the first matching defaults
2213
+
2214
+
2215
+ const firstMatchingDefaults = this.queryDefaults.find(x => partialMatchKey(queryKey, x.queryKey)); // Additional checks and error in dev mode
2216
+
2217
+ {
2218
+ // Retrieve all matching defaults for the given key
2219
+ 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
2220
+
2221
+ if (matchingDefaults.length > 1) {
2222
+ 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.");
2223
+ }
2224
+ }
2225
+
2226
+ return firstMatchingDefaults == null ? void 0 : firstMatchingDefaults.defaultOptions;
2227
+ }
2228
+
2229
+ setMutationDefaults(mutationKey, options) {
2230
+ const result = this.mutationDefaults.find(x => hashQueryKey(mutationKey) === hashQueryKey(x.mutationKey));
2231
+
2232
+ if (result) {
2233
+ result.defaultOptions = options;
2234
+ } else {
2235
+ this.mutationDefaults.push({
2236
+ mutationKey,
2237
+ defaultOptions: options
2238
+ });
2239
+ }
2240
+ }
2241
+
2242
+ getMutationDefaults(mutationKey) {
2243
+ if (!mutationKey) {
2244
+ return undefined;
2245
+ } // Get the first matching defaults
2246
+
2247
+
2248
+ const firstMatchingDefaults = this.mutationDefaults.find(x => partialMatchKey(mutationKey, x.mutationKey)); // Additional checks and error in dev mode
2249
+
2250
+ {
2251
+ // Retrieve all matching defaults for the given key
2252
+ 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
2253
+
2254
+ if (matchingDefaults.length > 1) {
2255
+ 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.");
2256
+ }
2257
+ }
2258
+
2259
+ return firstMatchingDefaults == null ? void 0 : firstMatchingDefaults.defaultOptions;
2260
+ }
2261
+
2262
+ defaultQueryOptions(options) {
2263
+ if (options != null && options._defaulted) {
2264
+ return options;
2265
+ }
2266
+
2267
+ const defaultedOptions = { ...this.defaultOptions.queries,
2268
+ ...this.getQueryDefaults(options == null ? void 0 : options.queryKey),
2269
+ ...options,
2270
+ _defaulted: true
2271
+ };
2272
+
2273
+ if (!defaultedOptions.queryHash && defaultedOptions.queryKey) {
2274
+ defaultedOptions.queryHash = hashQueryKeyByOptions(defaultedOptions.queryKey, defaultedOptions);
2275
+ } // dependent default values
2276
+
2277
+
2278
+ if (typeof defaultedOptions.refetchOnReconnect === 'undefined') {
2279
+ defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== 'always';
2280
+ }
2281
+
2282
+ if (typeof defaultedOptions.useErrorBoundary === 'undefined') {
2283
+ defaultedOptions.useErrorBoundary = !!defaultedOptions.suspense;
2284
+ }
2285
+
2286
+ return defaultedOptions;
2287
+ }
2288
+
2289
+ defaultMutationOptions(options) {
2290
+ if (options != null && options._defaulted) {
2291
+ return options;
2292
+ }
2293
+
2294
+ return { ...this.defaultOptions.mutations,
2295
+ ...this.getMutationDefaults(options == null ? void 0 : options.mutationKey),
2296
+ ...options,
2297
+ _defaulted: true
2298
+ };
2299
+ }
2300
+
2301
+ clear() {
2302
+ this.queryCache.clear();
2303
+ this.mutationCache.clear();
2304
+ }
2305
+
2306
+ }
2307
+
2308
+ class QueryObserver extends Subscribable {
2309
+ constructor(client, options) {
2310
+ super();
2311
+ this.client = client;
2312
+ this.options = options;
2313
+ this.trackedProps = new Set();
2314
+ this.selectError = null;
2315
+ this.bindMethods();
2316
+ this.setOptions(options);
2317
+ }
2318
+
2319
+ bindMethods() {
2320
+ this.remove = this.remove.bind(this);
2321
+ this.refetch = this.refetch.bind(this);
2322
+ }
2323
+
2324
+ onSubscribe() {
2325
+ if (this.listeners.size === 1) {
2326
+ this.currentQuery.addObserver(this);
2327
+
2328
+ if (shouldFetchOnMount(this.currentQuery, this.options)) {
2329
+ this.executeFetch();
2330
+ }
2331
+
2332
+ this.updateTimers();
2333
+ }
2334
+ }
2335
+
2336
+ onUnsubscribe() {
2337
+ if (!this.hasListeners()) {
2338
+ this.destroy();
2339
+ }
2340
+ }
2341
+
2342
+ shouldFetchOnReconnect() {
2343
+ return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnReconnect);
2344
+ }
2345
+
2346
+ shouldFetchOnWindowFocus() {
2347
+ return shouldFetchOn(this.currentQuery, this.options, this.options.refetchOnWindowFocus);
2348
+ }
2349
+
2350
+ destroy() {
2351
+ this.listeners = new Set();
2352
+ this.clearStaleTimeout();
2353
+ this.clearRefetchInterval();
2354
+ this.currentQuery.removeObserver(this);
2355
+ }
2356
+
2357
+ setOptions(options, notifyOptions) {
2358
+ const prevOptions = this.options;
2359
+ const prevQuery = this.currentQuery;
2360
+ this.options = this.client.defaultQueryOptions(options);
2361
+
2362
+ if (typeof (options == null ? void 0 : options.isDataEqual) !== 'undefined') {
2363
+ this.client.getLogger().error("The isDataEqual option has been deprecated and will be removed in the next major version. You can achieve the same functionality by passing a function as the structuralSharing option");
2364
+ }
2365
+
2366
+ if (!shallowEqualObjects(prevOptions, this.options)) {
2367
+ this.client.getQueryCache().notify({
2368
+ type: 'observerOptionsUpdated',
2369
+ query: this.currentQuery,
2370
+ observer: this
2371
+ });
2372
+ }
2373
+
2374
+ if (typeof this.options.enabled !== 'undefined' && typeof this.options.enabled !== 'boolean') {
2375
+ throw new Error('Expected enabled to be a boolean');
2376
+ } // Keep previous query key if the user does not supply one
2377
+
2378
+
2379
+ if (!this.options.queryKey) {
2380
+ this.options.queryKey = prevOptions.queryKey;
2381
+ }
2382
+
2383
+ this.updateQuery();
2384
+ const mounted = this.hasListeners(); // Fetch if there are subscribers
2385
+
2386
+ if (mounted && shouldFetchOptionally(this.currentQuery, prevQuery, this.options, prevOptions)) {
2387
+ this.executeFetch();
2388
+ } // Update result
2389
+
2390
+
2391
+ this.updateResult(notifyOptions); // Update stale interval if needed
2392
+
2393
+ if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || this.options.staleTime !== prevOptions.staleTime)) {
2394
+ this.updateStaleTimeout();
2395
+ }
2396
+
2397
+ const nextRefetchInterval = this.computeRefetchInterval(); // Update refetch interval if needed
2398
+
2399
+ if (mounted && (this.currentQuery !== prevQuery || this.options.enabled !== prevOptions.enabled || nextRefetchInterval !== this.currentRefetchInterval)) {
2400
+ this.updateRefetchInterval(nextRefetchInterval);
2401
+ }
2402
+ }
2403
+
2404
+ getOptimisticResult(options) {
2405
+ const query = this.client.getQueryCache().build(this.client, options);
2406
+ const result = this.createResult(query, options);
2407
+
2408
+ if (shouldAssignObserverCurrentProperties(this, result, options)) {
2409
+ // this assigns the optimistic result to the current Observer
2410
+ // because if the query function changes, useQuery will be performing
2411
+ // an effect where it would fetch again.
2412
+ // When the fetch finishes, we perform a deep data cloning in order
2413
+ // to reuse objects references. This deep data clone is performed against
2414
+ // the `observer.currentResult.data` property
2415
+ // When QueryKey changes, we refresh the query and get new `optimistic`
2416
+ // result, while we leave the `observer.currentResult`, so when new data
2417
+ // arrives, it finds the old `observer.currentResult` which is related
2418
+ // to the old QueryKey. Which means that currentResult and selectData are
2419
+ // out of sync already.
2420
+ // To solve this, we move the cursor of the currentResult everytime
2421
+ // an observer reads an optimistic value.
2422
+ // When keeping the previous data, the result doesn't change until new
2423
+ // data arrives.
2424
+ this.currentResult = result;
2425
+ this.currentResultOptions = this.options;
2426
+ this.currentResultState = this.currentQuery.state;
2427
+ }
2428
+
2429
+ return result;
2430
+ }
2431
+
2432
+ getCurrentResult() {
2433
+ return this.currentResult;
2434
+ }
2435
+
2436
+ trackResult(result) {
2437
+ const trackedResult = {};
2438
+ Object.keys(result).forEach(key => {
2439
+ Object.defineProperty(trackedResult, key, {
2440
+ configurable: false,
2441
+ enumerable: true,
2442
+ get: () => {
2443
+ this.trackedProps.add(key);
2444
+ return result[key];
2445
+ }
2446
+ });
2447
+ });
2448
+ return trackedResult;
2449
+ }
2450
+
2451
+ getCurrentQuery() {
2452
+ return this.currentQuery;
2453
+ }
2454
+
2455
+ remove() {
2456
+ this.client.getQueryCache().remove(this.currentQuery);
2457
+ }
2458
+
2459
+ refetch({
2460
+ refetchPage,
2461
+ ...options
2462
+ } = {}) {
2463
+ return this.fetch({ ...options,
2464
+ meta: {
2465
+ refetchPage
2466
+ }
2467
+ });
2468
+ }
2469
+
2470
+ fetchOptimistic(options) {
2471
+ const defaultedOptions = this.client.defaultQueryOptions(options);
2472
+ const query = this.client.getQueryCache().build(this.client, defaultedOptions);
2473
+ query.isFetchingOptimistic = true;
2474
+ return query.fetch().then(() => this.createResult(query, defaultedOptions));
2475
+ }
2476
+
2477
+ fetch(fetchOptions) {
2478
+ var _fetchOptions$cancelR;
2479
+
2480
+ return this.executeFetch({ ...fetchOptions,
2481
+ cancelRefetch: (_fetchOptions$cancelR = fetchOptions.cancelRefetch) != null ? _fetchOptions$cancelR : true
2482
+ }).then(() => {
2483
+ this.updateResult();
2484
+ return this.currentResult;
2485
+ });
2486
+ }
2487
+
2488
+ executeFetch(fetchOptions) {
2489
+ // Make sure we reference the latest query as the current one might have been removed
2490
+ this.updateQuery(); // Fetch
2491
+
2492
+ let promise = this.currentQuery.fetch(this.options, fetchOptions);
2493
+
2494
+ if (!(fetchOptions != null && fetchOptions.throwOnError)) {
2495
+ promise = promise.catch(noop$1);
2496
+ }
2497
+
2498
+ return promise;
2499
+ }
2500
+
2501
+ updateStaleTimeout() {
2502
+ this.clearStaleTimeout();
2503
+
2504
+ if (isServer || this.currentResult.isStale || !isValidTimeout(this.options.staleTime)) {
2505
+ return;
2506
+ }
2507
+
2508
+ const time = timeUntilStale(this.currentResult.dataUpdatedAt, this.options.staleTime); // The timeout is sometimes triggered 1 ms before the stale time expiration.
2509
+ // To mitigate this issue we always add 1 ms to the timeout.
2510
+
2511
+ const timeout = time + 1;
2512
+ this.staleTimeoutId = setTimeout(() => {
2513
+ if (!this.currentResult.isStale) {
2514
+ this.updateResult();
2515
+ }
2516
+ }, timeout);
2517
+ }
2518
+
2519
+ computeRefetchInterval() {
2520
+ var _this$options$refetch;
2521
+
2522
+ 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;
2523
+ }
2524
+
2525
+ updateRefetchInterval(nextInterval) {
2526
+ this.clearRefetchInterval();
2527
+ this.currentRefetchInterval = nextInterval;
2528
+
2529
+ if (isServer || this.options.enabled === false || !isValidTimeout(this.currentRefetchInterval) || this.currentRefetchInterval === 0) {
2530
+ return;
2531
+ }
2532
+
2533
+ this.refetchIntervalId = setInterval(() => {
2534
+ if (this.options.refetchIntervalInBackground || focusManager.isFocused()) {
2535
+ this.executeFetch();
2536
+ }
2537
+ }, this.currentRefetchInterval);
2538
+ }
2539
+
2540
+ updateTimers() {
2541
+ this.updateStaleTimeout();
2542
+ this.updateRefetchInterval(this.computeRefetchInterval());
2543
+ }
2544
+
2545
+ clearStaleTimeout() {
2546
+ if (this.staleTimeoutId) {
2547
+ clearTimeout(this.staleTimeoutId);
2548
+ this.staleTimeoutId = undefined;
2549
+ }
2550
+ }
2551
+
2552
+ clearRefetchInterval() {
2553
+ if (this.refetchIntervalId) {
2554
+ clearInterval(this.refetchIntervalId);
2555
+ this.refetchIntervalId = undefined;
2556
+ }
2557
+ }
2558
+
2559
+ createResult(query, options) {
2560
+ const prevQuery = this.currentQuery;
2561
+ const prevOptions = this.options;
2562
+ const prevResult = this.currentResult;
2563
+ const prevResultState = this.currentResultState;
2564
+ const prevResultOptions = this.currentResultOptions;
2565
+ const queryChange = query !== prevQuery;
2566
+ const queryInitialState = queryChange ? query.state : this.currentQueryInitialState;
2567
+ const prevQueryResult = queryChange ? this.currentResult : this.previousQueryResult;
2568
+ const {
2569
+ state
2570
+ } = query;
2571
+ let {
2572
+ dataUpdatedAt,
2573
+ error,
2574
+ errorUpdatedAt,
2575
+ fetchStatus,
2576
+ status
2577
+ } = state;
2578
+ let isPreviousData = false;
2579
+ let isPlaceholderData = false;
2580
+ let data; // Optimistically set result in fetching state if needed
2581
+
2582
+ if (options._optimisticResults) {
2583
+ const mounted = this.hasListeners();
2584
+ const fetchOnMount = !mounted && shouldFetchOnMount(query, options);
2585
+ const fetchOptionally = mounted && shouldFetchOptionally(query, prevQuery, options, prevOptions);
2586
+
2587
+ if (fetchOnMount || fetchOptionally) {
2588
+ fetchStatus = canFetch(query.options.networkMode) ? 'fetching' : 'paused';
2589
+
2590
+ if (!dataUpdatedAt) {
2591
+ status = 'loading';
2592
+ }
2593
+ }
2594
+
2595
+ if (options._optimisticResults === 'isRestoring') {
2596
+ fetchStatus = 'idle';
2597
+ }
2598
+ } // Keep previous data if needed
2599
+
2600
+
2601
+ if (options.keepPreviousData && !state.dataUpdatedAt && prevQueryResult != null && prevQueryResult.isSuccess && status !== 'error') {
2602
+ data = prevQueryResult.data;
2603
+ dataUpdatedAt = prevQueryResult.dataUpdatedAt;
2604
+ status = prevQueryResult.status;
2605
+ isPreviousData = true;
2606
+ } // Select data if needed
2607
+ else if (options.select && typeof state.data !== 'undefined') {
2608
+ // Memoize select result
2609
+ if (prevResult && state.data === (prevResultState == null ? void 0 : prevResultState.data) && options.select === this.selectFn) {
2610
+ data = this.selectResult;
2611
+ } else {
2612
+ try {
2613
+ this.selectFn = options.select;
2614
+ data = options.select(state.data);
2615
+ data = replaceData(prevResult == null ? void 0 : prevResult.data, data, options);
2616
+ this.selectResult = data;
2617
+ this.selectError = null;
2618
+ } catch (selectError) {
2619
+ {
2620
+ this.client.getLogger().error(selectError);
2621
+ }
2622
+
2623
+ this.selectError = selectError;
2624
+ }
2625
+ }
2626
+ } // Use query data
2627
+ else {
2628
+ data = state.data;
2629
+ } // Show placeholder data if needed
2630
+
2631
+
2632
+ if (typeof options.placeholderData !== 'undefined' && typeof data === 'undefined' && status === 'loading') {
2633
+ let placeholderData; // Memoize placeholder data
2634
+
2635
+ if (prevResult != null && prevResult.isPlaceholderData && options.placeholderData === (prevResultOptions == null ? void 0 : prevResultOptions.placeholderData)) {
2636
+ placeholderData = prevResult.data;
2637
+ } else {
2638
+ placeholderData = typeof options.placeholderData === 'function' ? options.placeholderData() : options.placeholderData;
2639
+
2640
+ if (options.select && typeof placeholderData !== 'undefined') {
2641
+ try {
2642
+ placeholderData = options.select(placeholderData);
2643
+ this.selectError = null;
2644
+ } catch (selectError) {
2645
+ {
2646
+ this.client.getLogger().error(selectError);
2647
+ }
2648
+
2649
+ this.selectError = selectError;
2650
+ }
2651
+ }
2652
+ }
2653
+
2654
+ if (typeof placeholderData !== 'undefined') {
2655
+ status = 'success';
2656
+ data = replaceData(prevResult == null ? void 0 : prevResult.data, placeholderData, options);
2657
+ isPlaceholderData = true;
2658
+ }
2659
+ }
2660
+
2661
+ if (this.selectError) {
2662
+ error = this.selectError;
2663
+ data = this.selectResult;
2664
+ errorUpdatedAt = Date.now();
2665
+ status = 'error';
2666
+ }
2667
+
2668
+ const isFetching = fetchStatus === 'fetching';
2669
+ const isLoading = status === 'loading';
2670
+ const isError = status === 'error';
2671
+ const result = {
2672
+ status,
2673
+ fetchStatus,
2674
+ isLoading,
2675
+ isSuccess: status === 'success',
2676
+ isError,
2677
+ isInitialLoading: isLoading && isFetching,
2678
+ data,
2679
+ dataUpdatedAt,
2680
+ error,
2681
+ errorUpdatedAt,
2682
+ failureCount: state.fetchFailureCount,
2683
+ failureReason: state.fetchFailureReason,
2684
+ errorUpdateCount: state.errorUpdateCount,
2685
+ isFetched: state.dataUpdateCount > 0 || state.errorUpdateCount > 0,
2686
+ isFetchedAfterMount: state.dataUpdateCount > queryInitialState.dataUpdateCount || state.errorUpdateCount > queryInitialState.errorUpdateCount,
2687
+ isFetching,
2688
+ isRefetching: isFetching && !isLoading,
2689
+ isLoadingError: isError && state.dataUpdatedAt === 0,
2690
+ isPaused: fetchStatus === 'paused',
2691
+ isPlaceholderData,
2692
+ isPreviousData,
2693
+ isRefetchError: isError && state.dataUpdatedAt !== 0,
2694
+ isStale: isStale(query, options),
2695
+ refetch: this.refetch,
2696
+ remove: this.remove
2697
+ };
2698
+ return result;
2699
+ }
2700
+
2701
+ updateResult(notifyOptions) {
2702
+ const prevResult = this.currentResult;
2703
+ const nextResult = this.createResult(this.currentQuery, this.options);
2704
+ this.currentResultState = this.currentQuery.state;
2705
+ this.currentResultOptions = this.options; // Only notify and update result if something has changed
2706
+
2707
+ if (shallowEqualObjects(nextResult, prevResult)) {
2708
+ return;
2709
+ }
2710
+
2711
+ this.currentResult = nextResult; // Determine which callbacks to trigger
2712
+
2713
+ const defaultNotifyOptions = {
2714
+ cache: true
2715
+ };
2716
+
2717
+ const shouldNotifyListeners = () => {
2718
+ if (!prevResult) {
2719
+ return true;
2720
+ }
2721
+
2722
+ const {
2723
+ notifyOnChangeProps
2724
+ } = this.options;
2725
+ const notifyOnChangePropsValue = typeof notifyOnChangeProps === 'function' ? notifyOnChangeProps() : notifyOnChangeProps;
2726
+
2727
+ if (notifyOnChangePropsValue === 'all' || !notifyOnChangePropsValue && !this.trackedProps.size) {
2728
+ return true;
2729
+ }
2730
+
2731
+ const includedProps = new Set(notifyOnChangePropsValue != null ? notifyOnChangePropsValue : this.trackedProps);
2732
+
2733
+ if (this.options.useErrorBoundary) {
2734
+ includedProps.add('error');
2735
+ }
2736
+
2737
+ return Object.keys(this.currentResult).some(key => {
2738
+ const typedKey = key;
2739
+ const changed = this.currentResult[typedKey] !== prevResult[typedKey];
2740
+ return changed && includedProps.has(typedKey);
2741
+ });
2742
+ };
2743
+
2744
+ if ((notifyOptions == null ? void 0 : notifyOptions.listeners) !== false && shouldNotifyListeners()) {
2745
+ defaultNotifyOptions.listeners = true;
2746
+ }
2747
+
2748
+ this.notify({ ...defaultNotifyOptions,
2749
+ ...notifyOptions
2750
+ });
2751
+ }
2752
+
2753
+ updateQuery() {
2754
+ const query = this.client.getQueryCache().build(this.client, this.options);
2755
+
2756
+ if (query === this.currentQuery) {
2757
+ return;
2758
+ }
2759
+
2760
+ const prevQuery = this.currentQuery;
2761
+ this.currentQuery = query;
2762
+ this.currentQueryInitialState = query.state;
2763
+ this.previousQueryResult = this.currentResult;
2764
+
2765
+ if (this.hasListeners()) {
2766
+ prevQuery == null ? void 0 : prevQuery.removeObserver(this);
2767
+ query.addObserver(this);
2768
+ }
2769
+ }
2770
+
2771
+ onQueryUpdate(action) {
2772
+ const notifyOptions = {};
2773
+
2774
+ if (action.type === 'success') {
2775
+ notifyOptions.onSuccess = !action.manual;
2776
+ } else if (action.type === 'error' && !isCancelledError(action.error)) {
2777
+ notifyOptions.onError = true;
2778
+ }
2779
+
2780
+ this.updateResult(notifyOptions);
2781
+
2782
+ if (this.hasListeners()) {
2783
+ this.updateTimers();
2784
+ }
2785
+ }
2786
+
2787
+ notify(notifyOptions) {
2788
+ notifyManager.batch(() => {
2789
+ // First trigger the configuration callbacks
2790
+ if (notifyOptions.onSuccess) {
2791
+ var _this$options$onSucce, _this$options, _this$options$onSettl, _this$options2;
2792
+
2793
+ (_this$options$onSucce = (_this$options = this.options).onSuccess) == null ? void 0 : _this$options$onSucce.call(_this$options, this.currentResult.data);
2794
+ (_this$options$onSettl = (_this$options2 = this.options).onSettled) == null ? void 0 : _this$options$onSettl.call(_this$options2, this.currentResult.data, null);
2795
+ } else if (notifyOptions.onError) {
2796
+ var _this$options$onError, _this$options3, _this$options$onSettl2, _this$options4;
2797
+
2798
+ (_this$options$onError = (_this$options3 = this.options).onError) == null ? void 0 : _this$options$onError.call(_this$options3, this.currentResult.error);
2799
+ (_this$options$onSettl2 = (_this$options4 = this.options).onSettled) == null ? void 0 : _this$options$onSettl2.call(_this$options4, undefined, this.currentResult.error);
2800
+ } // Then trigger the listeners
2801
+
2802
+
2803
+ if (notifyOptions.listeners) {
2804
+ this.listeners.forEach(({
2805
+ listener
2806
+ }) => {
2807
+ listener(this.currentResult);
2808
+ });
2809
+ } // Then the cache listeners
2810
+
2811
+
2812
+ if (notifyOptions.cache) {
2813
+ this.client.getQueryCache().notify({
2814
+ query: this.currentQuery,
2815
+ type: 'observerResultsUpdated'
2816
+ });
2817
+ }
2818
+ });
2819
+ }
2820
+
2821
+ }
2822
+
2823
+ function shouldLoadOnMount(query, options) {
2824
+ return options.enabled !== false && !query.state.dataUpdatedAt && !(query.state.status === 'error' && options.retryOnMount === false);
2825
+ }
2826
+
2827
+ function shouldFetchOnMount(query, options) {
2828
+ return shouldLoadOnMount(query, options) || query.state.dataUpdatedAt > 0 && shouldFetchOn(query, options, options.refetchOnMount);
2829
+ }
2830
+
2831
+ function shouldFetchOn(query, options, field) {
2832
+ if (options.enabled !== false) {
2833
+ const value = typeof field === 'function' ? field(query) : field;
2834
+ return value === 'always' || value !== false && isStale(query, options);
2835
+ }
2836
+
2837
+ return false;
2838
+ }
2839
+
2840
+ function shouldFetchOptionally(query, prevQuery, options, prevOptions) {
2841
+ return options.enabled !== false && (query !== prevQuery || prevOptions.enabled === false) && (!options.suspense || query.state.status !== 'error') && isStale(query, options);
2842
+ }
2843
+
2844
+ function isStale(query, options) {
2845
+ return query.isStaleByTime(options.staleTime);
2846
+ } // this function would decide if we will update the observer's 'current'
2847
+ // properties after an optimistic reading via getOptimisticResult
2848
+
2849
+
2850
+ function shouldAssignObserverCurrentProperties(observer, optimisticResult, options) {
2851
+ // it is important to keep this condition like this for three reasons:
2852
+ // 1. It will get removed in the v5
2853
+ // 2. it reads: don't update the properties if we want to keep the previous
2854
+ // data.
2855
+ // 3. The opposite condition (!options.keepPreviousData) would fallthrough
2856
+ // and will result in a bad decision
2857
+ if (options.keepPreviousData) {
2858
+ return false;
2859
+ } // this means we want to put some placeholder data when pending and queryKey
2860
+ // changed.
2861
+
2862
+
2863
+ if (options.placeholderData !== undefined) {
2864
+ // re-assign properties only if current data is placeholder data
2865
+ // which means that data did not arrive yet, so, if there is some cached data
2866
+ // we need to "prepare" to receive it
2867
+ return optimisticResult.isPlaceholderData;
2868
+ } // if the newly created result isn't what the observer is holding as current,
2869
+ // then we'll need to update the properties as well
2870
+
2871
+
2872
+ if (!shallowEqualObjects(observer.getCurrentResult(), optimisticResult)) {
2873
+ return true;
2874
+ } // basically, just keep previous properties if nothing changed
2875
+
2876
+
2877
+ return false;
2878
+ }
2879
+
2880
+ class QueriesObserver extends Subscribable {
2881
+ constructor(client, queries) {
2882
+ super();
2883
+ this.client = client;
2884
+ this.queries = [];
2885
+ this.result = [];
2886
+ this.observers = [];
2887
+ this.observersMap = {};
2888
+
2889
+ if (queries) {
2890
+ this.setQueries(queries);
2891
+ }
2892
+ }
2893
+
2894
+ onSubscribe() {
2895
+ if (this.listeners.size === 1) {
2896
+ this.observers.forEach(observer => {
2897
+ observer.subscribe(result => {
2898
+ this.onUpdate(observer, result);
2899
+ });
2900
+ });
2901
+ }
2902
+ }
2903
+
2904
+ onUnsubscribe() {
2905
+ if (!this.listeners.size) {
2906
+ this.destroy();
2907
+ }
2908
+ }
2909
+
2910
+ destroy() {
2911
+ this.listeners = new Set();
2912
+ this.observers.forEach(observer => {
2913
+ observer.destroy();
2914
+ });
2915
+ }
2916
+
2917
+ setQueries(queries, notifyOptions) {
2918
+ this.queries = queries;
2919
+ notifyManager.batch(() => {
2920
+ const prevObservers = this.observers;
2921
+ const newObserverMatches = this.findMatchingObservers(this.queries); // set options for the new observers to notify of changes
2922
+
2923
+ newObserverMatches.forEach(match => match.observer.setOptions(match.defaultedQueryOptions, notifyOptions));
2924
+ const newObservers = newObserverMatches.map(match => match.observer);
2925
+ const newObserversMap = Object.fromEntries(newObservers.map(observer => [observer.options.queryHash, observer]));
2926
+ const newResult = newObservers.map(observer => observer.getCurrentResult());
2927
+ const hasIndexChange = newObservers.some((observer, index) => observer !== prevObservers[index]);
2928
+
2929
+ if (prevObservers.length === newObservers.length && !hasIndexChange) {
2930
+ return;
2931
+ }
2932
+
2933
+ this.observers = newObservers;
2934
+ this.observersMap = newObserversMap;
2935
+ this.result = newResult;
2936
+
2937
+ if (!this.hasListeners()) {
2938
+ return;
2939
+ }
2940
+
2941
+ difference(prevObservers, newObservers).forEach(observer => {
2942
+ observer.destroy();
2943
+ });
2944
+ difference(newObservers, prevObservers).forEach(observer => {
2945
+ observer.subscribe(result => {
2946
+ this.onUpdate(observer, result);
2947
+ });
2948
+ });
2949
+ this.notify();
2950
+ });
2951
+ }
2952
+
2953
+ getCurrentResult() {
2954
+ return this.result;
2955
+ }
2956
+
2957
+ getQueries() {
2958
+ return this.observers.map(observer => observer.getCurrentQuery());
2959
+ }
2960
+
2961
+ getObservers() {
2962
+ return this.observers;
2963
+ }
2964
+
2965
+ getOptimisticResult(queries) {
2966
+ return this.findMatchingObservers(queries).map(match => match.observer.getOptimisticResult(match.defaultedQueryOptions));
2967
+ }
2968
+
2969
+ findMatchingObservers(queries) {
2970
+ const prevObservers = this.observers;
2971
+ const prevObserversMap = new Map(prevObservers.map(observer => [observer.options.queryHash, observer]));
2972
+ const defaultedQueryOptions = queries.map(options => this.client.defaultQueryOptions(options));
2973
+ const matchingObservers = defaultedQueryOptions.flatMap(defaultedOptions => {
2974
+ const match = prevObserversMap.get(defaultedOptions.queryHash);
2975
+
2976
+ if (match != null) {
2977
+ return [{
2978
+ defaultedQueryOptions: defaultedOptions,
2979
+ observer: match
2980
+ }];
2981
+ }
2982
+
2983
+ return [];
2984
+ });
2985
+ const matchedQueryHashes = new Set(matchingObservers.map(match => match.defaultedQueryOptions.queryHash));
2986
+ const unmatchedQueries = defaultedQueryOptions.filter(defaultedOptions => !matchedQueryHashes.has(defaultedOptions.queryHash));
2987
+ const matchingObserversSet = new Set(matchingObservers.map(match => match.observer));
2988
+ const unmatchedObservers = prevObservers.filter(prevObserver => !matchingObserversSet.has(prevObserver));
2989
+
2990
+ const getObserver = options => {
2991
+ const defaultedOptions = this.client.defaultQueryOptions(options);
2992
+ const currentObserver = this.observersMap[defaultedOptions.queryHash];
2993
+ return currentObserver != null ? currentObserver : new QueryObserver(this.client, defaultedOptions);
2994
+ };
2995
+
2996
+ const newOrReusedObservers = unmatchedQueries.map((options, index) => {
2997
+ if (options.keepPreviousData) {
2998
+ // return previous data from one of the observers that no longer match
2999
+ const previouslyUsedObserver = unmatchedObservers[index];
3000
+
3001
+ if (previouslyUsedObserver !== undefined) {
3002
+ return {
3003
+ defaultedQueryOptions: options,
3004
+ observer: previouslyUsedObserver
3005
+ };
3006
+ }
3007
+ }
3008
+
3009
+ return {
3010
+ defaultedQueryOptions: options,
3011
+ observer: getObserver(options)
3012
+ };
3013
+ });
3014
+
3015
+ const sortMatchesByOrderOfQueries = (a, b) => defaultedQueryOptions.indexOf(a.defaultedQueryOptions) - defaultedQueryOptions.indexOf(b.defaultedQueryOptions);
3016
+
3017
+ return matchingObservers.concat(newOrReusedObservers).sort(sortMatchesByOrderOfQueries);
3018
+ }
3019
+
3020
+ onUpdate(observer, result) {
3021
+ const index = this.observers.indexOf(observer);
3022
+
3023
+ if (index !== -1) {
3024
+ this.result = replaceAt(this.result, index, result);
3025
+ this.notify();
3026
+ }
3027
+ }
3028
+
3029
+ notify() {
3030
+ notifyManager.batch(() => {
3031
+ this.listeners.forEach(({
3032
+ listener
3033
+ }) => {
3034
+ listener(this.result);
3035
+ });
3036
+ });
3037
+ }
3038
+
3039
+ }
3040
+
3041
+ class InfiniteQueryObserver extends QueryObserver {
3042
+ // Type override
3043
+ // Type override
3044
+ // Type override
3045
+ // eslint-disable-next-line @typescript-eslint/no-useless-constructor
3046
+ constructor(client, options) {
3047
+ super(client, options);
3048
+ }
3049
+
3050
+ bindMethods() {
3051
+ super.bindMethods();
3052
+ this.fetchNextPage = this.fetchNextPage.bind(this);
3053
+ this.fetchPreviousPage = this.fetchPreviousPage.bind(this);
3054
+ }
3055
+
3056
+ setOptions(options, notifyOptions) {
3057
+ super.setOptions({ ...options,
3058
+ behavior: infiniteQueryBehavior()
3059
+ }, notifyOptions);
3060
+ }
3061
+
3062
+ getOptimisticResult(options) {
3063
+ options.behavior = infiniteQueryBehavior();
3064
+ return super.getOptimisticResult(options);
3065
+ }
3066
+
3067
+ fetchNextPage({
3068
+ pageParam,
3069
+ ...options
3070
+ } = {}) {
3071
+ return this.fetch({ ...options,
3072
+ meta: {
3073
+ fetchMore: {
3074
+ direction: 'forward',
3075
+ pageParam
3076
+ }
3077
+ }
3078
+ });
3079
+ }
3080
+
3081
+ fetchPreviousPage({
3082
+ pageParam,
3083
+ ...options
3084
+ } = {}) {
3085
+ return this.fetch({ ...options,
3086
+ meta: {
3087
+ fetchMore: {
3088
+ direction: 'backward',
3089
+ pageParam
3090
+ }
3091
+ }
3092
+ });
3093
+ }
3094
+
3095
+ createResult(query, options) {
3096
+ var _state$fetchMeta, _state$fetchMeta$fetc, _state$fetchMeta2, _state$fetchMeta2$fet, _state$data, _state$data2;
3097
+
3098
+ const {
3099
+ state
3100
+ } = query;
3101
+ const result = super.createResult(query, options);
3102
+ const {
3103
+ isFetching,
3104
+ isRefetching
3105
+ } = result;
3106
+ const isFetchingNextPage = isFetching && ((_state$fetchMeta = state.fetchMeta) == null ? void 0 : (_state$fetchMeta$fetc = _state$fetchMeta.fetchMore) == null ? void 0 : _state$fetchMeta$fetc.direction) === 'forward';
3107
+ const isFetchingPreviousPage = isFetching && ((_state$fetchMeta2 = state.fetchMeta) == null ? void 0 : (_state$fetchMeta2$fet = _state$fetchMeta2.fetchMore) == null ? void 0 : _state$fetchMeta2$fet.direction) === 'backward';
3108
+ return { ...result,
3109
+ fetchNextPage: this.fetchNextPage,
3110
+ fetchPreviousPage: this.fetchPreviousPage,
3111
+ hasNextPage: hasNextPage(options, (_state$data = state.data) == null ? void 0 : _state$data.pages),
3112
+ hasPreviousPage: hasPreviousPage(options, (_state$data2 = state.data) == null ? void 0 : _state$data2.pages),
3113
+ isFetchingNextPage,
3114
+ isFetchingPreviousPage,
3115
+ isRefetching: isRefetching && !isFetchingNextPage && !isFetchingPreviousPage
3116
+ };
3117
+ }
3118
+
3119
+ }
3120
+
3121
+ // CLASS
3122
+ class MutationObserver extends Subscribable {
3123
+ constructor(client, options) {
3124
+ super();
3125
+ this.client = client;
3126
+ this.setOptions(options);
3127
+ this.bindMethods();
3128
+ this.updateResult();
3129
+ }
3130
+
3131
+ bindMethods() {
3132
+ this.mutate = this.mutate.bind(this);
3133
+ this.reset = this.reset.bind(this);
3134
+ }
3135
+
3136
+ setOptions(options) {
3137
+ var _this$currentMutation;
3138
+
3139
+ const prevOptions = this.options;
3140
+ this.options = this.client.defaultMutationOptions(options);
3141
+
3142
+ if (!shallowEqualObjects(prevOptions, this.options)) {
3143
+ this.client.getMutationCache().notify({
3144
+ type: 'observerOptionsUpdated',
3145
+ mutation: this.currentMutation,
3146
+ observer: this
3147
+ });
3148
+ }
3149
+
3150
+ (_this$currentMutation = this.currentMutation) == null ? void 0 : _this$currentMutation.setOptions(this.options);
3151
+ }
3152
+
3153
+ onUnsubscribe() {
3154
+ if (!this.hasListeners()) {
3155
+ var _this$currentMutation2;
3156
+
3157
+ (_this$currentMutation2 = this.currentMutation) == null ? void 0 : _this$currentMutation2.removeObserver(this);
3158
+ }
3159
+ }
3160
+
3161
+ onMutationUpdate(action) {
3162
+ this.updateResult(); // Determine which callbacks to trigger
3163
+
3164
+ const notifyOptions = {
3165
+ listeners: true
3166
+ };
3167
+
3168
+ if (action.type === 'success') {
3169
+ notifyOptions.onSuccess = true;
3170
+ } else if (action.type === 'error') {
3171
+ notifyOptions.onError = true;
3172
+ }
3173
+
3174
+ this.notify(notifyOptions);
3175
+ }
3176
+
3177
+ getCurrentResult() {
3178
+ return this.currentResult;
3179
+ }
3180
+
3181
+ reset() {
3182
+ this.currentMutation = undefined;
3183
+ this.updateResult();
3184
+ this.notify({
3185
+ listeners: true
3186
+ });
3187
+ }
3188
+
3189
+ mutate(variables, options) {
3190
+ this.mutateOptions = options;
3191
+
3192
+ if (this.currentMutation) {
3193
+ this.currentMutation.removeObserver(this);
3194
+ }
3195
+
3196
+ this.currentMutation = this.client.getMutationCache().build(this.client, { ...this.options,
3197
+ variables: typeof variables !== 'undefined' ? variables : this.options.variables
3198
+ });
3199
+ this.currentMutation.addObserver(this);
3200
+ return this.currentMutation.execute();
3201
+ }
3202
+
3203
+ updateResult() {
3204
+ const state = this.currentMutation ? this.currentMutation.state : getDefaultState();
3205
+ const isLoading = state.status === 'loading';
3206
+ const result = { ...state,
3207
+ isLoading,
3208
+ isPending: isLoading,
3209
+ isSuccess: state.status === 'success',
3210
+ isError: state.status === 'error',
3211
+ isIdle: state.status === 'idle',
3212
+ mutate: this.mutate,
3213
+ reset: this.reset
3214
+ };
3215
+ this.currentResult = result;
3216
+ }
3217
+
3218
+ notify(options) {
3219
+ notifyManager.batch(() => {
3220
+ // First trigger the mutate callbacks
3221
+ if (this.mutateOptions && this.hasListeners()) {
3222
+ if (options.onSuccess) {
3223
+ var _this$mutateOptions$o, _this$mutateOptions, _this$mutateOptions$o2, _this$mutateOptions2;
3224
+
3225
+ (_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);
3226
+ (_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);
3227
+ } else if (options.onError) {
3228
+ var _this$mutateOptions$o3, _this$mutateOptions3, _this$mutateOptions$o4, _this$mutateOptions4;
3229
+
3230
+ (_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);
3231
+ (_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);
3232
+ }
3233
+ } // Then trigger the listeners
3234
+
3235
+
3236
+ if (options.listeners) {
3237
+ this.listeners.forEach(({
3238
+ listener
3239
+ }) => {
3240
+ listener(this.currentResult);
3241
+ });
3242
+ }
3243
+ });
3244
+ }
3245
+
3246
+ }
3247
+
3248
+ // TYPES
3249
+ // FUNCTIONS
3250
+ function dehydrateMutation(mutation) {
3251
+ return {
3252
+ mutationKey: mutation.options.mutationKey,
3253
+ state: mutation.state
3254
+ };
3255
+ } // Most config is not dehydrated but instead meant to configure again when
3256
+ // consuming the de/rehydrated data, typically with useQuery on the client.
3257
+ // Sometimes it might make sense to prefetch data on the server and include
3258
+ // in the html-payload, but not consume it on the initial render.
3259
+
3260
+
3261
+ function dehydrateQuery(query) {
3262
+ return {
3263
+ state: query.state,
3264
+ queryKey: query.queryKey,
3265
+ queryHash: query.queryHash
3266
+ };
3267
+ }
3268
+
3269
+ function defaultShouldDehydrateMutation(mutation) {
3270
+ return mutation.state.isPaused;
3271
+ }
3272
+ function defaultShouldDehydrateQuery(query) {
3273
+ return query.state.status === 'success';
3274
+ }
3275
+ function dehydrate(client, options = {}) {
3276
+ const mutations = [];
3277
+ const queries = [];
3278
+
3279
+ if (options.dehydrateMutations !== false) {
3280
+ const shouldDehydrateMutation = options.shouldDehydrateMutation || defaultShouldDehydrateMutation;
3281
+ client.getMutationCache().getAll().forEach(mutation => {
3282
+ if (shouldDehydrateMutation(mutation)) {
3283
+ mutations.push(dehydrateMutation(mutation));
3284
+ }
3285
+ });
3286
+ }
3287
+
3288
+ if (options.dehydrateQueries !== false) {
3289
+ const shouldDehydrateQuery = options.shouldDehydrateQuery || defaultShouldDehydrateQuery;
3290
+ client.getQueryCache().getAll().forEach(query => {
3291
+ if (shouldDehydrateQuery(query)) {
3292
+ queries.push(dehydrateQuery(query));
3293
+ }
3294
+ });
3295
+ }
3296
+
3297
+ return {
3298
+ mutations,
3299
+ queries
3300
+ };
3301
+ }
3302
+ function hydrate(client, dehydratedState, options) {
3303
+ if (typeof dehydratedState !== 'object' || dehydratedState === null) {
3304
+ return;
3305
+ }
3306
+
3307
+ const mutationCache = client.getMutationCache();
3308
+ const queryCache = client.getQueryCache(); // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3309
+
3310
+ const mutations = dehydratedState.mutations || []; // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
3311
+
3312
+ const queries = dehydratedState.queries || [];
3313
+ mutations.forEach(dehydratedMutation => {
3314
+ var _options$defaultOptio;
3315
+
3316
+ mutationCache.build(client, { ...(options == null ? void 0 : (_options$defaultOptio = options.defaultOptions) == null ? void 0 : _options$defaultOptio.mutations),
3317
+ mutationKey: dehydratedMutation.mutationKey
3318
+ }, dehydratedMutation.state);
3319
+ });
3320
+ queries.forEach(({
3321
+ queryKey,
3322
+ state,
3323
+ queryHash
3324
+ }) => {
3325
+ var _options$defaultOptio2;
3326
+
3327
+ const query = queryCache.get(queryHash); // Do not hydrate if an existing query exists with newer data
3328
+
3329
+ if (query) {
3330
+ if (query.state.dataUpdatedAt < state.dataUpdatedAt) {
3331
+ // omit fetchStatus from dehydrated state
3332
+ // so that query stays in its current fetchStatus
3333
+ const {
3334
+ fetchStatus: _ignored,
3335
+ ...dehydratedQueryState
3336
+ } = state;
3337
+ query.setState(dehydratedQueryState);
3338
+ }
3339
+
3340
+ return;
3341
+ } // Restore query
3342
+
3343
+
3344
+ queryCache.build(client, { ...(options == null ? void 0 : (_options$defaultOptio2 = options.defaultOptions) == null ? void 0 : _options$defaultOptio2.queries),
3345
+ queryKey,
3346
+ queryHash
3347
+ }, // Reset fetch status to idle to avoid
3348
+ // query being stuck in fetching state upon hydration
3349
+ { ...state,
3350
+ fetchStatus: 'idle'
3351
+ });
3352
+ });
3353
+ }
3354
+
3355
+ const unstable_batchedUpdates = ReactDOM__namespace.unstable_batchedUpdates;
3356
+
3357
+ notifyManager.setBatchNotifyFunction(unstable_batchedUpdates);
3358
+
3359
+ var shim = {exports: {}};
3360
+
3361
+ var useSyncExternalStoreShim_development = {};
3362
+
3363
+ /**
3364
+ * @license React
3365
+ * use-sync-external-store-shim.development.js
3366
+ *
3367
+ * Copyright (c) Facebook, Inc. and its affiliates.
3368
+ *
3369
+ * This source code is licensed under the MIT license found in the
3370
+ * LICENSE file in the root directory of this source tree.
3371
+ */
3372
+
3373
+ var hasRequiredUseSyncExternalStoreShim_development;
3374
+
3375
+ function requireUseSyncExternalStoreShim_development () {
3376
+ if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development;
3377
+ hasRequiredUseSyncExternalStoreShim_development = 1;
3378
+
3379
+ {
3380
+ (function() {
3381
+
3382
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
3383
+ if (
3384
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
3385
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart ===
3386
+ 'function'
3387
+ ) {
3388
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
3389
+ }
3390
+ var React = React__default["default"];
3391
+
3392
+ var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
3393
+
3394
+ function error(format) {
3395
+ {
3396
+ {
3397
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
3398
+ args[_key2 - 1] = arguments[_key2];
3399
+ }
3400
+
3401
+ printWarning('error', format, args);
3402
+ }
3403
+ }
3404
+ }
3405
+
3406
+ function printWarning(level, format, args) {
3407
+ // When changing this logic, you might want to also
3408
+ // update consoleWithStackDev.www.js as well.
3409
+ {
3410
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
3411
+ var stack = ReactDebugCurrentFrame.getStackAddendum();
3412
+
3413
+ if (stack !== '') {
3414
+ format += '%s';
3415
+ args = args.concat([stack]);
3416
+ } // eslint-disable-next-line react-internal/safe-string-coercion
3417
+
3418
+
3419
+ var argsWithFormat = args.map(function (item) {
3420
+ return String(item);
3421
+ }); // Careful: RN currently depends on this prefix
3422
+
3423
+ argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
3424
+ // breaks IE9: https://github.com/facebook/react/issues/13610
3425
+ // eslint-disable-next-line react-internal/no-production-logging
3426
+
3427
+ Function.prototype.apply.call(console[level], console, argsWithFormat);
3428
+ }
3429
+ }
3430
+
3431
+ /**
3432
+ * inlined Object.is polyfill to avoid requiring consumers ship their own
3433
+ * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
3434
+ */
3435
+ function is(x, y) {
3436
+ return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
3437
+ ;
3438
+ }
3439
+
3440
+ var objectIs = typeof Object.is === 'function' ? Object.is : is;
3441
+
3442
+ // dispatch for CommonJS interop named imports.
3443
+
3444
+ var useState = React.useState,
3445
+ useEffect = React.useEffect,
3446
+ useLayoutEffect = React.useLayoutEffect,
3447
+ useDebugValue = React.useDebugValue;
3448
+ var didWarnOld18Alpha = false;
3449
+ var didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
3450
+ // because of a very particular set of implementation details and assumptions
3451
+ // -- change any one of them and it will break. The most important assumption
3452
+ // is that updates are always synchronous, because concurrent rendering is
3453
+ // only available in versions of React that also have a built-in
3454
+ // useSyncExternalStore API. And we only use this shim when the built-in API
3455
+ // does not exist.
3456
+ //
3457
+ // Do not assume that the clever hacks used by this hook also work in general.
3458
+ // The point of this shim is to replace the need for hacks by other libraries.
3459
+
3460
+ function useSyncExternalStore(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of
3461
+ // React do not expose a way to check if we're hydrating. So users of the shim
3462
+ // will need to track that themselves and return the correct value
3463
+ // from `getSnapshot`.
3464
+ getServerSnapshot) {
3465
+ {
3466
+ if (!didWarnOld18Alpha) {
3467
+ if (React.startTransition !== undefined) {
3468
+ didWarnOld18Alpha = true;
3469
+
3470
+ error('You are using an outdated, pre-release alpha of React 18 that ' + 'does not support useSyncExternalStore. The ' + 'use-sync-external-store shim will not work correctly. Upgrade ' + 'to a newer pre-release.');
3471
+ }
3472
+ }
3473
+ } // Read the current snapshot from the store on every render. Again, this
3474
+ // breaks the rules of React, and only works here because of specific
3475
+ // implementation details, most importantly that updates are
3476
+ // always synchronous.
3477
+
3478
+
3479
+ var value = getSnapshot();
3480
+
3481
+ {
3482
+ if (!didWarnUncachedGetSnapshot) {
3483
+ var cachedValue = getSnapshot();
3484
+
3485
+ if (!objectIs(value, cachedValue)) {
3486
+ error('The result of getSnapshot should be cached to avoid an infinite loop');
3487
+
3488
+ didWarnUncachedGetSnapshot = true;
3489
+ }
3490
+ }
3491
+ } // Because updates are synchronous, we don't queue them. Instead we force a
3492
+ // re-render whenever the subscribed state changes by updating an some
3493
+ // arbitrary useState hook. Then, during render, we call getSnapshot to read
3494
+ // the current value.
3495
+ //
3496
+ // Because we don't actually use the state returned by the useState hook, we
3497
+ // can save a bit of memory by storing other stuff in that slot.
3498
+ //
3499
+ // To implement the early bailout, we need to track some things on a mutable
3500
+ // object. Usually, we would put that in a useRef hook, but we can stash it in
3501
+ // our useState hook instead.
3502
+ //
3503
+ // To force a re-render, we call forceUpdate({inst}). That works because the
3504
+ // new object always fails an equality check.
3505
+
3506
+
3507
+ var _useState = useState({
3508
+ inst: {
3509
+ value: value,
3510
+ getSnapshot: getSnapshot
3511
+ }
3512
+ }),
3513
+ inst = _useState[0].inst,
3514
+ forceUpdate = _useState[1]; // Track the latest getSnapshot function with a ref. This needs to be updated
3515
+ // in the layout phase so we can access it during the tearing check that
3516
+ // happens on subscribe.
3517
+
3518
+
3519
+ useLayoutEffect(function () {
3520
+ inst.value = value;
3521
+ inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
3522
+ // commit phase if there was an interleaved mutation. In concurrent mode
3523
+ // this can happen all the time, but even in synchronous mode, an earlier
3524
+ // effect may have mutated the store.
3525
+
3526
+ if (checkIfSnapshotChanged(inst)) {
3527
+ // Force a re-render.
3528
+ forceUpdate({
3529
+ inst: inst
3530
+ });
3531
+ }
3532
+ }, [subscribe, value, getSnapshot]);
3533
+ useEffect(function () {
3534
+ // Check for changes right before subscribing. Subsequent changes will be
3535
+ // detected in the subscription handler.
3536
+ if (checkIfSnapshotChanged(inst)) {
3537
+ // Force a re-render.
3538
+ forceUpdate({
3539
+ inst: inst
3540
+ });
3541
+ }
3542
+
3543
+ var handleStoreChange = function () {
3544
+ // TODO: Because there is no cross-renderer API for batching updates, it's
3545
+ // up to the consumer of this library to wrap their subscription event
3546
+ // with unstable_batchedUpdates. Should we try to detect when this isn't
3547
+ // the case and print a warning in development?
3548
+ // The store changed. Check if the snapshot changed since the last time we
3549
+ // read from the store.
3550
+ if (checkIfSnapshotChanged(inst)) {
3551
+ // Force a re-render.
3552
+ forceUpdate({
3553
+ inst: inst
3554
+ });
3555
+ }
3556
+ }; // Subscribe to the store and return a clean-up function.
3557
+
3558
+
3559
+ return subscribe(handleStoreChange);
3560
+ }, [subscribe]);
3561
+ useDebugValue(value);
3562
+ return value;
3563
+ }
3564
+
3565
+ function checkIfSnapshotChanged(inst) {
3566
+ var latestGetSnapshot = inst.getSnapshot;
3567
+ var prevValue = inst.value;
3568
+
3569
+ try {
3570
+ var nextValue = latestGetSnapshot();
3571
+ return !objectIs(prevValue, nextValue);
3572
+ } catch (error) {
3573
+ return true;
3574
+ }
3575
+ }
3576
+
3577
+ function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
3578
+ // Note: The shim does not use getServerSnapshot, because pre-18 versions of
3579
+ // React do not expose a way to check if we're hydrating. So users of the shim
3580
+ // will need to track that themselves and return the correct value
3581
+ // from `getSnapshot`.
3582
+ return getSnapshot();
3583
+ }
3584
+
3585
+ var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
3586
+
3587
+ var isServerEnvironment = !canUseDOM;
3588
+
3589
+ var shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore;
3590
+ var useSyncExternalStore$2 = React.useSyncExternalStore !== undefined ? React.useSyncExternalStore : shim;
3591
+
3592
+ useSyncExternalStoreShim_development.useSyncExternalStore = useSyncExternalStore$2;
3593
+ /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
3594
+ if (
3595
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
3596
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop ===
3597
+ 'function'
3598
+ ) {
3599
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error());
3600
+ }
3601
+
3602
+ })();
3603
+ }
3604
+ return useSyncExternalStoreShim_development;
3605
+ }
3606
+
3607
+ (function (module) {
3608
+
3609
+ {
3610
+ module.exports = requireUseSyncExternalStoreShim_development();
3611
+ }
3612
+ } (shim));
3613
+
3614
+ const useSyncExternalStore = shim.exports.useSyncExternalStore;
3615
+
3616
+ const defaultContext = /*#__PURE__*/React__namespace.createContext(undefined);
3617
+ const QueryClientSharingContext = /*#__PURE__*/React__namespace.createContext(false); // If we are given a context, we will use it.
3618
+ // Otherwise, if contextSharing is on, we share the first and at least one
3619
+ // instance of the context across the window
3620
+ // to ensure that if React Query is used across
3621
+ // different bundles or microfrontends they will
3622
+ // all use the same **instance** of context, regardless
3623
+ // of module scoping.
3624
+
3625
+ function getQueryClientContext(context, contextSharing) {
3626
+ if (context) {
3627
+ return context;
3628
+ }
3629
+
3630
+ if (contextSharing && typeof window !== 'undefined') {
3631
+ if (!window.ReactQueryClientContext) {
3632
+ window.ReactQueryClientContext = defaultContext;
3633
+ }
3634
+
3635
+ return window.ReactQueryClientContext;
3636
+ }
3637
+
3638
+ return defaultContext;
3639
+ }
3640
+
3641
+ const useQueryClient = ({
3642
+ context
3643
+ } = {}) => {
3644
+ const queryClient = React__namespace.useContext(getQueryClientContext(context, React__namespace.useContext(QueryClientSharingContext)));
3645
+
3646
+ if (!queryClient) {
3647
+ throw new Error('No QueryClient set, use QueryClientProvider to set one');
3648
+ }
3649
+
3650
+ return queryClient;
3651
+ };
3652
+ const QueryClientProvider = ({
3653
+ client,
3654
+ children,
3655
+ context,
3656
+ contextSharing = false
3657
+ }) => {
3658
+ React__namespace.useEffect(() => {
3659
+ client.mount();
3660
+ return () => {
3661
+ client.unmount();
3662
+ };
3663
+ }, [client]);
3664
+
3665
+ if (contextSharing) {
3666
+ client.getLogger().error("The contextSharing option has been deprecated and will be removed in the next major version");
3667
+ }
3668
+
3669
+ const Context = getQueryClientContext(context, contextSharing);
3670
+ return /*#__PURE__*/React__namespace.createElement(QueryClientSharingContext.Provider, {
3671
+ value: !context && contextSharing
3672
+ }, /*#__PURE__*/React__namespace.createElement(Context.Provider, {
3673
+ value: client
3674
+ }, children));
3675
+ };
3676
+
3677
+ const IsRestoringContext = /*#__PURE__*/React__namespace.createContext(false);
3678
+ const useIsRestoring = () => React__namespace.useContext(IsRestoringContext);
3679
+ const IsRestoringProvider = IsRestoringContext.Provider;
3680
+
3681
+ function createValue() {
3682
+ let isReset = false;
3683
+ return {
3684
+ clearReset: () => {
3685
+ isReset = false;
3686
+ },
3687
+ reset: () => {
3688
+ isReset = true;
3689
+ },
3690
+ isReset: () => {
3691
+ return isReset;
3692
+ }
3693
+ };
3694
+ }
3695
+
3696
+ const QueryErrorResetBoundaryContext = /*#__PURE__*/React__namespace.createContext(createValue()); // HOOK
3697
+
3698
+ const useQueryErrorResetBoundary = () => React__namespace.useContext(QueryErrorResetBoundaryContext); // COMPONENT
3699
+
3700
+ const QueryErrorResetBoundary = ({
3701
+ children
3702
+ }) => {
3703
+ const [value] = React__namespace.useState(() => createValue());
3704
+ return /*#__PURE__*/React__namespace.createElement(QueryErrorResetBoundaryContext.Provider, {
3705
+ value: value
3706
+ }, typeof children === 'function' ? children(value) : children);
3707
+ };
3708
+
3709
+ function shouldThrowError(_useErrorBoundary, params) {
3710
+ // Allow useErrorBoundary function to override throwing behavior on a per-error basis
3711
+ if (typeof _useErrorBoundary === 'function') {
3712
+ return _useErrorBoundary(...params);
3713
+ }
3714
+
3715
+ return !!_useErrorBoundary;
3716
+ }
3717
+
3718
+ const ensurePreventErrorBoundaryRetry = (options, errorResetBoundary) => {
3719
+ if (options.suspense || options.useErrorBoundary) {
3720
+ // Prevent retrying failed query if the error boundary has not been reset yet
3721
+ if (!errorResetBoundary.isReset()) {
3722
+ options.retryOnMount = false;
3723
+ }
3724
+ }
3725
+ };
3726
+ const useClearResetErrorBoundary = errorResetBoundary => {
3727
+ React__namespace.useEffect(() => {
3728
+ errorResetBoundary.clearReset();
3729
+ }, [errorResetBoundary]);
3730
+ };
3731
+ const getHasError = ({
3732
+ result,
3733
+ errorResetBoundary,
3734
+ useErrorBoundary,
3735
+ query
3736
+ }) => {
3737
+ return result.isError && !errorResetBoundary.isReset() && !result.isFetching && shouldThrowError(useErrorBoundary, [result.error, query]);
3738
+ };
3739
+
3740
+ const ensureStaleTime = defaultedOptions => {
3741
+ if (defaultedOptions.suspense) {
3742
+ // Always set stale time when using suspense to prevent
3743
+ // fetching again when directly mounting after suspending
3744
+ if (typeof defaultedOptions.staleTime !== 'number') {
3745
+ defaultedOptions.staleTime = 1000;
3746
+ }
3747
+ }
3748
+ };
3749
+ const willFetch = (result, isRestoring) => result.isLoading && result.isFetching && !isRestoring;
3750
+ const shouldSuspend = (defaultedOptions, result, isRestoring) => (defaultedOptions == null ? void 0 : defaultedOptions.suspense) && willFetch(result, isRestoring);
3751
+ const fetchOptimistic = (defaultedOptions, observer, errorResetBoundary) => observer.fetchOptimistic(defaultedOptions).then(({
3752
+ data
3753
+ }) => {
3754
+ defaultedOptions.onSuccess == null ? void 0 : defaultedOptions.onSuccess(data);
3755
+ defaultedOptions.onSettled == null ? void 0 : defaultedOptions.onSettled(data, null);
3756
+ }).catch(error => {
3757
+ errorResetBoundary.clearReset();
3758
+ defaultedOptions.onError == null ? void 0 : defaultedOptions.onError(error);
3759
+ defaultedOptions.onSettled == null ? void 0 : defaultedOptions.onSettled(undefined, error);
3760
+ });
3761
+
3762
+ function useQueries({
3763
+ queries,
3764
+ context
3765
+ }) {
3766
+ const queryClient = useQueryClient({
3767
+ context
3768
+ });
3769
+ const isRestoring = useIsRestoring();
3770
+ const errorResetBoundary = useQueryErrorResetBoundary();
3771
+ const defaultedQueries = React__namespace.useMemo(() => queries.map(options => {
3772
+ const defaultedOptions = queryClient.defaultQueryOptions(options); // Make sure the results are already in fetching state before subscribing or updating options
3773
+
3774
+ defaultedOptions._optimisticResults = isRestoring ? 'isRestoring' : 'optimistic';
3775
+ return defaultedOptions;
3776
+ }), [queries, queryClient, isRestoring]);
3777
+ defaultedQueries.forEach(query => {
3778
+ ensureStaleTime(query);
3779
+ ensurePreventErrorBoundaryRetry(query, errorResetBoundary);
3780
+ });
3781
+ useClearResetErrorBoundary(errorResetBoundary);
3782
+ const [observer] = React__namespace.useState(() => new QueriesObserver(queryClient, defaultedQueries));
3783
+ const optimisticResult = observer.getOptimisticResult(defaultedQueries);
3784
+ useSyncExternalStore(React__namespace.useCallback(onStoreChange => isRestoring ? () => undefined : observer.subscribe(notifyManager.batchCalls(onStoreChange)), [observer, isRestoring]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
3785
+ React__namespace.useEffect(() => {
3786
+ // Do not notify on updates because of changes in the options because
3787
+ // these changes should already be reflected in the optimistic result.
3788
+ observer.setQueries(defaultedQueries, {
3789
+ listeners: false
3790
+ });
3791
+ }, [defaultedQueries, observer]);
3792
+ const shouldAtLeastOneSuspend = optimisticResult.some((result, index) => shouldSuspend(defaultedQueries[index], result, isRestoring));
3793
+ const suspensePromises = shouldAtLeastOneSuspend ? optimisticResult.flatMap((result, index) => {
3794
+ const options = defaultedQueries[index];
3795
+ const queryObserver = observer.getObservers()[index];
3796
+
3797
+ if (options && queryObserver) {
3798
+ if (shouldSuspend(options, result, isRestoring)) {
3799
+ return fetchOptimistic(options, queryObserver, errorResetBoundary);
3800
+ } else if (willFetch(result, isRestoring)) {
3801
+ void fetchOptimistic(options, queryObserver, errorResetBoundary);
3802
+ }
3803
+ }
3804
+
3805
+ return [];
3806
+ }) : [];
3807
+
3808
+ if (suspensePromises.length > 0) {
3809
+ throw Promise.all(suspensePromises);
3810
+ }
3811
+
3812
+ const observerQueries = observer.getQueries();
3813
+ const firstSingleResultWhichShouldThrow = optimisticResult.find((result, index) => {
3814
+ var _defaultedQueries$ind, _defaultedQueries$ind2;
3815
+
3816
+ return getHasError({
3817
+ result,
3818
+ errorResetBoundary,
3819
+ useErrorBoundary: (_defaultedQueries$ind = (_defaultedQueries$ind2 = defaultedQueries[index]) == null ? void 0 : _defaultedQueries$ind2.useErrorBoundary) != null ? _defaultedQueries$ind : false,
3820
+ query: observerQueries[index]
3821
+ });
3822
+ });
3823
+
3824
+ if (firstSingleResultWhichShouldThrow != null && firstSingleResultWhichShouldThrow.error) {
3825
+ throw firstSingleResultWhichShouldThrow.error;
3826
+ }
3827
+
3828
+ return optimisticResult;
3829
+ }
3830
+
3831
+ function useBaseQuery(options, Observer) {
3832
+ const queryClient = useQueryClient({
3833
+ context: options.context
3834
+ });
3835
+ const isRestoring = useIsRestoring();
3836
+ const errorResetBoundary = useQueryErrorResetBoundary();
3837
+ const defaultedOptions = queryClient.defaultQueryOptions(options); // Make sure results are optimistically set in fetching state before subscribing or updating options
3838
+
3839
+ defaultedOptions._optimisticResults = isRestoring ? 'isRestoring' : 'optimistic'; // Include callbacks in batch renders
3840
+
3841
+ if (defaultedOptions.onError) {
3842
+ defaultedOptions.onError = notifyManager.batchCalls(defaultedOptions.onError);
3843
+ }
3844
+
3845
+ if (defaultedOptions.onSuccess) {
3846
+ defaultedOptions.onSuccess = notifyManager.batchCalls(defaultedOptions.onSuccess);
3847
+ }
3848
+
3849
+ if (defaultedOptions.onSettled) {
3850
+ defaultedOptions.onSettled = notifyManager.batchCalls(defaultedOptions.onSettled);
3851
+ }
3852
+
3853
+ ensureStaleTime(defaultedOptions);
3854
+ ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary);
3855
+ useClearResetErrorBoundary(errorResetBoundary);
3856
+ const [observer] = React__namespace.useState(() => new Observer(queryClient, defaultedOptions));
3857
+ const result = observer.getOptimisticResult(defaultedOptions);
3858
+ useSyncExternalStore(React__namespace.useCallback(onStoreChange => {
3859
+ const unsubscribe = isRestoring ? () => undefined : observer.subscribe(notifyManager.batchCalls(onStoreChange)); // Update result to make sure we did not miss any query updates
3860
+ // between creating the observer and subscribing to it.
3861
+
3862
+ observer.updateResult();
3863
+ return unsubscribe;
3864
+ }, [observer, isRestoring]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
3865
+ React__namespace.useEffect(() => {
3866
+ // Do not notify on updates because of changes in the options because
3867
+ // these changes should already be reflected in the optimistic result.
3868
+ observer.setOptions(defaultedOptions, {
3869
+ listeners: false
3870
+ });
3871
+ }, [defaultedOptions, observer]); // Handle suspense
3872
+
3873
+ if (shouldSuspend(defaultedOptions, result, isRestoring)) {
3874
+ throw fetchOptimistic(defaultedOptions, observer, errorResetBoundary);
3875
+ } // Handle error boundary
3876
+
3877
+
3878
+ if (getHasError({
3879
+ result,
3880
+ errorResetBoundary,
3881
+ useErrorBoundary: defaultedOptions.useErrorBoundary,
3882
+ query: observer.getCurrentQuery()
3883
+ })) {
3884
+ throw result.error;
3885
+ } // Handle result property usage tracking
3886
+
3887
+
3888
+ return !defaultedOptions.notifyOnChangeProps ? observer.trackResult(result) : result;
3889
+ }
3890
+
3891
+ /** @deprecated */
3892
+ function useQuery(arg1, arg2, arg3) {
3893
+ const parsedOptions = parseQueryArgs(arg1, arg2, arg3);
3894
+ return useBaseQuery(parsedOptions, QueryObserver);
3895
+ }
3896
+
3897
+ function useSuspenseQuery(options) {
3898
+ return useBaseQuery({ ...options,
3899
+ enabled: true,
3900
+ useErrorBoundary: true,
3901
+ suspense: true,
3902
+ placeholderData: undefined,
3903
+ networkMode: 'always'
3904
+ }, QueryObserver);
3905
+ }
3906
+
3907
+ function useSuspenseQueries({
3908
+ queries,
3909
+ context
3910
+ }) {
3911
+ return useQueries({
3912
+ queries: queries.map(query => ({ ...query,
3913
+ enabled: true,
3914
+ useErrorBoundary: true,
3915
+ suspense: true,
3916
+ placeholderData: undefined,
3917
+ networkMode: 'always'
3918
+ })),
3919
+ context
3920
+ });
3921
+ }
3922
+
3923
+ function useHydrate(state, options = {}) {
3924
+ const queryClient = useQueryClient({
3925
+ context: options.context
3926
+ });
3927
+ const optionsRef = React__namespace.useRef(options);
3928
+ optionsRef.current = options; // Running hydrate again with the same queries is safe,
3929
+ // it wont overwrite or initialize existing queries,
3930
+ // relying on useMemo here is only a performance optimization.
3931
+ // hydrate can and should be run *during* render here for SSR to work properly
3932
+
3933
+ React__namespace.useMemo(() => {
3934
+ if (state) {
3935
+ hydrate(queryClient, state, optionsRef.current);
3936
+ }
3937
+ }, [queryClient, state]);
3938
+ }
3939
+ const Hydrate = ({
3940
+ children,
3941
+ options,
3942
+ state
3943
+ }) => {
3944
+ useHydrate(state, options);
3945
+ return children;
3946
+ };
3947
+
3948
+ function useIsFetching(arg1, arg2, arg3) {
3949
+ const [filters, options = {}] = parseFilterArgs(arg1, arg2, arg3);
3950
+ const queryClient = useQueryClient({
3951
+ context: options.context
3952
+ });
3953
+ const queryCache = queryClient.getQueryCache();
3954
+ return useSyncExternalStore(React__namespace.useCallback(onStoreChange => queryCache.subscribe(notifyManager.batchCalls(onStoreChange)), [queryCache]), () => queryClient.isFetching(filters), () => queryClient.isFetching(filters));
3955
+ }
3956
+
3957
+ function useIsMutating(arg1, arg2, arg3) {
3958
+ const [filters, options = {}] = parseMutationFilterArgs(arg1, arg2, arg3);
3959
+ const queryClient = useQueryClient({
3960
+ context: options.context
3961
+ });
3962
+ const mutationCache = queryClient.getMutationCache();
3963
+ return useSyncExternalStore(React__namespace.useCallback(onStoreChange => mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)), [mutationCache]), () => queryClient.isMutating(filters), () => queryClient.isMutating(filters));
3964
+ }
3965
+
3966
+ function useMutation(arg1, arg2, arg3) {
3967
+ const options = parseMutationArgs(arg1, arg2, arg3);
3968
+ const queryClient = useQueryClient({
3969
+ context: options.context
3970
+ });
3971
+ const [observer] = React__namespace.useState(() => new MutationObserver(queryClient, options));
3972
+ React__namespace.useEffect(() => {
3973
+ observer.setOptions(options);
3974
+ }, [observer, options]);
3975
+ const result = useSyncExternalStore(React__namespace.useCallback(onStoreChange => observer.subscribe(notifyManager.batchCalls(onStoreChange)), [observer]), () => observer.getCurrentResult(), () => observer.getCurrentResult());
3976
+ const mutate = React__namespace.useCallback((variables, mutateOptions) => {
3977
+ observer.mutate(variables, mutateOptions).catch(noop);
3978
+ }, [observer]);
3979
+
3980
+ if (result.error && shouldThrowError(observer.options.useErrorBoundary, [result.error])) {
3981
+ throw result.error;
3982
+ }
3983
+
3984
+ return { ...result,
3985
+ mutate,
3986
+ mutateAsync: result.mutate
3987
+ };
3988
+ } // eslint-disable-next-line @typescript-eslint/no-empty-function
3989
+
3990
+ function noop() {}
3991
+
3992
+ function useInfiniteQuery(arg1, arg2, arg3) {
3993
+ const options = parseQueryArgs(arg1, arg2, arg3);
3994
+ return useBaseQuery(options, InfiniteQueryObserver);
3995
+ }
3996
+
3997
+ function queryOptions(options) {
3998
+ return options;
3999
+ }
4000
+
4001
+ exports.CancelledError = CancelledError;
4002
+ exports.Hydrate = Hydrate;
4003
+ exports.InfiniteQueryObserver = InfiniteQueryObserver;
4004
+ exports.IsRestoringProvider = IsRestoringProvider;
4005
+ exports.MutationCache = MutationCache;
4006
+ exports.MutationObserver = MutationObserver;
4007
+ exports.QueriesObserver = QueriesObserver;
4008
+ exports.Query = Query;
4009
+ exports.QueryCache = QueryCache;
4010
+ exports.QueryClient = QueryClient;
4011
+ exports.QueryClientProvider = QueryClientProvider;
4012
+ exports.QueryErrorResetBoundary = QueryErrorResetBoundary;
4013
+ exports.QueryObserver = QueryObserver;
4014
+ exports.defaultContext = defaultContext;
4015
+ exports.defaultShouldDehydrateMutation = defaultShouldDehydrateMutation;
4016
+ exports.defaultShouldDehydrateQuery = defaultShouldDehydrateQuery;
4017
+ exports.dehydrate = dehydrate;
4018
+ exports.focusManager = focusManager;
4019
+ exports.hashQueryKey = hashQueryKey;
4020
+ exports.hydrate = hydrate;
4021
+ exports.isCancelledError = isCancelledError;
4022
+ exports.isError = isError;
4023
+ exports.isServer = isServer;
4024
+ exports.matchQuery = matchQuery;
4025
+ exports.notifyManager = notifyManager;
4026
+ exports.onlineManager = onlineManager;
4027
+ exports.parseFilterArgs = parseFilterArgs;
4028
+ exports.parseMutationArgs = parseMutationArgs;
4029
+ exports.parseMutationFilterArgs = parseMutationFilterArgs;
4030
+ exports.parseQueryArgs = parseQueryArgs;
4031
+ exports.queryOptions = queryOptions;
4032
+ exports.replaceEqualDeep = replaceEqualDeep;
4033
+ exports.useHydrate = useHydrate;
4034
+ exports.useInfiniteQuery = useInfiniteQuery;
4035
+ exports.useIsFetching = useIsFetching;
4036
+ exports.useIsMutating = useIsMutating;
4037
+ exports.useIsRestoring = useIsRestoring;
4038
+ exports.useMutation = useMutation;
4039
+ exports.useQueries = useQueries;
4040
+ exports.useQuery = useQuery;
4041
+ exports.useQueryClient = useQueryClient;
4042
+ exports.useQueryErrorResetBoundary = useQueryErrorResetBoundary;
4043
+ exports.useSuspenseQueries = useSuspenseQueries;
4044
+ exports.useSuspenseQuery = useSuspenseQuery;
4045
+
4046
+ Object.defineProperty(exports, '__esModule', { value: true });
4047
+
4048
+ }));
4049
+ //# sourceMappingURL=index.development.js.map