@tanstack/react-query 4.24.9 → 5.0.0-alpha.0

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