@tanstack/react-query 4.0.5

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