@tanstack/solid-query 4.24.10 → 5.0.0-alpha.1

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