@depup/reduxjs__toolkit 2.12.0-depup.28

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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -0
  3. package/changes.json +18 -0
  4. package/dist/cjs/index.js +6 -0
  5. package/dist/cjs/redux-toolkit.development.cjs +2406 -0
  6. package/dist/cjs/redux-toolkit.development.cjs.map +1 -0
  7. package/dist/cjs/redux-toolkit.production.min.cjs +3 -0
  8. package/dist/cjs/redux-toolkit.production.min.cjs.map +1 -0
  9. package/dist/index.d.mts +2665 -0
  10. package/dist/index.d.ts +2665 -0
  11. package/dist/query/cjs/index.js +6 -0
  12. package/dist/query/cjs/rtk-query.development.cjs +3092 -0
  13. package/dist/query/cjs/rtk-query.development.cjs.map +1 -0
  14. package/dist/query/cjs/rtk-query.production.min.cjs +2 -0
  15. package/dist/query/cjs/rtk-query.production.min.cjs.map +1 -0
  16. package/dist/query/index.d.mts +3066 -0
  17. package/dist/query/index.d.ts +3066 -0
  18. package/dist/query/react/cjs/index.js +6 -0
  19. package/dist/query/react/cjs/rtk-query-react.development.cjs +748 -0
  20. package/dist/query/react/cjs/rtk-query-react.development.cjs.map +1 -0
  21. package/dist/query/react/cjs/rtk-query-react.production.min.cjs +2 -0
  22. package/dist/query/react/cjs/rtk-query-react.production.min.cjs.map +1 -0
  23. package/dist/query/react/index.d.mts +1009 -0
  24. package/dist/query/react/index.d.ts +1009 -0
  25. package/dist/query/react/rtk-query-react.browser.mjs +2 -0
  26. package/dist/query/react/rtk-query-react.browser.mjs.map +1 -0
  27. package/dist/query/react/rtk-query-react.legacy-esm.js +740 -0
  28. package/dist/query/react/rtk-query-react.legacy-esm.js.map +1 -0
  29. package/dist/query/react/rtk-query-react.modern.mjs +705 -0
  30. package/dist/query/react/rtk-query-react.modern.mjs.map +1 -0
  31. package/dist/query/rtk-query.browser.mjs +2 -0
  32. package/dist/query/rtk-query.browser.mjs.map +1 -0
  33. package/dist/query/rtk-query.legacy-esm.js +3117 -0
  34. package/dist/query/rtk-query.legacy-esm.js.map +1 -0
  35. package/dist/query/rtk-query.modern.mjs +3052 -0
  36. package/dist/query/rtk-query.modern.mjs.map +1 -0
  37. package/dist/react/cjs/index.js +6 -0
  38. package/dist/react/cjs/redux-toolkit-react.development.cjs +55 -0
  39. package/dist/react/cjs/redux-toolkit-react.development.cjs.map +1 -0
  40. package/dist/react/cjs/redux-toolkit-react.production.min.cjs +2 -0
  41. package/dist/react/cjs/redux-toolkit-react.production.min.cjs.map +1 -0
  42. package/dist/react/index.d.mts +22 -0
  43. package/dist/react/index.d.ts +22 -0
  44. package/dist/react/redux-toolkit-react.browser.mjs +2 -0
  45. package/dist/react/redux-toolkit-react.browser.mjs.map +1 -0
  46. package/dist/react/redux-toolkit-react.legacy-esm.js +47 -0
  47. package/dist/react/redux-toolkit-react.legacy-esm.js.map +1 -0
  48. package/dist/react/redux-toolkit-react.modern.mjs +28 -0
  49. package/dist/react/redux-toolkit-react.modern.mjs.map +1 -0
  50. package/dist/redux-toolkit.browser.mjs +3 -0
  51. package/dist/redux-toolkit.browser.mjs.map +1 -0
  52. package/dist/redux-toolkit.legacy-esm.js +2351 -0
  53. package/dist/redux-toolkit.legacy-esm.js.map +1 -0
  54. package/dist/redux-toolkit.modern.mjs +2330 -0
  55. package/dist/redux-toolkit.modern.mjs.map +1 -0
  56. package/dist/uncheckedindexed.ts +16 -0
  57. package/package.json +310 -0
  58. package/query/package.json +13 -0
  59. package/query/react/package.json +13 -0
  60. package/react/package.json +13 -0
  61. package/skills/build-modern-redux-apps/modern-redux/SKILL.md +304 -0
  62. package/skills/build-modern-redux-apps/modern-redux/references/store-lifetime.md +53 -0
  63. package/skills/build-modern-redux-apps/redux-dataflow/SKILL.md +264 -0
  64. package/skills/evolve-and-diagnose-redux-apps/debug-redux-toolkit-apps/SKILL.md +269 -0
  65. package/skills/evolve-and-diagnose-redux-apps/migrate-to-modern-redux/SKILL.md +226 -0
  66. package/skills/manage-server-data/adopt-rtk-query/SKILL.md +385 -0
  67. package/skills/manage-server-data/adopt-rtk-query/references/endpoint-lifecycle.md +36 -0
  68. package/skills/model-redux-state/build-slices-and-selectors/SKILL.md +364 -0
  69. package/skills/model-redux-state/build-slices-and-selectors/references/slice-patterns.md +59 -0
  70. package/skills/model-redux-state/design-state-ownership/SKILL.md +322 -0
  71. package/skills/model-redux-state/design-state-ownership/references/state-ownership.md +28 -0
  72. package/skills/orchestrate-side-effects/handle-side-effects/SKILL.md +271 -0
  73. package/skills/orchestrate-side-effects/handle-side-effects/references/listener-workflows.md +34 -0
  74. package/src/actionCreatorInvariantMiddleware.ts +34 -0
  75. package/src/autoBatchEnhancer.ts +146 -0
  76. package/src/combineSlices.ts +487 -0
  77. package/src/configureStore.ts +248 -0
  78. package/src/createAction.ts +324 -0
  79. package/src/createAsyncThunk.ts +791 -0
  80. package/src/createDraftSafeSelector.ts +30 -0
  81. package/src/createReducer.ts +217 -0
  82. package/src/createSlice.ts +1079 -0
  83. package/src/devtoolsExtension.ts +241 -0
  84. package/src/dynamicMiddleware/index.ts +93 -0
  85. package/src/dynamicMiddleware/react/index.ts +101 -0
  86. package/src/dynamicMiddleware/types.ts +82 -0
  87. package/src/entities/create_adapter.ts +47 -0
  88. package/src/entities/entity_state.ts +38 -0
  89. package/src/entities/index.ts +8 -0
  90. package/src/entities/models.ts +198 -0
  91. package/src/entities/sorted_state_adapter.ts +266 -0
  92. package/src/entities/state_adapter.ts +58 -0
  93. package/src/entities/state_selectors.ts +73 -0
  94. package/src/entities/unsorted_state_adapter.ts +204 -0
  95. package/src/entities/utils.ts +68 -0
  96. package/src/formatProdErrorMessage.ts +13 -0
  97. package/src/getDefaultEnhancers.ts +31 -0
  98. package/src/getDefaultMiddleware.ts +113 -0
  99. package/src/immerImports.ts +7 -0
  100. package/src/immutableStateInvariantMiddleware.ts +274 -0
  101. package/src/index.ts +213 -0
  102. package/src/listenerMiddleware/exceptions.ts +20 -0
  103. package/src/listenerMiddleware/index.ts +562 -0
  104. package/src/listenerMiddleware/task.ts +100 -0
  105. package/src/listenerMiddleware/types.ts +886 -0
  106. package/src/listenerMiddleware/utils.ts +30 -0
  107. package/src/mapBuilders.ts +298 -0
  108. package/src/matchers.ts +365 -0
  109. package/src/nanoid.ts +20 -0
  110. package/src/query/HandledError.ts +6 -0
  111. package/src/query/apiTypes.ts +120 -0
  112. package/src/query/baseQueryTypes.ts +101 -0
  113. package/src/query/core/apiState.ts +377 -0
  114. package/src/query/core/buildInitiate.ts +596 -0
  115. package/src/query/core/buildMiddleware/batchActions.ts +207 -0
  116. package/src/query/core/buildMiddleware/cacheCollection.ts +204 -0
  117. package/src/query/core/buildMiddleware/cacheLifecycle.ts +379 -0
  118. package/src/query/core/buildMiddleware/devMiddleware.ts +34 -0
  119. package/src/query/core/buildMiddleware/index.ts +162 -0
  120. package/src/query/core/buildMiddleware/invalidationByTags.ts +139 -0
  121. package/src/query/core/buildMiddleware/polling.ts +187 -0
  122. package/src/query/core/buildMiddleware/queryLifecycle.ts +508 -0
  123. package/src/query/core/buildMiddleware/types.ts +173 -0
  124. package/src/query/core/buildMiddleware/windowEventHandling.ts +64 -0
  125. package/src/query/core/buildSelectors.ts +413 -0
  126. package/src/query/core/buildSlice.ts +735 -0
  127. package/src/query/core/buildThunks.ts +1124 -0
  128. package/src/query/core/index.ts +58 -0
  129. package/src/query/core/module.ts +727 -0
  130. package/src/query/core/rtkImports.ts +24 -0
  131. package/src/query/core/setupListeners.ts +118 -0
  132. package/src/query/createApi.ts +506 -0
  133. package/src/query/defaultSerializeQueryArgs.ts +52 -0
  134. package/src/query/endpointDefinitions.ts +1717 -0
  135. package/src/query/fakeBaseQuery.ts +21 -0
  136. package/src/query/fetchBaseQuery.ts +385 -0
  137. package/src/query/index.ts +105 -0
  138. package/src/query/react/ApiProvider.tsx +69 -0
  139. package/src/query/react/buildHooks.ts +2297 -0
  140. package/src/query/react/constants.ts +2 -0
  141. package/src/query/react/index.ts +45 -0
  142. package/src/query/react/module.ts +275 -0
  143. package/src/query/react/namedHooks.ts +59 -0
  144. package/src/query/react/reactImports.ts +10 -0
  145. package/src/query/react/reactReduxImports.ts +1 -0
  146. package/src/query/react/rtkqImports.ts +8 -0
  147. package/src/query/react/useSerializedStableValue.ts +17 -0
  148. package/src/query/react/useShallowStableValue.ts +13 -0
  149. package/src/query/retry.ts +233 -0
  150. package/src/query/standardSchema.ts +35 -0
  151. package/src/query/tsHelpers.ts +48 -0
  152. package/src/query/utils/capitalize.ts +3 -0
  153. package/src/query/utils/copyWithStructuralSharing.ts +27 -0
  154. package/src/query/utils/countObjectKeys.ts +14 -0
  155. package/src/query/utils/filterMap.ts +27 -0
  156. package/src/query/utils/getCurrent.ts +6 -0
  157. package/src/query/utils/getOrInsert.ts +41 -0
  158. package/src/query/utils/immerImports.ts +9 -0
  159. package/src/query/utils/index.ts +11 -0
  160. package/src/query/utils/isAbsoluteUrl.ts +9 -0
  161. package/src/query/utils/isDocumentVisible.ts +12 -0
  162. package/src/query/utils/isNotNullish.ts +7 -0
  163. package/src/query/utils/isOnline.ts +12 -0
  164. package/src/query/utils/isValidUrl.ts +9 -0
  165. package/src/query/utils/joinUrls.ts +26 -0
  166. package/src/query/utils/signals.ts +33 -0
  167. package/src/react/index.ts +7 -0
  168. package/src/reduxImports.ts +8 -0
  169. package/src/reselectImports.ts +1 -0
  170. package/src/serializableStateInvariantMiddleware.ts +285 -0
  171. package/src/tsHelpers.ts +214 -0
  172. package/src/uncheckedindexed.ts +16 -0
  173. package/src/utils.ts +125 -0
@@ -0,0 +1,3092 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/query/index.ts
21
+ var query_exports = {};
22
+ __export(query_exports, {
23
+ NamedSchemaError: () => NamedSchemaError,
24
+ QueryStatus: () => QueryStatus,
25
+ _NEVER: () => _NEVER,
26
+ buildCreateApi: () => buildCreateApi,
27
+ copyWithStructuralSharing: () => copyWithStructuralSharing,
28
+ coreModule: () => coreModule,
29
+ coreModuleName: () => coreModuleName,
30
+ createApi: () => createApi,
31
+ defaultSerializeQueryArgs: () => defaultSerializeQueryArgs,
32
+ fakeBaseQuery: () => fakeBaseQuery,
33
+ fetchBaseQuery: () => fetchBaseQuery,
34
+ retry: () => retry,
35
+ setupListeners: () => setupListeners,
36
+ skipToken: () => skipToken
37
+ });
38
+ module.exports = __toCommonJS(query_exports);
39
+
40
+ // src/query/core/apiState.ts
41
+ var QueryStatus = /* @__PURE__ */ ((QueryStatus7) => {
42
+ QueryStatus7["uninitialized"] = "uninitialized";
43
+ QueryStatus7["pending"] = "pending";
44
+ QueryStatus7["fulfilled"] = "fulfilled";
45
+ QueryStatus7["rejected"] = "rejected";
46
+ return QueryStatus7;
47
+ })(QueryStatus || {});
48
+ var STATUS_UNINITIALIZED = "uninitialized" /* uninitialized */;
49
+ var STATUS_PENDING = "pending" /* pending */;
50
+ var STATUS_FULFILLED = "fulfilled" /* fulfilled */;
51
+ var STATUS_REJECTED = "rejected" /* rejected */;
52
+ function getRequestStatusFlags(status) {
53
+ return {
54
+ status,
55
+ isUninitialized: status === STATUS_UNINITIALIZED,
56
+ isLoading: status === STATUS_PENDING,
57
+ isSuccess: status === STATUS_FULFILLED,
58
+ isError: status === STATUS_REJECTED
59
+ };
60
+ }
61
+
62
+ // src/query/core/rtkImports.ts
63
+ var import_toolkit = require("@reduxjs/toolkit");
64
+
65
+ // src/query/utils/copyWithStructuralSharing.ts
66
+ var isPlainObject2 = import_toolkit.isPlainObject;
67
+ function copyWithStructuralSharing(oldObj, newObj) {
68
+ if (oldObj === newObj || !(isPlainObject2(oldObj) && isPlainObject2(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {
69
+ return newObj;
70
+ }
71
+ const newKeys = Object.keys(newObj);
72
+ const oldKeys = Object.keys(oldObj);
73
+ let isSameObject = newKeys.length === oldKeys.length;
74
+ const mergeObj = Array.isArray(newObj) ? [] : {};
75
+ for (const key of newKeys) {
76
+ mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);
77
+ if (isSameObject) isSameObject = oldObj[key] === mergeObj[key];
78
+ }
79
+ return isSameObject ? oldObj : mergeObj;
80
+ }
81
+
82
+ // src/query/utils/filterMap.ts
83
+ function filterMap(array, predicate, mapper) {
84
+ return array.reduce((acc, item, i) => {
85
+ if (predicate(item, i)) {
86
+ acc.push(mapper(item, i));
87
+ }
88
+ return acc;
89
+ }, []).flat();
90
+ }
91
+
92
+ // src/query/utils/isAbsoluteUrl.ts
93
+ function isAbsoluteUrl(url) {
94
+ return new RegExp(`(^|:)//`).test(url);
95
+ }
96
+
97
+ // src/query/utils/isDocumentVisible.ts
98
+ function isDocumentVisible() {
99
+ if (typeof document === "undefined") {
100
+ return true;
101
+ }
102
+ return document.visibilityState !== "hidden";
103
+ }
104
+
105
+ // src/query/utils/isNotNullish.ts
106
+ function isNotNullish(v) {
107
+ return v != null;
108
+ }
109
+ function filterNullishValues(map) {
110
+ return [...map?.values() ?? []].filter(isNotNullish);
111
+ }
112
+
113
+ // src/query/utils/isOnline.ts
114
+ function isOnline() {
115
+ return typeof navigator === "undefined" ? true : navigator.onLine === void 0 ? true : navigator.onLine;
116
+ }
117
+
118
+ // src/query/utils/joinUrls.ts
119
+ var withoutTrailingSlash = (url) => url.replace(/\/$/, "");
120
+ var withoutLeadingSlash = (url) => url.replace(/^\//, "");
121
+ function joinUrls(base, url) {
122
+ if (!base) {
123
+ return url;
124
+ }
125
+ if (!url) {
126
+ return base;
127
+ }
128
+ if (isAbsoluteUrl(url)) {
129
+ return url;
130
+ }
131
+ const delimiter = base.endsWith("/") || !url.startsWith("?") ? "/" : "";
132
+ base = withoutTrailingSlash(base);
133
+ url = withoutLeadingSlash(url);
134
+ return `${base}${delimiter}${url}`;
135
+ }
136
+
137
+ // src/query/utils/getOrInsert.ts
138
+ function getOrInsertComputed(map, key, compute) {
139
+ if (map.has(key)) return map.get(key);
140
+ return map.set(key, compute(key)).get(key);
141
+ }
142
+ var createNewMap = () => /* @__PURE__ */ new Map();
143
+
144
+ // src/query/utils/signals.ts
145
+ var timeoutSignal = (milliseconds) => {
146
+ const abortController = new AbortController();
147
+ setTimeout(() => {
148
+ const message = "signal timed out";
149
+ const name = "TimeoutError";
150
+ abortController.abort(
151
+ // some environments (React Native, Node) don't have DOMException
152
+ typeof DOMException !== "undefined" ? new DOMException(message, name) : Object.assign(new Error(message), {
153
+ name
154
+ })
155
+ );
156
+ }, milliseconds);
157
+ return abortController.signal;
158
+ };
159
+ var anySignal = (...signals) => {
160
+ for (const signal of signals) if (signal.aborted) return AbortSignal.abort(signal.reason);
161
+ const abortController = new AbortController();
162
+ for (const signal of signals) {
163
+ signal.addEventListener("abort", () => abortController.abort(signal.reason), {
164
+ signal: abortController.signal,
165
+ once: true
166
+ });
167
+ }
168
+ return abortController.signal;
169
+ };
170
+
171
+ // src/query/fetchBaseQuery.ts
172
+ var defaultFetchFn = (...args) => fetch(...args);
173
+ var defaultValidateStatus = (response) => response.status >= 200 && response.status <= 299;
174
+ var defaultIsJsonContentType = (headers) => (
175
+ /*applicat*/
176
+ /ion\/(vnd\.api\+)?json/.test(headers.get("content-type") || "")
177
+ );
178
+ function stripUndefined(obj) {
179
+ if (!(0, import_toolkit.isPlainObject)(obj)) {
180
+ return obj;
181
+ }
182
+ const copy = {
183
+ ...obj
184
+ };
185
+ for (const [k, v] of Object.entries(copy)) {
186
+ if (v === void 0) delete copy[k];
187
+ }
188
+ return copy;
189
+ }
190
+ var isJsonifiable = (body) => typeof body === "object" && ((0, import_toolkit.isPlainObject)(body) || Array.isArray(body) || typeof body.toJSON === "function");
191
+ function fetchBaseQuery({
192
+ baseUrl,
193
+ prepareHeaders = (x) => x,
194
+ fetchFn = defaultFetchFn,
195
+ paramsSerializer,
196
+ isJsonContentType = defaultIsJsonContentType,
197
+ jsonContentType = "application/json",
198
+ jsonReplacer,
199
+ timeout: defaultTimeout,
200
+ responseHandler: globalResponseHandler,
201
+ validateStatus: globalValidateStatus,
202
+ ...baseFetchOptions
203
+ } = {}) {
204
+ if (typeof fetch === "undefined" && fetchFn === defaultFetchFn) {
205
+ console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.");
206
+ }
207
+ return async (arg, api, extraOptions) => {
208
+ const {
209
+ getState,
210
+ extra,
211
+ endpoint,
212
+ forced,
213
+ type
214
+ } = api;
215
+ let meta;
216
+ let {
217
+ url,
218
+ headers = new Headers(baseFetchOptions.headers),
219
+ params = void 0,
220
+ responseHandler = globalResponseHandler ?? "json",
221
+ validateStatus = globalValidateStatus ?? defaultValidateStatus,
222
+ timeout = defaultTimeout,
223
+ ...rest
224
+ } = typeof arg == "string" ? {
225
+ url: arg
226
+ } : arg;
227
+ let config = {
228
+ ...baseFetchOptions,
229
+ signal: timeout ? anySignal(api.signal, timeoutSignal(timeout)) : api.signal,
230
+ ...rest
231
+ };
232
+ headers = new Headers(stripUndefined(headers));
233
+ config.headers = await prepareHeaders(headers, {
234
+ getState,
235
+ arg,
236
+ extra,
237
+ endpoint,
238
+ forced,
239
+ type,
240
+ extraOptions
241
+ }) || headers;
242
+ const bodyIsJsonifiable = isJsonifiable(config.body);
243
+ if (config.body != null && !bodyIsJsonifiable && typeof config.body !== "string") {
244
+ config.headers.delete("content-type");
245
+ }
246
+ if (!config.headers.has("content-type") && bodyIsJsonifiable) {
247
+ config.headers.set("content-type", jsonContentType);
248
+ }
249
+ if (bodyIsJsonifiable && isJsonContentType(config.headers)) {
250
+ config.body = JSON.stringify(config.body, jsonReplacer);
251
+ }
252
+ if (!config.headers.has("accept")) {
253
+ if (responseHandler === "json") {
254
+ config.headers.set("accept", "application/json");
255
+ } else if (responseHandler === "text") {
256
+ config.headers.set("accept", "text/plain, text/html, */*");
257
+ }
258
+ }
259
+ if (params) {
260
+ const divider = ~url.indexOf("?") ? "&" : "?";
261
+ const query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params));
262
+ url += divider + query;
263
+ }
264
+ url = joinUrls(baseUrl, url);
265
+ const request = new Request(url, config);
266
+ const requestClone = new Request(url, config);
267
+ meta = {
268
+ request: requestClone
269
+ };
270
+ let response;
271
+ try {
272
+ response = await fetchFn(request);
273
+ } catch (e) {
274
+ return {
275
+ error: {
276
+ status: (e instanceof Error || typeof DOMException !== "undefined" && e instanceof DOMException) && e.name === "TimeoutError" ? "TIMEOUT_ERROR" : "FETCH_ERROR",
277
+ error: String(e)
278
+ },
279
+ meta
280
+ };
281
+ }
282
+ const responseClone = response.clone();
283
+ meta.response = responseClone;
284
+ let resultData;
285
+ let responseText = "";
286
+ try {
287
+ let handleResponseError;
288
+ await Promise.all([
289
+ handleResponse(response, responseHandler).then((r) => resultData = r, (e) => handleResponseError = e),
290
+ // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182
291
+ // we *have* to "use up" both streams at the same time or they will stop running in node-fetch scenarios
292
+ responseClone.text().then((r) => responseText = r, () => {
293
+ })
294
+ ]);
295
+ if (handleResponseError) throw handleResponseError;
296
+ } catch (e) {
297
+ return {
298
+ error: {
299
+ status: "PARSING_ERROR",
300
+ originalStatus: response.status,
301
+ data: responseText,
302
+ error: String(e)
303
+ },
304
+ meta
305
+ };
306
+ }
307
+ return validateStatus(response, resultData) ? {
308
+ data: resultData,
309
+ meta
310
+ } : {
311
+ error: {
312
+ status: response.status,
313
+ data: resultData
314
+ },
315
+ meta
316
+ };
317
+ };
318
+ async function handleResponse(response, responseHandler) {
319
+ if (typeof responseHandler === "function") {
320
+ return responseHandler(response);
321
+ }
322
+ if (responseHandler === "content-type") {
323
+ responseHandler = isJsonContentType(response.headers) ? "json" : "text";
324
+ }
325
+ if (responseHandler === "json") {
326
+ const text = await response.text();
327
+ return text.length ? JSON.parse(text) : null;
328
+ }
329
+ return response.text();
330
+ }
331
+ }
332
+
333
+ // src/query/HandledError.ts
334
+ var HandledError = class {
335
+ constructor(value, meta = void 0) {
336
+ this.value = value;
337
+ this.meta = meta;
338
+ }
339
+ value;
340
+ meta;
341
+ };
342
+
343
+ // src/query/retry.ts
344
+ async function defaultBackoff(attempt = 0, maxRetries = 5, signal) {
345
+ const attempts = Math.min(attempt, maxRetries);
346
+ const timeout = ~~((Math.random() + 0.4) * (300 << attempts));
347
+ await new Promise((resolve, reject) => {
348
+ const timeoutId = setTimeout(() => resolve(), timeout);
349
+ if (signal) {
350
+ const abortHandler = () => {
351
+ clearTimeout(timeoutId);
352
+ reject(new Error("Aborted"));
353
+ };
354
+ if (signal.aborted) {
355
+ clearTimeout(timeoutId);
356
+ reject(new Error("Aborted"));
357
+ } else {
358
+ signal.addEventListener("abort", abortHandler, {
359
+ once: true
360
+ });
361
+ }
362
+ }
363
+ });
364
+ }
365
+ function fail(error, meta) {
366
+ throw Object.assign(new HandledError({
367
+ error,
368
+ meta
369
+ }), {
370
+ throwImmediately: true
371
+ });
372
+ }
373
+ function failIfAborted(signal) {
374
+ if (signal.aborted) {
375
+ fail({
376
+ status: "CUSTOM_ERROR",
377
+ error: "Aborted"
378
+ });
379
+ }
380
+ }
381
+ var EMPTY_OPTIONS = {};
382
+ var retryWithBackoff = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {
383
+ const possibleMaxRetries = [5, (defaultOptions || EMPTY_OPTIONS).maxRetries, (extraOptions || EMPTY_OPTIONS).maxRetries].filter((x) => x !== void 0);
384
+ const [maxRetries] = possibleMaxRetries.slice(-1);
385
+ const defaultRetryCondition = (_, __, {
386
+ attempt
387
+ }) => attempt <= maxRetries;
388
+ const options = {
389
+ maxRetries,
390
+ backoff: defaultBackoff,
391
+ retryCondition: defaultRetryCondition,
392
+ ...defaultOptions,
393
+ ...extraOptions
394
+ };
395
+ let retry2 = 0;
396
+ while (true) {
397
+ failIfAborted(api.signal);
398
+ try {
399
+ const result = await baseQuery(args, api, extraOptions);
400
+ if (result.error) {
401
+ throw new HandledError(result);
402
+ }
403
+ return result;
404
+ } catch (e) {
405
+ retry2++;
406
+ if (e.throwImmediately) {
407
+ if (e instanceof HandledError) {
408
+ return e.value;
409
+ }
410
+ throw e;
411
+ }
412
+ if (e instanceof HandledError) {
413
+ if (!options.retryCondition(e.value.error, args, {
414
+ attempt: retry2,
415
+ baseQueryApi: api,
416
+ extraOptions
417
+ })) {
418
+ return e.value;
419
+ }
420
+ } else {
421
+ if (retry2 > options.maxRetries) {
422
+ return {
423
+ error: e
424
+ };
425
+ }
426
+ }
427
+ failIfAborted(api.signal);
428
+ try {
429
+ await options.backoff(retry2, options.maxRetries, api.signal);
430
+ } catch (backoffError) {
431
+ failIfAborted(api.signal);
432
+ throw backoffError;
433
+ }
434
+ }
435
+ }
436
+ };
437
+ var retry = /* @__PURE__ */ Object.assign(retryWithBackoff, {
438
+ fail
439
+ });
440
+
441
+ // src/query/core/setupListeners.ts
442
+ var INTERNAL_PREFIX = "__rtkq/";
443
+ var ONLINE = "online";
444
+ var OFFLINE = "offline";
445
+ var FOCUS = "focus";
446
+ var FOCUSED = "focused";
447
+ var VISIBILITYCHANGE = "visibilitychange";
448
+ var onFocus = /* @__PURE__ */ (0, import_toolkit.createAction)(`${INTERNAL_PREFIX}${FOCUSED}`);
449
+ var onFocusLost = /* @__PURE__ */ (0, import_toolkit.createAction)(`${INTERNAL_PREFIX}un${FOCUSED}`);
450
+ var onOnline = /* @__PURE__ */ (0, import_toolkit.createAction)(`${INTERNAL_PREFIX}${ONLINE}`);
451
+ var onOffline = /* @__PURE__ */ (0, import_toolkit.createAction)(`${INTERNAL_PREFIX}${OFFLINE}`);
452
+ var actions = {
453
+ onFocus,
454
+ onFocusLost,
455
+ onOnline,
456
+ onOffline
457
+ };
458
+ var initialized = false;
459
+ function setupListeners(dispatch, customHandler) {
460
+ function defaultHandler() {
461
+ const [handleFocus, handleFocusLost, handleOnline, handleOffline] = [onFocus, onFocusLost, onOnline, onOffline].map((action) => () => dispatch(action()));
462
+ const handleVisibilityChange = () => {
463
+ if (window.document.visibilityState === "visible") {
464
+ handleFocus();
465
+ } else {
466
+ handleFocusLost();
467
+ }
468
+ };
469
+ let unsubscribe = () => {
470
+ initialized = false;
471
+ };
472
+ if (!initialized) {
473
+ if (typeof window !== "undefined" && window.addEventListener) {
474
+ let updateListeners2 = function(add) {
475
+ Object.entries(handlers).forEach(([event, handler]) => {
476
+ if (add) {
477
+ window.addEventListener(event, handler, false);
478
+ } else {
479
+ window.removeEventListener(event, handler);
480
+ }
481
+ });
482
+ };
483
+ var updateListeners = updateListeners2;
484
+ const handlers = {
485
+ [FOCUS]: handleFocus,
486
+ [VISIBILITYCHANGE]: handleVisibilityChange,
487
+ [ONLINE]: handleOnline,
488
+ [OFFLINE]: handleOffline
489
+ };
490
+ updateListeners2(true);
491
+ initialized = true;
492
+ unsubscribe = () => {
493
+ updateListeners2(false);
494
+ initialized = false;
495
+ };
496
+ }
497
+ }
498
+ return unsubscribe;
499
+ }
500
+ return customHandler ? customHandler(dispatch, actions) : defaultHandler();
501
+ }
502
+
503
+ // src/query/endpointDefinitions.ts
504
+ var ENDPOINT_QUERY = "query" /* query */;
505
+ var ENDPOINT_MUTATION = "mutation" /* mutation */;
506
+ var ENDPOINT_INFINITEQUERY = "infinitequery" /* infinitequery */;
507
+ function isQueryDefinition(e) {
508
+ return e.type === ENDPOINT_QUERY;
509
+ }
510
+ function isMutationDefinition(e) {
511
+ return e.type === ENDPOINT_MUTATION;
512
+ }
513
+ function isInfiniteQueryDefinition(e) {
514
+ return e.type === ENDPOINT_INFINITEQUERY;
515
+ }
516
+ function isAnyQueryDefinition(e) {
517
+ return isQueryDefinition(e) || isInfiniteQueryDefinition(e);
518
+ }
519
+ function calculateProvidedBy(description, result, error, queryArg, meta, assertTagTypes) {
520
+ const finalDescription = isFunction(description) ? description(result, error, queryArg, meta) : description;
521
+ if (finalDescription) {
522
+ return filterMap(finalDescription, isNotNullish, (tag) => assertTagTypes(expandTagDescription(tag)));
523
+ }
524
+ return [];
525
+ }
526
+ function isFunction(t) {
527
+ return typeof t === "function";
528
+ }
529
+ function expandTagDescription(description) {
530
+ return typeof description === "string" ? {
531
+ type: description
532
+ } : description;
533
+ }
534
+
535
+ // src/query/utils/immerImports.ts
536
+ var import_immer = require("immer");
537
+
538
+ // src/query/core/buildInitiate.ts
539
+ var import_toolkit2 = require("@reduxjs/toolkit");
540
+
541
+ // src/tsHelpers.ts
542
+ function asSafePromise(promise, fallback) {
543
+ return promise.catch(fallback);
544
+ }
545
+
546
+ // src/query/apiTypes.ts
547
+ var getEndpointDefinition = (context, endpointName) => context.endpointDefinitions[endpointName];
548
+
549
+ // src/query/core/buildInitiate.ts
550
+ var forceQueryFnSymbol = /* @__PURE__ */ Symbol("forceQueryFn");
551
+ var isUpsertQuery = (arg) => typeof arg[forceQueryFnSymbol] === "function";
552
+ function buildInitiate({
553
+ serializeQueryArgs,
554
+ queryThunk,
555
+ infiniteQueryThunk,
556
+ mutationThunk,
557
+ api,
558
+ context,
559
+ getInternalState
560
+ }) {
561
+ const getRunningQueries = (dispatch) => getInternalState(dispatch)?.runningQueries;
562
+ const getRunningMutations = (dispatch) => getInternalState(dispatch)?.runningMutations;
563
+ const {
564
+ unsubscribeQueryResult,
565
+ removeMutationResult,
566
+ updateSubscriptionOptions
567
+ } = api.internalActions;
568
+ return {
569
+ buildInitiateQuery,
570
+ buildInitiateInfiniteQuery,
571
+ buildInitiateMutation,
572
+ getRunningQueryThunk,
573
+ getRunningMutationThunk,
574
+ getRunningQueriesThunk,
575
+ getRunningMutationsThunk
576
+ };
577
+ function getRunningQueryThunk(endpointName, queryArgs) {
578
+ return (dispatch) => {
579
+ const endpointDefinition = getEndpointDefinition(context, endpointName);
580
+ const queryCacheKey = serializeQueryArgs({
581
+ queryArgs,
582
+ endpointDefinition,
583
+ endpointName
584
+ });
585
+ return getRunningQueries(dispatch)?.get(queryCacheKey);
586
+ };
587
+ }
588
+ function getRunningMutationThunk(_endpointName, fixedCacheKeyOrRequestId) {
589
+ return (dispatch) => {
590
+ return getRunningMutations(dispatch)?.get(fixedCacheKeyOrRequestId);
591
+ };
592
+ }
593
+ function getRunningQueriesThunk() {
594
+ return (dispatch) => filterNullishValues(getRunningQueries(dispatch));
595
+ }
596
+ function getRunningMutationsThunk() {
597
+ return (dispatch) => filterNullishValues(getRunningMutations(dispatch));
598
+ }
599
+ function middlewareWarning(dispatch) {
600
+ if (true) {
601
+ if (middlewareWarning.triggered) return;
602
+ const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
603
+ middlewareWarning.triggered = true;
604
+ if (typeof returnedValue !== "object" || typeof returnedValue?.type === "string") {
605
+ throw new Error(false ? _formatProdErrorMessage(34) : `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
606
+ You must add the middleware for RTK-Query to function correctly!`);
607
+ }
608
+ }
609
+ }
610
+ function buildInitiateAnyQuery(endpointName, endpointDefinition) {
611
+ const queryAction = (arg, {
612
+ subscribe = true,
613
+ forceRefetch,
614
+ subscriptionOptions,
615
+ [forceQueryFnSymbol]: forceQueryFn,
616
+ ...rest
617
+ } = {}) => (dispatch, getState) => {
618
+ const queryCacheKey = serializeQueryArgs({
619
+ queryArgs: arg,
620
+ endpointDefinition,
621
+ endpointName
622
+ });
623
+ let thunk;
624
+ const commonThunkArgs = {
625
+ ...rest,
626
+ type: ENDPOINT_QUERY,
627
+ subscribe,
628
+ forceRefetch,
629
+ subscriptionOptions,
630
+ endpointName,
631
+ originalArgs: arg,
632
+ queryCacheKey,
633
+ [forceQueryFnSymbol]: forceQueryFn
634
+ };
635
+ if (isQueryDefinition(endpointDefinition)) {
636
+ thunk = queryThunk(commonThunkArgs);
637
+ } else {
638
+ const {
639
+ direction,
640
+ initialPageParam,
641
+ refetchCachedPages
642
+ } = rest;
643
+ thunk = infiniteQueryThunk({
644
+ ...commonThunkArgs,
645
+ // Supply these even if undefined. This helps with a field existence
646
+ // check over in `buildSlice.ts`
647
+ direction,
648
+ initialPageParam,
649
+ refetchCachedPages
650
+ });
651
+ }
652
+ const selector = api.endpoints[endpointName].select(arg);
653
+ const thunkResult = dispatch(thunk);
654
+ const stateAfter = selector(getState());
655
+ middlewareWarning(dispatch);
656
+ const {
657
+ requestId,
658
+ abort
659
+ } = thunkResult;
660
+ const skippedSynchronously = stateAfter.requestId !== requestId;
661
+ const runningQuery = getRunningQueries(dispatch)?.get(queryCacheKey);
662
+ const selectFromState = () => selector(getState());
663
+ const statePromise = Object.assign(forceQueryFn ? (
664
+ // a query has been forced (upsertQueryData)
665
+ // -> we want to resolve it once data has been written with the data that will be written
666
+ thunkResult.then(selectFromState)
667
+ ) : skippedSynchronously && !runningQuery ? (
668
+ // a query has been skipped due to a condition and we do not have any currently running query
669
+ // -> we want to resolve it immediately with the current data
670
+ Promise.resolve(stateAfter)
671
+ ) : (
672
+ // query just started or one is already in flight
673
+ // -> wait for the running query, then resolve with data from after that
674
+ Promise.all([runningQuery, thunkResult]).then(selectFromState)
675
+ ), {
676
+ arg,
677
+ requestId,
678
+ subscriptionOptions,
679
+ queryCacheKey,
680
+ abort,
681
+ async unwrap() {
682
+ const result = await statePromise;
683
+ if (result.isError) {
684
+ throw result.error;
685
+ }
686
+ return result.data;
687
+ },
688
+ refetch: (options) => dispatch(queryAction(arg, {
689
+ subscribe: false,
690
+ forceRefetch: true,
691
+ ...options
692
+ })),
693
+ unsubscribe() {
694
+ if (subscribe) dispatch(unsubscribeQueryResult({
695
+ queryCacheKey,
696
+ requestId
697
+ }));
698
+ },
699
+ updateSubscriptionOptions(options) {
700
+ statePromise.subscriptionOptions = options;
701
+ dispatch(updateSubscriptionOptions({
702
+ endpointName,
703
+ requestId,
704
+ queryCacheKey,
705
+ options
706
+ }));
707
+ }
708
+ });
709
+ if (!runningQuery && !skippedSynchronously && !forceQueryFn) {
710
+ const runningQueries = getRunningQueries(dispatch);
711
+ runningQueries.set(queryCacheKey, statePromise);
712
+ statePromise.then(() => {
713
+ runningQueries.delete(queryCacheKey);
714
+ });
715
+ }
716
+ return statePromise;
717
+ };
718
+ return queryAction;
719
+ }
720
+ function buildInitiateQuery(endpointName, endpointDefinition) {
721
+ const queryAction = buildInitiateAnyQuery(endpointName, endpointDefinition);
722
+ return queryAction;
723
+ }
724
+ function buildInitiateInfiniteQuery(endpointName, endpointDefinition) {
725
+ const infiniteQueryAction = buildInitiateAnyQuery(endpointName, endpointDefinition);
726
+ return infiniteQueryAction;
727
+ }
728
+ function buildInitiateMutation(endpointName) {
729
+ return (arg, {
730
+ track = true,
731
+ fixedCacheKey
732
+ } = {}) => (dispatch, getState) => {
733
+ const thunk = mutationThunk({
734
+ type: "mutation",
735
+ endpointName,
736
+ originalArgs: arg,
737
+ track,
738
+ fixedCacheKey
739
+ });
740
+ const thunkResult = dispatch(thunk);
741
+ middlewareWarning(dispatch);
742
+ const {
743
+ requestId,
744
+ abort,
745
+ unwrap
746
+ } = thunkResult;
747
+ const returnValuePromise = asSafePromise(thunkResult.unwrap().then((data) => ({
748
+ data
749
+ })), (error) => ({
750
+ error
751
+ }));
752
+ const reset = () => {
753
+ dispatch(removeMutationResult({
754
+ requestId,
755
+ fixedCacheKey
756
+ }));
757
+ };
758
+ const ret = Object.assign(returnValuePromise, {
759
+ arg: thunkResult.arg,
760
+ requestId,
761
+ abort,
762
+ unwrap,
763
+ reset
764
+ });
765
+ const runningMutations = getRunningMutations(dispatch);
766
+ runningMutations.set(requestId, ret);
767
+ ret.then(() => {
768
+ runningMutations.delete(requestId);
769
+ });
770
+ if (fixedCacheKey) {
771
+ runningMutations.set(fixedCacheKey, ret);
772
+ ret.then(() => {
773
+ if (runningMutations.get(fixedCacheKey) === ret) {
774
+ runningMutations.delete(fixedCacheKey);
775
+ }
776
+ });
777
+ }
778
+ return ret;
779
+ };
780
+ }
781
+ }
782
+
783
+ // src/query/standardSchema.ts
784
+ var import_utils4 = require("@standard-schema/utils");
785
+ var NamedSchemaError = class extends import_utils4.SchemaError {
786
+ constructor(issues, value, schemaName, _bqMeta) {
787
+ super(issues);
788
+ this.value = value;
789
+ this.schemaName = schemaName;
790
+ this._bqMeta = _bqMeta;
791
+ }
792
+ value;
793
+ schemaName;
794
+ _bqMeta;
795
+ };
796
+ var shouldSkip = (skipSchemaValidation, schemaName) => Array.isArray(skipSchemaValidation) ? skipSchemaValidation.includes(schemaName) : !!skipSchemaValidation;
797
+ async function parseWithSchema(schema, data, schemaName, bqMeta) {
798
+ const result = await schema["~standard"].validate(data);
799
+ if (result.issues) {
800
+ throw new NamedSchemaError(result.issues, data, schemaName, bqMeta);
801
+ }
802
+ return result.value;
803
+ }
804
+
805
+ // src/query/core/buildThunks.ts
806
+ function defaultTransformResponse(baseQueryReturnValue) {
807
+ return baseQueryReturnValue;
808
+ }
809
+ var addShouldAutoBatch = (arg = {}) => {
810
+ return {
811
+ ...arg,
812
+ [import_toolkit.SHOULD_AUTOBATCH]: true
813
+ };
814
+ };
815
+ function buildThunks({
816
+ reducerPath,
817
+ baseQuery,
818
+ context: {
819
+ endpointDefinitions
820
+ },
821
+ serializeQueryArgs,
822
+ api,
823
+ assertTagType,
824
+ selectors,
825
+ onSchemaFailure,
826
+ catchSchemaFailure: globalCatchSchemaFailure,
827
+ skipSchemaValidation: globalSkipSchemaValidation
828
+ }) {
829
+ const patchQueryData = (endpointName, arg, patches, updateProvided) => (dispatch, getState) => {
830
+ const endpointDefinition = endpointDefinitions[endpointName];
831
+ const queryCacheKey = serializeQueryArgs({
832
+ queryArgs: arg,
833
+ endpointDefinition,
834
+ endpointName
835
+ });
836
+ dispatch(api.internalActions.queryResultPatched({
837
+ queryCacheKey,
838
+ patches
839
+ }));
840
+ if (!updateProvided) {
841
+ return;
842
+ }
843
+ const newValue = api.endpoints[endpointName].select(arg)(
844
+ // Work around TS 4.1 mismatch
845
+ getState()
846
+ );
847
+ const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, void 0, arg, {}, assertTagType);
848
+ dispatch(api.internalActions.updateProvidedBy([{
849
+ queryCacheKey,
850
+ providedTags
851
+ }]));
852
+ };
853
+ function addToStart(items, item, max = 0) {
854
+ const newItems = [item, ...items];
855
+ return max && newItems.length > max ? newItems.slice(0, -1) : newItems;
856
+ }
857
+ function addToEnd(items, item, max = 0) {
858
+ const newItems = [...items, item];
859
+ return max && newItems.length > max ? newItems.slice(1) : newItems;
860
+ }
861
+ const updateQueryData = (endpointName, arg, updateRecipe, updateProvided = true) => (dispatch, getState) => {
862
+ const endpointDefinition = api.endpoints[endpointName];
863
+ const currentState = endpointDefinition.select(arg)(
864
+ // Work around TS 4.1 mismatch
865
+ getState()
866
+ );
867
+ const ret = {
868
+ patches: [],
869
+ inversePatches: [],
870
+ undo: () => dispatch(api.util.patchQueryData(endpointName, arg, ret.inversePatches, updateProvided))
871
+ };
872
+ if (currentState.status === STATUS_UNINITIALIZED) {
873
+ return ret;
874
+ }
875
+ let newValue;
876
+ if ("data" in currentState) {
877
+ if ((0, import_immer.isDraftable)(currentState.data)) {
878
+ const [value, patches, inversePatches] = (0, import_immer.produceWithPatches)(currentState.data, updateRecipe);
879
+ ret.patches.push(...patches);
880
+ ret.inversePatches.push(...inversePatches);
881
+ newValue = value;
882
+ } else {
883
+ newValue = updateRecipe(currentState.data);
884
+ ret.patches.push({
885
+ op: "replace",
886
+ path: [],
887
+ value: newValue
888
+ });
889
+ ret.inversePatches.push({
890
+ op: "replace",
891
+ path: [],
892
+ value: currentState.data
893
+ });
894
+ }
895
+ }
896
+ if (ret.patches.length === 0) {
897
+ return ret;
898
+ }
899
+ dispatch(api.util.patchQueryData(endpointName, arg, ret.patches, updateProvided));
900
+ return ret;
901
+ };
902
+ const upsertQueryData = (endpointName, arg, value) => (dispatch) => {
903
+ const res = dispatch(api.endpoints[endpointName].initiate(arg, {
904
+ subscribe: false,
905
+ forceRefetch: true,
906
+ [forceQueryFnSymbol]: () => ({
907
+ data: value
908
+ })
909
+ }));
910
+ return res;
911
+ };
912
+ const getTransformCallbackForEndpoint = (endpointDefinition, transformFieldName) => {
913
+ return endpointDefinition.query && endpointDefinition[transformFieldName] ? endpointDefinition[transformFieldName] : defaultTransformResponse;
914
+ };
915
+ const executeEndpoint = async (arg, {
916
+ signal,
917
+ abort,
918
+ rejectWithValue,
919
+ fulfillWithValue,
920
+ dispatch,
921
+ getState,
922
+ extra
923
+ }) => {
924
+ const endpointDefinition = endpointDefinitions[arg.endpointName];
925
+ const {
926
+ metaSchema,
927
+ skipSchemaValidation = globalSkipSchemaValidation
928
+ } = endpointDefinition;
929
+ const isQuery = arg.type === ENDPOINT_QUERY;
930
+ try {
931
+ let transformResponse = defaultTransformResponse;
932
+ const baseQueryApi = {
933
+ signal,
934
+ abort,
935
+ dispatch,
936
+ getState,
937
+ extra,
938
+ endpoint: arg.endpointName,
939
+ type: arg.type,
940
+ forced: isQuery ? isForcedQuery(arg, getState()) : void 0,
941
+ queryCacheKey: isQuery ? arg.queryCacheKey : void 0
942
+ };
943
+ const forceQueryFn = isQuery ? arg[forceQueryFnSymbol] : void 0;
944
+ let finalQueryReturnValue;
945
+ const fetchPage = async (data, param, maxPages, previous) => {
946
+ if (param == null && data.pages.length) {
947
+ return Promise.resolve({
948
+ data
949
+ });
950
+ }
951
+ const finalQueryArg = {
952
+ queryArg: arg.originalArgs,
953
+ pageParam: param
954
+ };
955
+ const pageResponse = await executeRequest(finalQueryArg);
956
+ const addTo = previous ? addToStart : addToEnd;
957
+ return {
958
+ data: {
959
+ pages: addTo(data.pages, pageResponse.data, maxPages),
960
+ pageParams: addTo(data.pageParams, param, maxPages)
961
+ },
962
+ meta: pageResponse.meta
963
+ };
964
+ };
965
+ async function executeRequest(finalQueryArg) {
966
+ let result;
967
+ const {
968
+ extraOptions,
969
+ argSchema,
970
+ rawResponseSchema,
971
+ responseSchema
972
+ } = endpointDefinition;
973
+ if (argSchema && !shouldSkip(skipSchemaValidation, "arg")) {
974
+ finalQueryArg = await parseWithSchema(
975
+ argSchema,
976
+ finalQueryArg,
977
+ "argSchema",
978
+ {}
979
+ // we don't have a meta yet, so we can't pass it
980
+ );
981
+ }
982
+ if (forceQueryFn) {
983
+ result = forceQueryFn();
984
+ } else if (endpointDefinition.query) {
985
+ transformResponse = getTransformCallbackForEndpoint(endpointDefinition, "transformResponse");
986
+ result = await baseQuery(endpointDefinition.query(finalQueryArg), baseQueryApi, extraOptions);
987
+ } else {
988
+ result = await endpointDefinition.queryFn(finalQueryArg, baseQueryApi, extraOptions, (arg2) => baseQuery(arg2, baseQueryApi, extraOptions));
989
+ }
990
+ if (typeof process !== "undefined" && true) {
991
+ const what = endpointDefinition.query ? "`baseQuery`" : "`queryFn`";
992
+ let err;
993
+ if (!result) {
994
+ err = `${what} did not return anything.`;
995
+ } else if (typeof result !== "object") {
996
+ err = `${what} did not return an object.`;
997
+ } else if (result.error && result.data) {
998
+ err = `${what} returned an object containing both \`error\` and \`result\`.`;
999
+ } else if (result.error === void 0 && result.data === void 0) {
1000
+ err = `${what} returned an object containing neither a valid \`error\` and \`result\`. At least one of them should not be \`undefined\``;
1001
+ } else {
1002
+ for (const key of Object.keys(result)) {
1003
+ if (key !== "error" && key !== "data" && key !== "meta") {
1004
+ err = `The object returned by ${what} has the unknown property ${key}.`;
1005
+ break;
1006
+ }
1007
+ }
1008
+ }
1009
+ if (err) {
1010
+ console.error(`Error encountered handling the endpoint ${arg.endpointName}.
1011
+ ${err}
1012
+ It needs to return an object with either the shape \`{ data: <value> }\` or \`{ error: <value> }\` that may contain an optional \`meta\` property.
1013
+ Object returned was:`, result);
1014
+ }
1015
+ }
1016
+ if (result.error) throw new HandledError(result.error, result.meta);
1017
+ let {
1018
+ data
1019
+ } = result;
1020
+ if (rawResponseSchema && !shouldSkip(skipSchemaValidation, "rawResponse")) {
1021
+ data = await parseWithSchema(rawResponseSchema, result.data, "rawResponseSchema", result.meta);
1022
+ }
1023
+ let transformedResponse = await transformResponse(data, result.meta, finalQueryArg);
1024
+ if (responseSchema && !shouldSkip(skipSchemaValidation, "response")) {
1025
+ transformedResponse = await parseWithSchema(responseSchema, transformedResponse, "responseSchema", result.meta);
1026
+ }
1027
+ return {
1028
+ ...result,
1029
+ data: transformedResponse
1030
+ };
1031
+ }
1032
+ if (isQuery && "infiniteQueryOptions" in endpointDefinition) {
1033
+ const {
1034
+ infiniteQueryOptions
1035
+ } = endpointDefinition;
1036
+ const {
1037
+ maxPages = Infinity
1038
+ } = infiniteQueryOptions;
1039
+ const refetchCachedPages = arg.refetchCachedPages ?? infiniteQueryOptions.refetchCachedPages ?? true;
1040
+ let result;
1041
+ const blankData = {
1042
+ pages: [],
1043
+ pageParams: []
1044
+ };
1045
+ const cachedData = selectors.selectQueryEntry(getState(), arg.queryCacheKey)?.data;
1046
+ const isForcedQueryNeedingRefetch = (
1047
+ // arg.forceRefetch
1048
+ isForcedQuery(arg, getState()) && !arg.direction
1049
+ );
1050
+ const existingData = isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData;
1051
+ if ("direction" in arg && arg.direction && existingData.pages.length) {
1052
+ const previous = arg.direction === "backward";
1053
+ const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
1054
+ const param = pageParamFn(infiniteQueryOptions, existingData, arg.originalArgs);
1055
+ result = await fetchPage(existingData, param, maxPages, previous);
1056
+ } else {
1057
+ const {
1058
+ initialPageParam = infiniteQueryOptions.initialPageParam
1059
+ } = arg;
1060
+ const cachedPageParams = cachedData?.pageParams ?? [];
1061
+ const firstPageParam = cachedPageParams[0] ?? initialPageParam;
1062
+ const totalPages = cachedPageParams.length;
1063
+ result = await fetchPage(existingData, firstPageParam, maxPages);
1064
+ if (forceQueryFn) {
1065
+ result = {
1066
+ data: result.data.pages[0]
1067
+ };
1068
+ }
1069
+ if (refetchCachedPages) {
1070
+ for (let i = 1; i < totalPages; i++) {
1071
+ const param = getNextPageParam(infiniteQueryOptions, result.data, arg.originalArgs);
1072
+ result = await fetchPage(result.data, param, maxPages);
1073
+ }
1074
+ }
1075
+ }
1076
+ finalQueryReturnValue = result;
1077
+ } else {
1078
+ finalQueryReturnValue = await executeRequest(arg.originalArgs);
1079
+ }
1080
+ if (metaSchema && !shouldSkip(skipSchemaValidation, "meta") && finalQueryReturnValue.meta) {
1081
+ finalQueryReturnValue.meta = await parseWithSchema(metaSchema, finalQueryReturnValue.meta, "metaSchema", finalQueryReturnValue.meta);
1082
+ }
1083
+ return fulfillWithValue(finalQueryReturnValue.data, addShouldAutoBatch({
1084
+ fulfilledTimeStamp: Date.now(),
1085
+ baseQueryMeta: finalQueryReturnValue.meta
1086
+ }));
1087
+ } catch (error) {
1088
+ let caughtError = error;
1089
+ if (caughtError instanceof HandledError) {
1090
+ let transformErrorResponse = getTransformCallbackForEndpoint(endpointDefinition, "transformErrorResponse");
1091
+ const {
1092
+ rawErrorResponseSchema,
1093
+ errorResponseSchema
1094
+ } = endpointDefinition;
1095
+ let {
1096
+ value,
1097
+ meta
1098
+ } = caughtError;
1099
+ try {
1100
+ if (rawErrorResponseSchema && !shouldSkip(skipSchemaValidation, "rawErrorResponse")) {
1101
+ value = await parseWithSchema(rawErrorResponseSchema, value, "rawErrorResponseSchema", meta);
1102
+ }
1103
+ if (metaSchema && !shouldSkip(skipSchemaValidation, "meta")) {
1104
+ meta = await parseWithSchema(metaSchema, meta, "metaSchema", meta);
1105
+ }
1106
+ let transformedErrorResponse = await transformErrorResponse(value, meta, arg.originalArgs);
1107
+ if (errorResponseSchema && !shouldSkip(skipSchemaValidation, "errorResponse")) {
1108
+ transformedErrorResponse = await parseWithSchema(errorResponseSchema, transformedErrorResponse, "errorResponseSchema", meta);
1109
+ }
1110
+ return rejectWithValue(transformedErrorResponse, addShouldAutoBatch({
1111
+ baseQueryMeta: meta
1112
+ }));
1113
+ } catch (e) {
1114
+ caughtError = e;
1115
+ }
1116
+ }
1117
+ try {
1118
+ if (caughtError instanceof NamedSchemaError) {
1119
+ const info = {
1120
+ endpoint: arg.endpointName,
1121
+ arg: arg.originalArgs,
1122
+ type: arg.type,
1123
+ queryCacheKey: isQuery ? arg.queryCacheKey : void 0
1124
+ };
1125
+ endpointDefinition.onSchemaFailure?.(caughtError, info);
1126
+ onSchemaFailure?.(caughtError, info);
1127
+ const {
1128
+ catchSchemaFailure = globalCatchSchemaFailure
1129
+ } = endpointDefinition;
1130
+ if (catchSchemaFailure) {
1131
+ return rejectWithValue(catchSchemaFailure(caughtError, info), addShouldAutoBatch({
1132
+ baseQueryMeta: caughtError._bqMeta
1133
+ }));
1134
+ }
1135
+ }
1136
+ } catch (e) {
1137
+ caughtError = e;
1138
+ }
1139
+ if (typeof process !== "undefined" && true) {
1140
+ console.error(`An unhandled error occurred processing a request for the endpoint "${arg.endpointName}".
1141
+ In the case of an unhandled error, no tags will be "provided" or "invalidated".`, caughtError);
1142
+ } else {
1143
+ console.error(caughtError);
1144
+ }
1145
+ throw caughtError;
1146
+ }
1147
+ };
1148
+ function isForcedQuery(arg, state) {
1149
+ const requestState = selectors.selectQueryEntry(state, arg.queryCacheKey);
1150
+ const baseFetchOnMountOrArgChange = selectors.selectConfig(state).refetchOnMountOrArgChange;
1151
+ const fulfilledVal = requestState?.fulfilledTimeStamp;
1152
+ const refetchVal = arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange);
1153
+ if (refetchVal) {
1154
+ return refetchVal === true || (Number(/* @__PURE__ */ new Date()) - Number(fulfilledVal)) / 1e3 >= refetchVal;
1155
+ }
1156
+ return false;
1157
+ }
1158
+ const createQueryThunk = () => {
1159
+ const generatedQueryThunk = (0, import_toolkit.createAsyncThunk)(`${reducerPath}/executeQuery`, executeEndpoint, {
1160
+ getPendingMeta({
1161
+ arg
1162
+ }) {
1163
+ const endpointDefinition = endpointDefinitions[arg.endpointName];
1164
+ return addShouldAutoBatch({
1165
+ startedTimeStamp: Date.now(),
1166
+ ...isInfiniteQueryDefinition(endpointDefinition) ? {
1167
+ direction: arg.direction
1168
+ } : {}
1169
+ });
1170
+ },
1171
+ condition(queryThunkArg, {
1172
+ getState
1173
+ }) {
1174
+ const state = getState();
1175
+ const requestState = selectors.selectQueryEntry(state, queryThunkArg.queryCacheKey);
1176
+ const fulfilledVal = requestState?.fulfilledTimeStamp;
1177
+ const currentArg = queryThunkArg.originalArgs;
1178
+ const previousArg = requestState?.originalArgs;
1179
+ const endpointDefinition = endpointDefinitions[queryThunkArg.endpointName];
1180
+ const direction = queryThunkArg.direction;
1181
+ if (isUpsertQuery(queryThunkArg)) {
1182
+ return true;
1183
+ }
1184
+ if (requestState?.status === "pending") {
1185
+ return false;
1186
+ }
1187
+ if (isForcedQuery(queryThunkArg, state)) {
1188
+ return true;
1189
+ }
1190
+ if (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({
1191
+ currentArg,
1192
+ previousArg,
1193
+ endpointState: requestState,
1194
+ state
1195
+ })) {
1196
+ return true;
1197
+ }
1198
+ if (fulfilledVal && !direction) {
1199
+ return false;
1200
+ }
1201
+ return true;
1202
+ },
1203
+ dispatchConditionRejection: true
1204
+ });
1205
+ return generatedQueryThunk;
1206
+ };
1207
+ const queryThunk = createQueryThunk();
1208
+ const infiniteQueryThunk = createQueryThunk();
1209
+ const mutationThunk = (0, import_toolkit.createAsyncThunk)(`${reducerPath}/executeMutation`, executeEndpoint, {
1210
+ getPendingMeta() {
1211
+ return addShouldAutoBatch({
1212
+ startedTimeStamp: Date.now()
1213
+ });
1214
+ }
1215
+ });
1216
+ const hasTheForce = (options) => "force" in options;
1217
+ const hasMaxAge = (options) => "ifOlderThan" in options;
1218
+ const prefetch = (endpointName, arg, options = {}) => (dispatch, getState) => {
1219
+ const force = hasTheForce(options) && options.force;
1220
+ const maxAge = hasMaxAge(options) && options.ifOlderThan;
1221
+ const queryAction = (force2 = true) => {
1222
+ const options2 = {
1223
+ forceRefetch: force2,
1224
+ subscribe: false
1225
+ };
1226
+ return api.endpoints[endpointName].initiate(arg, options2);
1227
+ };
1228
+ const latestStateValue = api.endpoints[endpointName].select(arg)(getState());
1229
+ if (force) {
1230
+ dispatch(queryAction());
1231
+ } else if (maxAge) {
1232
+ const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp;
1233
+ if (!lastFulfilledTs) {
1234
+ dispatch(queryAction());
1235
+ return;
1236
+ }
1237
+ const shouldRetrigger = (Number(/* @__PURE__ */ new Date()) - Number(new Date(lastFulfilledTs))) / 1e3 >= maxAge;
1238
+ if (shouldRetrigger) {
1239
+ dispatch(queryAction());
1240
+ }
1241
+ } else {
1242
+ dispatch(queryAction(false));
1243
+ }
1244
+ };
1245
+ function matchesEndpoint(endpointName) {
1246
+ return (action) => action?.meta?.arg?.endpointName === endpointName;
1247
+ }
1248
+ function buildMatchThunkActions(thunk, endpointName) {
1249
+ return {
1250
+ matchPending: (0, import_toolkit.isAllOf)((0, import_toolkit.isPending)(thunk), matchesEndpoint(endpointName)),
1251
+ matchFulfilled: (0, import_toolkit.isAllOf)((0, import_toolkit.isFulfilled)(thunk), matchesEndpoint(endpointName)),
1252
+ matchRejected: (0, import_toolkit.isAllOf)((0, import_toolkit.isRejected)(thunk), matchesEndpoint(endpointName))
1253
+ };
1254
+ }
1255
+ return {
1256
+ queryThunk,
1257
+ mutationThunk,
1258
+ infiniteQueryThunk,
1259
+ prefetch,
1260
+ updateQueryData,
1261
+ upsertQueryData,
1262
+ patchQueryData,
1263
+ buildMatchThunkActions
1264
+ };
1265
+ }
1266
+ function getNextPageParam(options, {
1267
+ pages,
1268
+ pageParams
1269
+ }, queryArg) {
1270
+ const lastIndex = pages.length - 1;
1271
+ return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams, queryArg);
1272
+ }
1273
+ function getPreviousPageParam(options, {
1274
+ pages,
1275
+ pageParams
1276
+ }, queryArg) {
1277
+ return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams, queryArg);
1278
+ }
1279
+ function calculateProvidedByThunk(action, type, endpointDefinitions, assertTagType) {
1280
+ return calculateProvidedBy(endpointDefinitions[action.meta.arg.endpointName][type], (0, import_toolkit.isFulfilled)(action) ? action.payload : void 0, (0, import_toolkit.isRejectedWithValue)(action) ? action.payload : void 0, action.meta.arg.originalArgs, "baseQueryMeta" in action.meta ? action.meta.baseQueryMeta : void 0, assertTagType);
1281
+ }
1282
+
1283
+ // src/query/utils/getCurrent.ts
1284
+ function getCurrent(value) {
1285
+ return (0, import_immer.isDraft)(value) ? (0, import_immer.current)(value) : value;
1286
+ }
1287
+
1288
+ // src/query/core/buildSlice.ts
1289
+ function updateQuerySubstateIfExists(state, queryCacheKey, update) {
1290
+ const substate = state[queryCacheKey];
1291
+ if (substate) {
1292
+ update(substate);
1293
+ }
1294
+ }
1295
+ function getMutationCacheKey(id) {
1296
+ return ("arg" in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId;
1297
+ }
1298
+ function updateMutationSubstateIfExists(state, id, update) {
1299
+ const substate = state[getMutationCacheKey(id)];
1300
+ if (substate) {
1301
+ update(substate);
1302
+ }
1303
+ }
1304
+ var initialState = {};
1305
+ function buildSlice({
1306
+ reducerPath,
1307
+ queryThunk,
1308
+ mutationThunk,
1309
+ serializeQueryArgs,
1310
+ context: {
1311
+ endpointDefinitions: definitions,
1312
+ apiUid,
1313
+ extractRehydrationInfo,
1314
+ hasRehydrationInfo
1315
+ },
1316
+ assertTagType,
1317
+ config
1318
+ }) {
1319
+ const resetApiState = (0, import_toolkit.createAction)(`${reducerPath}/resetApiState`);
1320
+ function writePendingCacheEntry(draft, arg, upserting, meta) {
1321
+ draft[arg.queryCacheKey] ??= {
1322
+ status: STATUS_UNINITIALIZED,
1323
+ endpointName: arg.endpointName
1324
+ };
1325
+ updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
1326
+ substate.status = STATUS_PENDING;
1327
+ substate.requestId = upserting && substate.requestId ? (
1328
+ // for `upsertQuery` **updates**, keep the current `requestId`
1329
+ substate.requestId
1330
+ ) : (
1331
+ // for normal queries or `upsertQuery` **inserts** always update the `requestId`
1332
+ meta.requestId
1333
+ );
1334
+ if (arg.originalArgs !== void 0) {
1335
+ substate.originalArgs = arg.originalArgs;
1336
+ }
1337
+ substate.startedTimeStamp = meta.startedTimeStamp;
1338
+ const endpointDefinition = definitions[meta.arg.endpointName];
1339
+ if (isInfiniteQueryDefinition(endpointDefinition) && "direction" in arg) {
1340
+ ;
1341
+ substate.direction = arg.direction;
1342
+ }
1343
+ });
1344
+ }
1345
+ function writeFulfilledCacheEntry(draft, meta, payload, upserting) {
1346
+ updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, (substate) => {
1347
+ if (substate.requestId !== meta.requestId && !upserting) return;
1348
+ const {
1349
+ merge
1350
+ } = definitions[meta.arg.endpointName];
1351
+ substate.status = STATUS_FULFILLED;
1352
+ if (merge) {
1353
+ if (substate.data !== void 0) {
1354
+ const {
1355
+ fulfilledTimeStamp,
1356
+ arg,
1357
+ baseQueryMeta,
1358
+ requestId
1359
+ } = meta;
1360
+ let newData = (0, import_toolkit.createNextState)(substate.data, (draftSubstateData) => {
1361
+ return merge(draftSubstateData, payload, {
1362
+ arg: arg.originalArgs,
1363
+ baseQueryMeta,
1364
+ fulfilledTimeStamp,
1365
+ requestId
1366
+ });
1367
+ });
1368
+ substate.data = newData;
1369
+ } else {
1370
+ substate.data = payload;
1371
+ }
1372
+ } else {
1373
+ substate.data = definitions[meta.arg.endpointName].structuralSharing ?? true ? copyWithStructuralSharing((0, import_immer.isDraft)(substate.data) ? (0, import_immer.original)(substate.data) : substate.data, payload) : payload;
1374
+ }
1375
+ delete substate.error;
1376
+ substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
1377
+ });
1378
+ }
1379
+ const querySlice = (0, import_toolkit.createSlice)({
1380
+ name: `${reducerPath}/queries`,
1381
+ initialState,
1382
+ reducers: {
1383
+ removeQueryResult: {
1384
+ reducer(draft, {
1385
+ payload: {
1386
+ queryCacheKey
1387
+ }
1388
+ }) {
1389
+ delete draft[queryCacheKey];
1390
+ },
1391
+ prepare: (0, import_toolkit.prepareAutoBatched)()
1392
+ },
1393
+ cacheEntriesUpserted: {
1394
+ reducer(draft, action) {
1395
+ for (const entry of action.payload) {
1396
+ const {
1397
+ queryDescription: arg,
1398
+ value
1399
+ } = entry;
1400
+ writePendingCacheEntry(draft, arg, true, {
1401
+ arg,
1402
+ requestId: action.meta.requestId,
1403
+ startedTimeStamp: action.meta.timestamp
1404
+ });
1405
+ writeFulfilledCacheEntry(
1406
+ draft,
1407
+ {
1408
+ arg,
1409
+ requestId: action.meta.requestId,
1410
+ fulfilledTimeStamp: action.meta.timestamp,
1411
+ baseQueryMeta: {}
1412
+ },
1413
+ value,
1414
+ // We know we're upserting here
1415
+ true
1416
+ );
1417
+ }
1418
+ },
1419
+ prepare: (payload) => {
1420
+ const queryDescriptions = payload.map((entry) => {
1421
+ const {
1422
+ endpointName,
1423
+ arg,
1424
+ value
1425
+ } = entry;
1426
+ const endpointDefinition = definitions[endpointName];
1427
+ const queryDescription = {
1428
+ type: ENDPOINT_QUERY,
1429
+ endpointName,
1430
+ originalArgs: entry.arg,
1431
+ queryCacheKey: serializeQueryArgs({
1432
+ queryArgs: arg,
1433
+ endpointDefinition,
1434
+ endpointName
1435
+ })
1436
+ };
1437
+ return {
1438
+ queryDescription,
1439
+ value
1440
+ };
1441
+ });
1442
+ const result = {
1443
+ payload: queryDescriptions,
1444
+ meta: {
1445
+ [import_toolkit.SHOULD_AUTOBATCH]: true,
1446
+ requestId: (0, import_toolkit.nanoid)(),
1447
+ timestamp: Date.now()
1448
+ }
1449
+ };
1450
+ return result;
1451
+ }
1452
+ },
1453
+ queryResultPatched: {
1454
+ reducer(draft, {
1455
+ payload: {
1456
+ queryCacheKey,
1457
+ patches
1458
+ }
1459
+ }) {
1460
+ updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {
1461
+ substate.data = (0, import_immer.applyPatches)(substate.data, patches.concat());
1462
+ });
1463
+ },
1464
+ prepare: (0, import_toolkit.prepareAutoBatched)()
1465
+ }
1466
+ },
1467
+ extraReducers(builder) {
1468
+ builder.addCase(queryThunk.pending, (draft, {
1469
+ meta,
1470
+ meta: {
1471
+ arg
1472
+ }
1473
+ }) => {
1474
+ const upserting = isUpsertQuery(arg);
1475
+ writePendingCacheEntry(draft, arg, upserting, meta);
1476
+ }).addCase(queryThunk.fulfilled, (draft, {
1477
+ meta,
1478
+ payload
1479
+ }) => {
1480
+ const upserting = isUpsertQuery(meta.arg);
1481
+ writeFulfilledCacheEntry(draft, meta, payload, upserting);
1482
+ }).addCase(queryThunk.rejected, (draft, {
1483
+ meta: {
1484
+ condition,
1485
+ arg,
1486
+ requestId
1487
+ },
1488
+ error,
1489
+ payload
1490
+ }) => {
1491
+ updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
1492
+ if (condition) {
1493
+ } else {
1494
+ if (substate.requestId !== requestId) return;
1495
+ substate.status = STATUS_REJECTED;
1496
+ substate.error = payload ?? error;
1497
+ }
1498
+ });
1499
+ }).addMatcher(hasRehydrationInfo, (draft, action) => {
1500
+ const {
1501
+ queries
1502
+ } = extractRehydrationInfo(action);
1503
+ for (const [key, entry] of Object.entries(queries)) {
1504
+ if (
1505
+ // do not rehydrate entries that were currently in flight.
1506
+ entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED
1507
+ ) {
1508
+ draft[key] = entry;
1509
+ }
1510
+ }
1511
+ });
1512
+ }
1513
+ });
1514
+ const mutationSlice = (0, import_toolkit.createSlice)({
1515
+ name: `${reducerPath}/mutations`,
1516
+ initialState,
1517
+ reducers: {
1518
+ removeMutationResult: {
1519
+ reducer(draft, {
1520
+ payload
1521
+ }) {
1522
+ const cacheKey = getMutationCacheKey(payload);
1523
+ if (cacheKey in draft) {
1524
+ delete draft[cacheKey];
1525
+ }
1526
+ },
1527
+ prepare: (0, import_toolkit.prepareAutoBatched)()
1528
+ }
1529
+ },
1530
+ extraReducers(builder) {
1531
+ builder.addCase(mutationThunk.pending, (draft, {
1532
+ meta,
1533
+ meta: {
1534
+ requestId,
1535
+ arg,
1536
+ startedTimeStamp
1537
+ }
1538
+ }) => {
1539
+ if (!arg.track) return;
1540
+ draft[getMutationCacheKey(meta)] = {
1541
+ requestId,
1542
+ status: STATUS_PENDING,
1543
+ endpointName: arg.endpointName,
1544
+ startedTimeStamp
1545
+ };
1546
+ }).addCase(mutationThunk.fulfilled, (draft, {
1547
+ payload,
1548
+ meta
1549
+ }) => {
1550
+ if (!meta.arg.track) return;
1551
+ updateMutationSubstateIfExists(draft, meta, (substate) => {
1552
+ if (substate.requestId !== meta.requestId) return;
1553
+ substate.status = STATUS_FULFILLED;
1554
+ substate.data = payload;
1555
+ substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
1556
+ });
1557
+ }).addCase(mutationThunk.rejected, (draft, {
1558
+ payload,
1559
+ error,
1560
+ meta
1561
+ }) => {
1562
+ if (!meta.arg.track) return;
1563
+ updateMutationSubstateIfExists(draft, meta, (substate) => {
1564
+ if (substate.requestId !== meta.requestId) return;
1565
+ substate.status = STATUS_REJECTED;
1566
+ substate.error = payload ?? error;
1567
+ });
1568
+ }).addMatcher(hasRehydrationInfo, (draft, action) => {
1569
+ const {
1570
+ mutations
1571
+ } = extractRehydrationInfo(action);
1572
+ for (const [key, entry] of Object.entries(mutations)) {
1573
+ if (
1574
+ // do not rehydrate entries that were currently in flight.
1575
+ (entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED) && // only rehydrate endpoints that were persisted using a `fixedCacheKey`
1576
+ key !== entry?.requestId
1577
+ ) {
1578
+ draft[key] = entry;
1579
+ }
1580
+ }
1581
+ });
1582
+ }
1583
+ });
1584
+ const initialInvalidationState = {
1585
+ tags: {},
1586
+ keys: {}
1587
+ };
1588
+ const invalidationSlice = (0, import_toolkit.createSlice)({
1589
+ name: `${reducerPath}/invalidation`,
1590
+ initialState: initialInvalidationState,
1591
+ reducers: {
1592
+ updateProvidedBy: {
1593
+ reducer(draft, action) {
1594
+ for (const {
1595
+ queryCacheKey,
1596
+ providedTags
1597
+ } of action.payload) {
1598
+ removeCacheKeyFromTags(draft, queryCacheKey);
1599
+ for (const {
1600
+ type,
1601
+ id
1602
+ } of providedTags) {
1603
+ const subscribedQueries = (draft.tags[type] ??= {})[id || "__internal_without_id"] ??= [];
1604
+ const alreadySubscribed = subscribedQueries.includes(queryCacheKey);
1605
+ if (!alreadySubscribed) {
1606
+ subscribedQueries.push(queryCacheKey);
1607
+ }
1608
+ }
1609
+ draft.keys[queryCacheKey] = providedTags;
1610
+ }
1611
+ },
1612
+ prepare: (0, import_toolkit.prepareAutoBatched)()
1613
+ }
1614
+ },
1615
+ extraReducers(builder) {
1616
+ builder.addCase(querySlice.actions.removeQueryResult, (draft, {
1617
+ payload: {
1618
+ queryCacheKey
1619
+ }
1620
+ }) => {
1621
+ removeCacheKeyFromTags(draft, queryCacheKey);
1622
+ }).addMatcher(hasRehydrationInfo, (draft, action) => {
1623
+ const {
1624
+ provided
1625
+ } = extractRehydrationInfo(action);
1626
+ for (const [type, incomingTags] of Object.entries(provided.tags ?? {})) {
1627
+ for (const [id, cacheKeys] of Object.entries(incomingTags)) {
1628
+ const subscribedQueries = (draft.tags[type] ??= {})[id || "__internal_without_id"] ??= [];
1629
+ for (const queryCacheKey of cacheKeys) {
1630
+ const alreadySubscribed = subscribedQueries.includes(queryCacheKey);
1631
+ if (!alreadySubscribed) {
1632
+ subscribedQueries.push(queryCacheKey);
1633
+ }
1634
+ draft.keys[queryCacheKey] = provided.keys[queryCacheKey];
1635
+ }
1636
+ }
1637
+ }
1638
+ }).addMatcher((0, import_toolkit.isAnyOf)((0, import_toolkit.isFulfilled)(queryThunk), (0, import_toolkit.isRejectedWithValue)(queryThunk)), (draft, action) => {
1639
+ writeProvidedTagsForQueries(draft, [action]);
1640
+ }).addMatcher(querySlice.actions.cacheEntriesUpserted.match, (draft, action) => {
1641
+ const mockActions = action.payload.map(({
1642
+ queryDescription,
1643
+ value
1644
+ }) => {
1645
+ return {
1646
+ type: "UNKNOWN",
1647
+ payload: value,
1648
+ meta: {
1649
+ requestStatus: "fulfilled",
1650
+ requestId: "UNKNOWN",
1651
+ arg: queryDescription
1652
+ }
1653
+ };
1654
+ });
1655
+ writeProvidedTagsForQueries(draft, mockActions);
1656
+ });
1657
+ }
1658
+ });
1659
+ function removeCacheKeyFromTags(draft, queryCacheKey) {
1660
+ const existingTags = getCurrent(draft.keys[queryCacheKey] ?? []);
1661
+ for (const tag of existingTags) {
1662
+ const tagType = tag.type;
1663
+ const tagId = tag.id ?? "__internal_without_id";
1664
+ const tagSubscriptions = draft.tags[tagType]?.[tagId];
1665
+ if (tagSubscriptions) {
1666
+ draft.tags[tagType][tagId] = getCurrent(tagSubscriptions).filter((qc) => qc !== queryCacheKey);
1667
+ }
1668
+ }
1669
+ delete draft.keys[queryCacheKey];
1670
+ }
1671
+ function writeProvidedTagsForQueries(draft, actions3) {
1672
+ const providedByEntries = actions3.map((action) => {
1673
+ const providedTags = calculateProvidedByThunk(action, "providesTags", definitions, assertTagType);
1674
+ const {
1675
+ queryCacheKey
1676
+ } = action.meta.arg;
1677
+ return {
1678
+ queryCacheKey,
1679
+ providedTags
1680
+ };
1681
+ });
1682
+ invalidationSlice.caseReducers.updateProvidedBy(draft, invalidationSlice.actions.updateProvidedBy(providedByEntries));
1683
+ }
1684
+ const subscriptionSlice = (0, import_toolkit.createSlice)({
1685
+ name: `${reducerPath}/subscriptions`,
1686
+ initialState,
1687
+ reducers: {
1688
+ updateSubscriptionOptions(d, a) {
1689
+ },
1690
+ unsubscribeQueryResult(d, a) {
1691
+ },
1692
+ internal_getRTKQSubscriptions() {
1693
+ }
1694
+ }
1695
+ });
1696
+ const internalSubscriptionsSlice = (0, import_toolkit.createSlice)({
1697
+ name: `${reducerPath}/internalSubscriptions`,
1698
+ initialState,
1699
+ reducers: {
1700
+ subscriptionsUpdated: {
1701
+ reducer(state, action) {
1702
+ return (0, import_immer.applyPatches)(state, action.payload);
1703
+ },
1704
+ prepare: (0, import_toolkit.prepareAutoBatched)()
1705
+ }
1706
+ }
1707
+ });
1708
+ const configSlice = (0, import_toolkit.createSlice)({
1709
+ name: `${reducerPath}/config`,
1710
+ initialState: {
1711
+ online: isOnline(),
1712
+ focused: isDocumentVisible(),
1713
+ middlewareRegistered: false,
1714
+ ...config
1715
+ },
1716
+ reducers: {
1717
+ middlewareRegistered(state, {
1718
+ payload
1719
+ }) {
1720
+ state.middlewareRegistered = state.middlewareRegistered === "conflict" || apiUid !== payload ? "conflict" : true;
1721
+ }
1722
+ },
1723
+ extraReducers: (builder) => {
1724
+ builder.addCase(onOnline, (state) => {
1725
+ state.online = true;
1726
+ }).addCase(onOffline, (state) => {
1727
+ state.online = false;
1728
+ }).addCase(onFocus, (state) => {
1729
+ state.focused = true;
1730
+ }).addCase(onFocusLost, (state) => {
1731
+ state.focused = false;
1732
+ }).addMatcher(hasRehydrationInfo, (draft) => ({
1733
+ ...draft
1734
+ }));
1735
+ }
1736
+ });
1737
+ const combinedReducer = (0, import_toolkit.combineReducers)({
1738
+ queries: querySlice.reducer,
1739
+ mutations: mutationSlice.reducer,
1740
+ provided: invalidationSlice.reducer,
1741
+ subscriptions: internalSubscriptionsSlice.reducer,
1742
+ config: configSlice.reducer
1743
+ });
1744
+ const reducer = (state, action) => combinedReducer(resetApiState.match(action) ? void 0 : state, action);
1745
+ const actions2 = {
1746
+ ...configSlice.actions,
1747
+ ...querySlice.actions,
1748
+ ...subscriptionSlice.actions,
1749
+ ...internalSubscriptionsSlice.actions,
1750
+ ...mutationSlice.actions,
1751
+ ...invalidationSlice.actions,
1752
+ resetApiState
1753
+ };
1754
+ return {
1755
+ reducer,
1756
+ actions: actions2
1757
+ };
1758
+ }
1759
+
1760
+ // src/query/core/buildSelectors.ts
1761
+ var skipToken = /* @__PURE__ */ Symbol.for("RTKQ/skipToken");
1762
+ var initialSubState = {
1763
+ status: STATUS_UNINITIALIZED
1764
+ };
1765
+ var defaultQuerySubState = /* @__PURE__ */ (0, import_toolkit.createNextState)(initialSubState, () => {
1766
+ });
1767
+ var defaultMutationSubState = /* @__PURE__ */ (0, import_toolkit.createNextState)(initialSubState, () => {
1768
+ });
1769
+ function buildSelectors({
1770
+ serializeQueryArgs,
1771
+ reducerPath,
1772
+ createSelector: createSelector2
1773
+ }) {
1774
+ const selectSkippedQuery = (state) => defaultQuerySubState;
1775
+ const selectSkippedMutation = (state) => defaultMutationSubState;
1776
+ return {
1777
+ buildQuerySelector,
1778
+ buildInfiniteQuerySelector,
1779
+ buildMutationSelector,
1780
+ selectInvalidatedBy,
1781
+ selectCachedArgsForQuery,
1782
+ selectApiState,
1783
+ selectQueries,
1784
+ selectMutations,
1785
+ selectQueryEntry,
1786
+ selectConfig
1787
+ };
1788
+ function withRequestFlags(substate) {
1789
+ return {
1790
+ ...substate,
1791
+ ...getRequestStatusFlags(substate.status)
1792
+ };
1793
+ }
1794
+ function selectApiState(rootState) {
1795
+ const state = rootState[reducerPath];
1796
+ if (true) {
1797
+ if (!state) {
1798
+ if (selectApiState.triggered) return state;
1799
+ selectApiState.triggered = true;
1800
+ console.error(`Error: No data found at \`state.${reducerPath}\`. Did you forget to add the reducer to the store?`);
1801
+ }
1802
+ }
1803
+ return state;
1804
+ }
1805
+ function selectQueries(rootState) {
1806
+ return selectApiState(rootState)?.queries;
1807
+ }
1808
+ function selectQueryEntry(rootState, cacheKey) {
1809
+ return selectQueries(rootState)?.[cacheKey];
1810
+ }
1811
+ function selectMutations(rootState) {
1812
+ return selectApiState(rootState)?.mutations;
1813
+ }
1814
+ function selectConfig(rootState) {
1815
+ return selectApiState(rootState)?.config;
1816
+ }
1817
+ function buildAnyQuerySelector(endpointName, endpointDefinition, combiner) {
1818
+ return (queryArgs) => {
1819
+ if (queryArgs === skipToken) {
1820
+ return createSelector2(selectSkippedQuery, combiner);
1821
+ }
1822
+ const serializedArgs = serializeQueryArgs({
1823
+ queryArgs,
1824
+ endpointDefinition,
1825
+ endpointName
1826
+ });
1827
+ const selectQuerySubstate = (state) => selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState;
1828
+ return createSelector2(selectQuerySubstate, combiner);
1829
+ };
1830
+ }
1831
+ function buildQuerySelector(endpointName, endpointDefinition) {
1832
+ return buildAnyQuerySelector(endpointName, endpointDefinition, withRequestFlags);
1833
+ }
1834
+ function buildInfiniteQuerySelector(endpointName, endpointDefinition) {
1835
+ const {
1836
+ infiniteQueryOptions
1837
+ } = endpointDefinition;
1838
+ function withInfiniteQueryResultFlags(substate) {
1839
+ const stateWithRequestFlags = {
1840
+ ...substate,
1841
+ ...getRequestStatusFlags(substate.status)
1842
+ };
1843
+ const {
1844
+ isLoading,
1845
+ isError,
1846
+ direction
1847
+ } = stateWithRequestFlags;
1848
+ const isForward = direction === "forward";
1849
+ const isBackward = direction === "backward";
1850
+ return {
1851
+ ...stateWithRequestFlags,
1852
+ hasNextPage: getHasNextPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),
1853
+ hasPreviousPage: getHasPreviousPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),
1854
+ isFetchingNextPage: isLoading && isForward,
1855
+ isFetchingPreviousPage: isLoading && isBackward,
1856
+ isFetchNextPageError: isError && isForward,
1857
+ isFetchPreviousPageError: isError && isBackward
1858
+ };
1859
+ }
1860
+ return buildAnyQuerySelector(endpointName, endpointDefinition, withInfiniteQueryResultFlags);
1861
+ }
1862
+ function buildMutationSelector() {
1863
+ return ((id) => {
1864
+ let mutationId;
1865
+ if (typeof id === "object") {
1866
+ mutationId = getMutationCacheKey(id) ?? skipToken;
1867
+ } else {
1868
+ mutationId = id;
1869
+ }
1870
+ const selectMutationSubstate = (state) => selectApiState(state)?.mutations?.[mutationId] ?? defaultMutationSubState;
1871
+ const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;
1872
+ return createSelector2(finalSelectMutationSubstate, withRequestFlags);
1873
+ });
1874
+ }
1875
+ function selectInvalidatedBy(state, tags) {
1876
+ const apiState = state[reducerPath];
1877
+ const toInvalidate = /* @__PURE__ */ new Set();
1878
+ const finalTags = filterMap(tags, isNotNullish, expandTagDescription);
1879
+ for (const tag of finalTags) {
1880
+ const provided = apiState.provided.tags[tag.type];
1881
+ if (!provided) {
1882
+ continue;
1883
+ }
1884
+ let invalidateSubscriptions = (tag.id !== void 0 ? (
1885
+ // id given: invalidate all queries that provide this type & id
1886
+ provided[tag.id]
1887
+ ) : (
1888
+ // no id: invalidate all queries that provide this type
1889
+ Object.values(provided).flat()
1890
+ )) ?? [];
1891
+ for (const invalidate of invalidateSubscriptions) {
1892
+ toInvalidate.add(invalidate);
1893
+ }
1894
+ }
1895
+ return Array.from(toInvalidate.values()).flatMap((queryCacheKey) => {
1896
+ const querySubState = apiState.queries[queryCacheKey];
1897
+ return querySubState ? {
1898
+ queryCacheKey,
1899
+ endpointName: querySubState.endpointName,
1900
+ originalArgs: querySubState.originalArgs
1901
+ } : [];
1902
+ });
1903
+ }
1904
+ function selectCachedArgsForQuery(state, queryName) {
1905
+ return filterMap(Object.values(selectQueries(state)), (entry) => entry?.endpointName === queryName && entry.status !== STATUS_UNINITIALIZED, (entry) => entry.originalArgs);
1906
+ }
1907
+ function getHasNextPage(options, data, queryArg) {
1908
+ if (!data) return false;
1909
+ return getNextPageParam(options, data, queryArg) != null;
1910
+ }
1911
+ function getHasPreviousPage(options, data, queryArg) {
1912
+ if (!data || !options.getPreviousPageParam) return false;
1913
+ return getPreviousPageParam(options, data, queryArg) != null;
1914
+ }
1915
+ }
1916
+
1917
+ // src/query/createApi.ts
1918
+ var import_toolkit3 = require("@reduxjs/toolkit");
1919
+ var import_reselect = require("reselect");
1920
+
1921
+ // src/query/defaultSerializeQueryArgs.ts
1922
+ var cache = WeakMap ? /* @__PURE__ */ new WeakMap() : void 0;
1923
+ var defaultSerializeQueryArgs = ({
1924
+ endpointName,
1925
+ queryArgs
1926
+ }) => {
1927
+ let serialized = "";
1928
+ const cached = cache?.get(queryArgs);
1929
+ if (typeof cached === "string") {
1930
+ serialized = cached;
1931
+ } else {
1932
+ const stringified = JSON.stringify(queryArgs, (key, value) => {
1933
+ value = typeof value === "bigint" ? {
1934
+ $bigint: value.toString()
1935
+ } : value;
1936
+ value = (0, import_toolkit.isPlainObject)(value) ? Object.keys(value).sort().reduce((acc, key2) => {
1937
+ acc[key2] = value[key2];
1938
+ return acc;
1939
+ }, {}) : value;
1940
+ return value;
1941
+ });
1942
+ if ((0, import_toolkit.isPlainObject)(queryArgs)) {
1943
+ cache?.set(queryArgs, stringified);
1944
+ }
1945
+ serialized = stringified;
1946
+ }
1947
+ return `${endpointName}(${serialized})`;
1948
+ };
1949
+
1950
+ // src/query/createApi.ts
1951
+ function buildCreateApi(...modules) {
1952
+ return function baseCreateApi(options) {
1953
+ const extractRehydrationInfo = (0, import_reselect.weakMapMemoize)((action) => options.extractRehydrationInfo?.(action, {
1954
+ reducerPath: options.reducerPath ?? "api"
1955
+ }));
1956
+ const optionsWithDefaults = {
1957
+ reducerPath: "api",
1958
+ keepUnusedDataFor: 60,
1959
+ refetchOnMountOrArgChange: false,
1960
+ refetchOnFocus: false,
1961
+ refetchOnReconnect: false,
1962
+ invalidationBehavior: "delayed",
1963
+ ...options,
1964
+ extractRehydrationInfo,
1965
+ serializeQueryArgs(queryArgsApi) {
1966
+ let finalSerializeQueryArgs = defaultSerializeQueryArgs;
1967
+ if ("serializeQueryArgs" in queryArgsApi.endpointDefinition) {
1968
+ const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs;
1969
+ finalSerializeQueryArgs = (queryArgsApi2) => {
1970
+ const initialResult = endpointSQA(queryArgsApi2);
1971
+ if (typeof initialResult === "string") {
1972
+ return initialResult;
1973
+ } else {
1974
+ return defaultSerializeQueryArgs({
1975
+ ...queryArgsApi2,
1976
+ queryArgs: initialResult
1977
+ });
1978
+ }
1979
+ };
1980
+ } else if (options.serializeQueryArgs) {
1981
+ finalSerializeQueryArgs = options.serializeQueryArgs;
1982
+ }
1983
+ return finalSerializeQueryArgs(queryArgsApi);
1984
+ },
1985
+ tagTypes: [...options.tagTypes || []]
1986
+ };
1987
+ const context = {
1988
+ endpointDefinitions: {},
1989
+ batch(fn) {
1990
+ fn();
1991
+ },
1992
+ apiUid: (0, import_toolkit.nanoid)(),
1993
+ extractRehydrationInfo,
1994
+ hasRehydrationInfo: (0, import_reselect.weakMapMemoize)((action) => extractRehydrationInfo(action) != null)
1995
+ };
1996
+ const api = {
1997
+ injectEndpoints,
1998
+ enhanceEndpoints({
1999
+ addTagTypes,
2000
+ endpoints
2001
+ }) {
2002
+ if (addTagTypes) {
2003
+ for (const eT of addTagTypes) {
2004
+ if (!optionsWithDefaults.tagTypes.includes(eT)) {
2005
+ ;
2006
+ optionsWithDefaults.tagTypes.push(eT);
2007
+ }
2008
+ }
2009
+ }
2010
+ if (endpoints) {
2011
+ for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {
2012
+ if (typeof partialDefinition === "function") {
2013
+ partialDefinition(getEndpointDefinition(context, endpointName));
2014
+ } else {
2015
+ Object.assign(getEndpointDefinition(context, endpointName) || {}, partialDefinition);
2016
+ }
2017
+ }
2018
+ }
2019
+ return api;
2020
+ }
2021
+ };
2022
+ const initializedModules = modules.map((m) => m.init(api, optionsWithDefaults, context));
2023
+ function injectEndpoints(inject) {
2024
+ const evaluatedEndpoints = inject.endpoints({
2025
+ query: (x) => ({
2026
+ ...x,
2027
+ type: ENDPOINT_QUERY
2028
+ }),
2029
+ mutation: (x) => ({
2030
+ ...x,
2031
+ type: ENDPOINT_MUTATION
2032
+ }),
2033
+ infiniteQuery: (x) => ({
2034
+ ...x,
2035
+ type: ENDPOINT_INFINITEQUERY
2036
+ })
2037
+ });
2038
+ for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {
2039
+ if (inject.overrideExisting !== true && endpointName in context.endpointDefinitions) {
2040
+ if (inject.overrideExisting === "throw") {
2041
+ throw new Error(false ? _formatProdErrorMessage2(39) : `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``);
2042
+ } else if (typeof process !== "undefined" && true) {
2043
+ console.error(`called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``);
2044
+ }
2045
+ continue;
2046
+ }
2047
+ if (typeof process !== "undefined" && true) {
2048
+ if (isInfiniteQueryDefinition(definition)) {
2049
+ const {
2050
+ infiniteQueryOptions
2051
+ } = definition;
2052
+ const {
2053
+ maxPages,
2054
+ getPreviousPageParam: getPreviousPageParam2
2055
+ } = infiniteQueryOptions;
2056
+ if (typeof maxPages === "number") {
2057
+ if (maxPages < 1) {
2058
+ throw new Error(false ? _formatProdErrorMessage22(40) : `maxPages for endpoint '${endpointName}' must be a number greater than 0`);
2059
+ }
2060
+ if (typeof getPreviousPageParam2 !== "function") {
2061
+ throw new Error(false ? _formatProdErrorMessage3(41) : `getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`);
2062
+ }
2063
+ }
2064
+ }
2065
+ }
2066
+ context.endpointDefinitions[endpointName] = definition;
2067
+ for (const m of initializedModules) {
2068
+ m.injectEndpoint(endpointName, definition);
2069
+ }
2070
+ }
2071
+ return api;
2072
+ }
2073
+ return api.injectEndpoints({
2074
+ endpoints: options.endpoints
2075
+ });
2076
+ };
2077
+ }
2078
+
2079
+ // src/query/fakeBaseQuery.ts
2080
+ var import_toolkit4 = require("@reduxjs/toolkit");
2081
+ var _NEVER = /* @__PURE__ */ Symbol();
2082
+ function fakeBaseQuery() {
2083
+ return function() {
2084
+ throw new Error(false ? _formatProdErrorMessage4(33) : "When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.");
2085
+ };
2086
+ }
2087
+
2088
+ // src/query/tsHelpers.ts
2089
+ function assertCast(v) {
2090
+ }
2091
+ function safeAssign(target, ...args) {
2092
+ return Object.assign(target, ...args);
2093
+ }
2094
+
2095
+ // src/query/core/buildMiddleware/batchActions.ts
2096
+ var buildBatchedActionsHandler = ({
2097
+ api,
2098
+ queryThunk,
2099
+ internalState,
2100
+ mwApi
2101
+ }) => {
2102
+ const subscriptionsPrefix = `${api.reducerPath}/subscriptions`;
2103
+ let previousSubscriptions = null;
2104
+ let updateSyncTimer = null;
2105
+ const {
2106
+ updateSubscriptionOptions,
2107
+ unsubscribeQueryResult
2108
+ } = api.internalActions;
2109
+ const actuallyMutateSubscriptions = (currentSubscriptions, action) => {
2110
+ if (updateSubscriptionOptions.match(action)) {
2111
+ const {
2112
+ queryCacheKey,
2113
+ requestId,
2114
+ options
2115
+ } = action.payload;
2116
+ const sub = currentSubscriptions.get(queryCacheKey);
2117
+ if (sub?.has(requestId)) {
2118
+ sub.set(requestId, options);
2119
+ }
2120
+ return true;
2121
+ }
2122
+ if (unsubscribeQueryResult.match(action)) {
2123
+ const {
2124
+ queryCacheKey,
2125
+ requestId
2126
+ } = action.payload;
2127
+ const sub = currentSubscriptions.get(queryCacheKey);
2128
+ if (sub) {
2129
+ sub.delete(requestId);
2130
+ }
2131
+ return true;
2132
+ }
2133
+ if (api.internalActions.removeQueryResult.match(action)) {
2134
+ currentSubscriptions.delete(action.payload.queryCacheKey);
2135
+ return true;
2136
+ }
2137
+ if (queryThunk.pending.match(action)) {
2138
+ const {
2139
+ meta: {
2140
+ arg,
2141
+ requestId
2142
+ }
2143
+ } = action;
2144
+ const substate = getOrInsertComputed(currentSubscriptions, arg.queryCacheKey, createNewMap);
2145
+ if (arg.subscribe) {
2146
+ substate.set(requestId, arg.subscriptionOptions ?? substate.get(requestId) ?? {});
2147
+ }
2148
+ return true;
2149
+ }
2150
+ let mutated = false;
2151
+ if (queryThunk.rejected.match(action)) {
2152
+ const {
2153
+ meta: {
2154
+ condition,
2155
+ arg,
2156
+ requestId
2157
+ }
2158
+ } = action;
2159
+ if (condition && arg.subscribe) {
2160
+ const substate = getOrInsertComputed(currentSubscriptions, arg.queryCacheKey, createNewMap);
2161
+ substate.set(requestId, arg.subscriptionOptions ?? substate.get(requestId) ?? {});
2162
+ mutated = true;
2163
+ }
2164
+ }
2165
+ return mutated;
2166
+ };
2167
+ const getSubscriptions = () => internalState.currentSubscriptions;
2168
+ const getSubscriptionCount = (queryCacheKey) => {
2169
+ const subscriptions = getSubscriptions();
2170
+ const subscriptionsForQueryArg = subscriptions.get(queryCacheKey);
2171
+ return subscriptionsForQueryArg?.size ?? 0;
2172
+ };
2173
+ const isRequestSubscribed = (queryCacheKey, requestId) => {
2174
+ const subscriptions = getSubscriptions();
2175
+ return !!subscriptions?.get(queryCacheKey)?.get(requestId);
2176
+ };
2177
+ const subscriptionSelectors = {
2178
+ getSubscriptions,
2179
+ getSubscriptionCount,
2180
+ isRequestSubscribed
2181
+ };
2182
+ function serializeSubscriptions(currentSubscriptions) {
2183
+ return JSON.parse(JSON.stringify(Object.fromEntries([...currentSubscriptions].map(([k, v]) => [k, Object.fromEntries(v)]))));
2184
+ }
2185
+ return (action, mwApi2) => {
2186
+ if (!previousSubscriptions) {
2187
+ previousSubscriptions = serializeSubscriptions(internalState.currentSubscriptions);
2188
+ }
2189
+ if (api.util.resetApiState.match(action)) {
2190
+ previousSubscriptions = {};
2191
+ internalState.currentSubscriptions.clear();
2192
+ updateSyncTimer = null;
2193
+ return [true, false];
2194
+ }
2195
+ if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {
2196
+ return [false, subscriptionSelectors];
2197
+ }
2198
+ const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);
2199
+ let actionShouldContinue = true;
2200
+ if (false) {
2201
+ return [false, internalState.currentPolls];
2202
+ }
2203
+ if (didMutate) {
2204
+ if (!updateSyncTimer) {
2205
+ updateSyncTimer = setTimeout(() => {
2206
+ const newSubscriptions = serializeSubscriptions(internalState.currentSubscriptions);
2207
+ const [, patches] = (0, import_immer.produceWithPatches)(previousSubscriptions, () => newSubscriptions);
2208
+ mwApi2.next(api.internalActions.subscriptionsUpdated(patches));
2209
+ previousSubscriptions = newSubscriptions;
2210
+ updateSyncTimer = null;
2211
+ }, 500);
2212
+ }
2213
+ const isSubscriptionSliceAction = typeof action.type == "string" && !!action.type.startsWith(subscriptionsPrefix);
2214
+ const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;
2215
+ actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;
2216
+ }
2217
+ return [actionShouldContinue, false];
2218
+ };
2219
+ };
2220
+
2221
+ // src/query/core/buildMiddleware/cacheCollection.ts
2222
+ var THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2147483647 / 1e3 - 1;
2223
+ var buildCacheCollectionHandler = ({
2224
+ reducerPath,
2225
+ api,
2226
+ queryThunk,
2227
+ context,
2228
+ internalState,
2229
+ selectors: {
2230
+ selectQueryEntry,
2231
+ selectConfig
2232
+ },
2233
+ getRunningQueryThunk,
2234
+ mwApi
2235
+ }) => {
2236
+ const {
2237
+ removeQueryResult,
2238
+ unsubscribeQueryResult,
2239
+ cacheEntriesUpserted
2240
+ } = api.internalActions;
2241
+ const canTriggerUnsubscribe = (0, import_toolkit.isAnyOf)(unsubscribeQueryResult.match, queryThunk.fulfilled, queryThunk.rejected, cacheEntriesUpserted.match);
2242
+ function anySubscriptionsRemainingForKey(queryCacheKey) {
2243
+ const subscriptions = internalState.currentSubscriptions.get(queryCacheKey);
2244
+ if (!subscriptions) {
2245
+ return false;
2246
+ }
2247
+ const hasSubscriptions = subscriptions.size > 0;
2248
+ return hasSubscriptions;
2249
+ }
2250
+ const currentRemovalTimeouts = {};
2251
+ function abortAllPromises(promiseMap) {
2252
+ for (const promise of promiseMap.values()) {
2253
+ promise?.abort?.();
2254
+ }
2255
+ }
2256
+ const handler = (action, mwApi2) => {
2257
+ const state = mwApi2.getState();
2258
+ const config = selectConfig(state);
2259
+ if (canTriggerUnsubscribe(action)) {
2260
+ let queryCacheKeys;
2261
+ if (cacheEntriesUpserted.match(action)) {
2262
+ queryCacheKeys = action.payload.map((entry) => entry.queryDescription.queryCacheKey);
2263
+ } else {
2264
+ const {
2265
+ queryCacheKey
2266
+ } = unsubscribeQueryResult.match(action) ? action.payload : action.meta.arg;
2267
+ queryCacheKeys = [queryCacheKey];
2268
+ }
2269
+ handleUnsubscribeMany(queryCacheKeys, mwApi2, config);
2270
+ }
2271
+ if (api.util.resetApiState.match(action)) {
2272
+ for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {
2273
+ if (timeout) clearTimeout(timeout);
2274
+ delete currentRemovalTimeouts[key];
2275
+ }
2276
+ abortAllPromises(internalState.runningQueries);
2277
+ abortAllPromises(internalState.runningMutations);
2278
+ }
2279
+ if (context.hasRehydrationInfo(action)) {
2280
+ const {
2281
+ queries
2282
+ } = context.extractRehydrationInfo(action);
2283
+ handleUnsubscribeMany(Object.keys(queries), mwApi2, config);
2284
+ }
2285
+ };
2286
+ function handleUnsubscribeMany(cacheKeys, api2, config) {
2287
+ const state = api2.getState();
2288
+ for (const queryCacheKey of cacheKeys) {
2289
+ const entry = selectQueryEntry(state, queryCacheKey);
2290
+ if (entry?.endpointName) {
2291
+ handleUnsubscribe(queryCacheKey, entry.endpointName, api2, config);
2292
+ }
2293
+ }
2294
+ }
2295
+ function handleUnsubscribe(queryCacheKey, endpointName, api2, config) {
2296
+ const endpointDefinition = getEndpointDefinition(context, endpointName);
2297
+ const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;
2298
+ if (keepUnusedDataFor === Infinity) {
2299
+ return;
2300
+ }
2301
+ const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));
2302
+ if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
2303
+ const currentTimeout = currentRemovalTimeouts[queryCacheKey];
2304
+ if (currentTimeout) {
2305
+ clearTimeout(currentTimeout);
2306
+ }
2307
+ currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {
2308
+ if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
2309
+ const entry = selectQueryEntry(api2.getState(), queryCacheKey);
2310
+ if (entry?.endpointName) {
2311
+ const runningQuery = api2.dispatch(getRunningQueryThunk(entry.endpointName, entry.originalArgs));
2312
+ runningQuery?.abort();
2313
+ }
2314
+ api2.dispatch(removeQueryResult({
2315
+ queryCacheKey
2316
+ }));
2317
+ }
2318
+ delete currentRemovalTimeouts[queryCacheKey];
2319
+ }, finalKeepUnusedDataFor * 1e3);
2320
+ }
2321
+ }
2322
+ return handler;
2323
+ };
2324
+
2325
+ // src/query/core/buildMiddleware/cacheLifecycle.ts
2326
+ var neverResolvedError = new Error("Promise never resolved before cacheEntryRemoved.");
2327
+ var buildCacheLifecycleHandler = ({
2328
+ api,
2329
+ reducerPath,
2330
+ context,
2331
+ queryThunk,
2332
+ mutationThunk,
2333
+ internalState,
2334
+ selectors: {
2335
+ selectQueryEntry,
2336
+ selectApiState
2337
+ }
2338
+ }) => {
2339
+ const isQueryThunk = (0, import_toolkit.isAsyncThunkAction)(queryThunk);
2340
+ const isMutationThunk = (0, import_toolkit.isAsyncThunkAction)(mutationThunk);
2341
+ const isFulfilledThunk = (0, import_toolkit.isFulfilled)(queryThunk, mutationThunk);
2342
+ const lifecycleMap = {};
2343
+ const {
2344
+ removeQueryResult,
2345
+ removeMutationResult,
2346
+ cacheEntriesUpserted
2347
+ } = api.internalActions;
2348
+ function resolveLifecycleEntry(cacheKey, data, meta) {
2349
+ const lifecycle = lifecycleMap[cacheKey];
2350
+ if (lifecycle?.valueResolved) {
2351
+ lifecycle.valueResolved({
2352
+ data,
2353
+ meta
2354
+ });
2355
+ delete lifecycle.valueResolved;
2356
+ }
2357
+ }
2358
+ function removeLifecycleEntry(cacheKey) {
2359
+ const lifecycle = lifecycleMap[cacheKey];
2360
+ if (lifecycle) {
2361
+ delete lifecycleMap[cacheKey];
2362
+ lifecycle.cacheEntryRemoved();
2363
+ }
2364
+ }
2365
+ function getActionMetaFields(action) {
2366
+ const {
2367
+ arg,
2368
+ requestId
2369
+ } = action.meta;
2370
+ const {
2371
+ endpointName,
2372
+ originalArgs
2373
+ } = arg;
2374
+ return [endpointName, originalArgs, requestId];
2375
+ }
2376
+ const handler = (action, mwApi, stateBefore) => {
2377
+ const cacheKey = getCacheKey(action);
2378
+ function checkForNewCacheKey(endpointName, cacheKey2, requestId, originalArgs) {
2379
+ const oldEntry = selectQueryEntry(stateBefore, cacheKey2);
2380
+ const newEntry = selectQueryEntry(mwApi.getState(), cacheKey2);
2381
+ if (!oldEntry && newEntry) {
2382
+ handleNewKey(endpointName, originalArgs, cacheKey2, mwApi, requestId);
2383
+ }
2384
+ }
2385
+ if (queryThunk.pending.match(action)) {
2386
+ const [endpointName, originalArgs, requestId] = getActionMetaFields(action);
2387
+ checkForNewCacheKey(endpointName, cacheKey, requestId, originalArgs);
2388
+ } else if (cacheEntriesUpserted.match(action)) {
2389
+ for (const {
2390
+ queryDescription,
2391
+ value
2392
+ } of action.payload) {
2393
+ const {
2394
+ endpointName,
2395
+ originalArgs,
2396
+ queryCacheKey
2397
+ } = queryDescription;
2398
+ checkForNewCacheKey(endpointName, queryCacheKey, action.meta.requestId, originalArgs);
2399
+ resolveLifecycleEntry(queryCacheKey, value, {});
2400
+ }
2401
+ } else if (mutationThunk.pending.match(action)) {
2402
+ const state = mwApi.getState()[reducerPath].mutations[cacheKey];
2403
+ if (state) {
2404
+ const [endpointName, originalArgs, requestId] = getActionMetaFields(action);
2405
+ handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);
2406
+ }
2407
+ } else if (isFulfilledThunk(action)) {
2408
+ resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta);
2409
+ } else if (removeQueryResult.match(action) || removeMutationResult.match(action)) {
2410
+ removeLifecycleEntry(cacheKey);
2411
+ } else if (api.util.resetApiState.match(action)) {
2412
+ for (const cacheKey2 of Object.keys(lifecycleMap)) {
2413
+ removeLifecycleEntry(cacheKey2);
2414
+ }
2415
+ }
2416
+ };
2417
+ function getCacheKey(action) {
2418
+ if (isQueryThunk(action)) return action.meta.arg.queryCacheKey;
2419
+ if (isMutationThunk(action)) {
2420
+ return action.meta.arg.fixedCacheKey ?? action.meta.requestId;
2421
+ }
2422
+ if (removeQueryResult.match(action)) return action.payload.queryCacheKey;
2423
+ if (removeMutationResult.match(action)) return getMutationCacheKey(action.payload);
2424
+ return "";
2425
+ }
2426
+ function handleNewKey(endpointName, originalArgs, queryCacheKey, mwApi, requestId) {
2427
+ const endpointDefinition = getEndpointDefinition(context, endpointName);
2428
+ const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;
2429
+ if (!onCacheEntryAdded) return;
2430
+ const lifecycle = {};
2431
+ const cacheEntryRemoved = new Promise((resolve) => {
2432
+ lifecycle.cacheEntryRemoved = resolve;
2433
+ });
2434
+ const cacheDataLoaded = Promise.race([new Promise((resolve) => {
2435
+ lifecycle.valueResolved = resolve;
2436
+ }), cacheEntryRemoved.then(() => {
2437
+ throw neverResolvedError;
2438
+ })]);
2439
+ cacheDataLoaded.catch(() => {
2440
+ });
2441
+ lifecycleMap[queryCacheKey] = lifecycle;
2442
+ const selector = api.endpoints[endpointName].select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : queryCacheKey);
2443
+ const extra = mwApi.dispatch((_, __, extra2) => extra2);
2444
+ const lifecycleApi = {
2445
+ ...mwApi,
2446
+ getCacheEntry: () => selector(mwApi.getState()),
2447
+ requestId,
2448
+ extra,
2449
+ updateCachedData: isAnyQueryDefinition(endpointDefinition) ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
2450
+ cacheDataLoaded,
2451
+ cacheEntryRemoved
2452
+ };
2453
+ const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi);
2454
+ Promise.resolve(runningHandler).catch((e) => {
2455
+ if (e === neverResolvedError) return;
2456
+ throw e;
2457
+ });
2458
+ }
2459
+ return handler;
2460
+ };
2461
+
2462
+ // src/query/core/buildMiddleware/devMiddleware.ts
2463
+ var buildDevCheckHandler = ({
2464
+ api,
2465
+ context: {
2466
+ apiUid
2467
+ },
2468
+ reducerPath
2469
+ }) => {
2470
+ return (action, mwApi) => {
2471
+ if (api.util.resetApiState.match(action)) {
2472
+ mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
2473
+ }
2474
+ if (typeof process !== "undefined" && true) {
2475
+ if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && mwApi.getState()[reducerPath]?.config?.middlewareRegistered === "conflict") {
2476
+ console.warn(`There is a mismatch between slice and middleware for the reducerPath "${reducerPath}".
2477
+ You can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === "api" ? `
2478
+ If you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ""}`);
2479
+ }
2480
+ }
2481
+ };
2482
+ };
2483
+
2484
+ // src/query/core/buildMiddleware/invalidationByTags.ts
2485
+ var buildInvalidationByTagsHandler = ({
2486
+ reducerPath,
2487
+ context,
2488
+ context: {
2489
+ endpointDefinitions
2490
+ },
2491
+ mutationThunk,
2492
+ queryThunk,
2493
+ api,
2494
+ assertTagType,
2495
+ refetchQuery,
2496
+ internalState
2497
+ }) => {
2498
+ const {
2499
+ removeQueryResult
2500
+ } = api.internalActions;
2501
+ const isThunkActionWithTags = (0, import_toolkit.isAnyOf)((0, import_toolkit.isFulfilled)(mutationThunk), (0, import_toolkit.isRejectedWithValue)(mutationThunk));
2502
+ const isQueryEnd = (0, import_toolkit.isAnyOf)((0, import_toolkit.isFulfilled)(queryThunk, mutationThunk), (0, import_toolkit.isRejected)(queryThunk, mutationThunk));
2503
+ let pendingTagInvalidations = [];
2504
+ let pendingRequestCount = 0;
2505
+ const handler = (action, mwApi) => {
2506
+ if (queryThunk.pending.match(action) || mutationThunk.pending.match(action)) {
2507
+ pendingRequestCount++;
2508
+ }
2509
+ if (isQueryEnd(action)) {
2510
+ pendingRequestCount = Math.max(0, pendingRequestCount - 1);
2511
+ }
2512
+ if (isThunkActionWithTags(action)) {
2513
+ invalidateTags(calculateProvidedByThunk(action, "invalidatesTags", endpointDefinitions, assertTagType), mwApi);
2514
+ } else if (isQueryEnd(action)) {
2515
+ invalidateTags([], mwApi);
2516
+ } else if (api.util.invalidateTags.match(action)) {
2517
+ invalidateTags(calculateProvidedBy(action.payload, void 0, void 0, void 0, void 0, assertTagType), mwApi);
2518
+ }
2519
+ };
2520
+ function hasPendingRequests() {
2521
+ return pendingRequestCount > 0;
2522
+ }
2523
+ function invalidateTags(newTags, mwApi) {
2524
+ const rootState = mwApi.getState();
2525
+ const state = rootState[reducerPath];
2526
+ pendingTagInvalidations.push(...newTags);
2527
+ if (state.config.invalidationBehavior === "delayed" && hasPendingRequests()) {
2528
+ return;
2529
+ }
2530
+ const tags = pendingTagInvalidations;
2531
+ pendingTagInvalidations = [];
2532
+ if (tags.length === 0) return;
2533
+ const toInvalidate = api.util.selectInvalidatedBy(rootState, tags);
2534
+ context.batch(() => {
2535
+ const valuesArray = Array.from(toInvalidate.values());
2536
+ for (const {
2537
+ queryCacheKey
2538
+ } of valuesArray) {
2539
+ const querySubState = state.queries[queryCacheKey];
2540
+ const subscriptionSubState = getOrInsertComputed(internalState.currentSubscriptions, queryCacheKey, createNewMap);
2541
+ if (querySubState) {
2542
+ if (subscriptionSubState.size === 0) {
2543
+ mwApi.dispatch(removeQueryResult({
2544
+ queryCacheKey
2545
+ }));
2546
+ } else if (querySubState.status !== STATUS_UNINITIALIZED) {
2547
+ mwApi.dispatch(refetchQuery(querySubState));
2548
+ }
2549
+ }
2550
+ }
2551
+ });
2552
+ }
2553
+ return handler;
2554
+ };
2555
+
2556
+ // src/query/core/buildMiddleware/polling.ts
2557
+ var buildPollingHandler = ({
2558
+ reducerPath,
2559
+ queryThunk,
2560
+ api,
2561
+ refetchQuery,
2562
+ internalState
2563
+ }) => {
2564
+ const {
2565
+ currentPolls,
2566
+ currentSubscriptions
2567
+ } = internalState;
2568
+ const pendingPollingUpdates = /* @__PURE__ */ new Set();
2569
+ let pollingUpdateTimer = null;
2570
+ const handler = (action, mwApi) => {
2571
+ if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) {
2572
+ schedulePollingUpdate(action.payload.queryCacheKey, mwApi);
2573
+ }
2574
+ if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {
2575
+ schedulePollingUpdate(action.meta.arg.queryCacheKey, mwApi);
2576
+ }
2577
+ if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {
2578
+ startNextPoll(action.meta.arg, mwApi);
2579
+ }
2580
+ if (api.util.resetApiState.match(action)) {
2581
+ clearPolls();
2582
+ if (pollingUpdateTimer) {
2583
+ clearTimeout(pollingUpdateTimer);
2584
+ pollingUpdateTimer = null;
2585
+ }
2586
+ pendingPollingUpdates.clear();
2587
+ }
2588
+ };
2589
+ function schedulePollingUpdate(queryCacheKey, api2) {
2590
+ pendingPollingUpdates.add(queryCacheKey);
2591
+ if (!pollingUpdateTimer) {
2592
+ pollingUpdateTimer = setTimeout(() => {
2593
+ for (const key of pendingPollingUpdates) {
2594
+ updatePollingInterval({
2595
+ queryCacheKey: key
2596
+ }, api2);
2597
+ }
2598
+ pendingPollingUpdates.clear();
2599
+ pollingUpdateTimer = null;
2600
+ }, 0);
2601
+ }
2602
+ }
2603
+ function startNextPoll({
2604
+ queryCacheKey
2605
+ }, api2) {
2606
+ const state = api2.getState()[reducerPath];
2607
+ const querySubState = state.queries[queryCacheKey];
2608
+ const subscriptions = currentSubscriptions.get(queryCacheKey);
2609
+ if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) return;
2610
+ const {
2611
+ lowestPollingInterval,
2612
+ skipPollingIfUnfocused
2613
+ } = findLowestPollingInterval(subscriptions);
2614
+ if (!Number.isFinite(lowestPollingInterval)) return;
2615
+ const currentPoll = currentPolls.get(queryCacheKey);
2616
+ if (currentPoll?.timeout) {
2617
+ clearTimeout(currentPoll.timeout);
2618
+ currentPoll.timeout = void 0;
2619
+ }
2620
+ const nextPollTimestamp = Date.now() + lowestPollingInterval;
2621
+ currentPolls.set(queryCacheKey, {
2622
+ nextPollTimestamp,
2623
+ pollingInterval: lowestPollingInterval,
2624
+ timeout: setTimeout(() => {
2625
+ if (state.config.focused || !skipPollingIfUnfocused) {
2626
+ api2.dispatch(refetchQuery(querySubState));
2627
+ }
2628
+ startNextPoll({
2629
+ queryCacheKey
2630
+ }, api2);
2631
+ }, lowestPollingInterval)
2632
+ });
2633
+ }
2634
+ function updatePollingInterval({
2635
+ queryCacheKey
2636
+ }, api2) {
2637
+ const state = api2.getState()[reducerPath];
2638
+ const querySubState = state.queries[queryCacheKey];
2639
+ const subscriptions = currentSubscriptions.get(queryCacheKey);
2640
+ if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {
2641
+ return;
2642
+ }
2643
+ const {
2644
+ lowestPollingInterval
2645
+ } = findLowestPollingInterval(subscriptions);
2646
+ if (false) {
2647
+ const updateCounters = currentPolls.pollUpdateCounters ??= {};
2648
+ updateCounters[queryCacheKey] ??= 0;
2649
+ updateCounters[queryCacheKey]++;
2650
+ }
2651
+ if (!Number.isFinite(lowestPollingInterval)) {
2652
+ cleanupPollForKey(queryCacheKey);
2653
+ return;
2654
+ }
2655
+ const currentPoll = currentPolls.get(queryCacheKey);
2656
+ const nextPollTimestamp = Date.now() + lowestPollingInterval;
2657
+ if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {
2658
+ startNextPoll({
2659
+ queryCacheKey
2660
+ }, api2);
2661
+ }
2662
+ }
2663
+ function cleanupPollForKey(key) {
2664
+ const existingPoll = currentPolls.get(key);
2665
+ if (existingPoll?.timeout) {
2666
+ clearTimeout(existingPoll.timeout);
2667
+ }
2668
+ currentPolls.delete(key);
2669
+ }
2670
+ function clearPolls() {
2671
+ for (const key of currentPolls.keys()) {
2672
+ cleanupPollForKey(key);
2673
+ }
2674
+ }
2675
+ function findLowestPollingInterval(subscribers = /* @__PURE__ */ new Map()) {
2676
+ let skipPollingIfUnfocused = false;
2677
+ let lowestPollingInterval = Number.POSITIVE_INFINITY;
2678
+ for (const entry of subscribers.values()) {
2679
+ if (!!entry.pollingInterval) {
2680
+ lowestPollingInterval = Math.min(entry.pollingInterval, lowestPollingInterval);
2681
+ skipPollingIfUnfocused = entry.skipPollingIfUnfocused || skipPollingIfUnfocused;
2682
+ }
2683
+ }
2684
+ return {
2685
+ lowestPollingInterval,
2686
+ skipPollingIfUnfocused
2687
+ };
2688
+ }
2689
+ return handler;
2690
+ };
2691
+
2692
+ // src/query/core/buildMiddleware/queryLifecycle.ts
2693
+ var buildQueryLifecycleHandler = ({
2694
+ api,
2695
+ context,
2696
+ queryThunk,
2697
+ mutationThunk
2698
+ }) => {
2699
+ const isPendingThunk = (0, import_toolkit.isPending)(queryThunk, mutationThunk);
2700
+ const isRejectedThunk = (0, import_toolkit.isRejected)(queryThunk, mutationThunk);
2701
+ const isFulfilledThunk = (0, import_toolkit.isFulfilled)(queryThunk, mutationThunk);
2702
+ const lifecycleMap = {};
2703
+ const handler = (action, mwApi) => {
2704
+ if (isPendingThunk(action)) {
2705
+ const {
2706
+ requestId,
2707
+ arg: {
2708
+ endpointName,
2709
+ originalArgs
2710
+ }
2711
+ } = action.meta;
2712
+ const endpointDefinition = getEndpointDefinition(context, endpointName);
2713
+ const onQueryStarted = endpointDefinition?.onQueryStarted;
2714
+ if (onQueryStarted) {
2715
+ const lifecycle = {};
2716
+ const queryFulfilled = new Promise((resolve, reject) => {
2717
+ lifecycle.resolve = resolve;
2718
+ lifecycle.reject = reject;
2719
+ });
2720
+ queryFulfilled.catch(() => {
2721
+ });
2722
+ lifecycleMap[requestId] = lifecycle;
2723
+ const selector = api.endpoints[endpointName].select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : requestId);
2724
+ const extra = mwApi.dispatch((_, __, extra2) => extra2);
2725
+ const lifecycleApi = {
2726
+ ...mwApi,
2727
+ getCacheEntry: () => selector(mwApi.getState()),
2728
+ requestId,
2729
+ extra,
2730
+ updateCachedData: isAnyQueryDefinition(endpointDefinition) ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
2731
+ queryFulfilled
2732
+ };
2733
+ onQueryStarted(originalArgs, lifecycleApi);
2734
+ }
2735
+ } else if (isFulfilledThunk(action)) {
2736
+ const {
2737
+ requestId,
2738
+ baseQueryMeta
2739
+ } = action.meta;
2740
+ lifecycleMap[requestId]?.resolve({
2741
+ data: action.payload,
2742
+ meta: baseQueryMeta
2743
+ });
2744
+ delete lifecycleMap[requestId];
2745
+ } else if (isRejectedThunk(action)) {
2746
+ const {
2747
+ requestId,
2748
+ rejectedWithValue,
2749
+ baseQueryMeta
2750
+ } = action.meta;
2751
+ lifecycleMap[requestId]?.reject({
2752
+ error: action.payload ?? action.error,
2753
+ isUnhandledError: !rejectedWithValue,
2754
+ meta: baseQueryMeta
2755
+ });
2756
+ delete lifecycleMap[requestId];
2757
+ }
2758
+ };
2759
+ return handler;
2760
+ };
2761
+
2762
+ // src/query/core/buildMiddleware/windowEventHandling.ts
2763
+ var buildWindowEventHandler = ({
2764
+ reducerPath,
2765
+ context,
2766
+ api,
2767
+ refetchQuery,
2768
+ internalState
2769
+ }) => {
2770
+ const {
2771
+ removeQueryResult
2772
+ } = api.internalActions;
2773
+ const handler = (action, mwApi) => {
2774
+ if (onFocus.match(action)) {
2775
+ refetchValidQueries(mwApi, "refetchOnFocus");
2776
+ }
2777
+ if (onOnline.match(action)) {
2778
+ refetchValidQueries(mwApi, "refetchOnReconnect");
2779
+ }
2780
+ };
2781
+ function refetchValidQueries(api2, type) {
2782
+ const state = api2.getState()[reducerPath];
2783
+ const queries = state.queries;
2784
+ const subscriptions = internalState.currentSubscriptions;
2785
+ context.batch(() => {
2786
+ for (const queryCacheKey of subscriptions.keys()) {
2787
+ const querySubState = queries[queryCacheKey];
2788
+ const subscriptionSubState = subscriptions.get(queryCacheKey);
2789
+ if (!subscriptionSubState || !querySubState) continue;
2790
+ const values = [...subscriptionSubState.values()];
2791
+ const shouldRefetch = values.some((sub) => sub[type] === true) || values.every((sub) => sub[type] === void 0) && state.config[type];
2792
+ if (shouldRefetch) {
2793
+ if (subscriptionSubState.size === 0) {
2794
+ api2.dispatch(removeQueryResult({
2795
+ queryCacheKey
2796
+ }));
2797
+ } else if (querySubState.status !== STATUS_UNINITIALIZED) {
2798
+ api2.dispatch(refetchQuery(querySubState));
2799
+ }
2800
+ }
2801
+ }
2802
+ });
2803
+ }
2804
+ return handler;
2805
+ };
2806
+
2807
+ // src/query/core/buildMiddleware/index.ts
2808
+ function buildMiddleware(input) {
2809
+ const {
2810
+ reducerPath,
2811
+ queryThunk,
2812
+ api,
2813
+ context,
2814
+ getInternalState
2815
+ } = input;
2816
+ const {
2817
+ apiUid
2818
+ } = context;
2819
+ const actions2 = {
2820
+ invalidateTags: (0, import_toolkit.createAction)(`${reducerPath}/invalidateTags`)
2821
+ };
2822
+ const isThisApiSliceAction = (action) => action.type.startsWith(`${reducerPath}/`);
2823
+ const handlerBuilders = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler];
2824
+ const middleware = (mwApi) => {
2825
+ let initialized2 = false;
2826
+ const internalState = getInternalState(mwApi.dispatch);
2827
+ const builderArgs = {
2828
+ ...input,
2829
+ internalState,
2830
+ refetchQuery,
2831
+ isThisApiSliceAction,
2832
+ mwApi
2833
+ };
2834
+ const handlers = handlerBuilders.map((build) => build(builderArgs));
2835
+ const batchedActionsHandler = buildBatchedActionsHandler(builderArgs);
2836
+ const windowEventsHandler = buildWindowEventHandler(builderArgs);
2837
+ return (next) => {
2838
+ return (action) => {
2839
+ if (!(0, import_toolkit.isAction)(action)) {
2840
+ return next(action);
2841
+ }
2842
+ if (!initialized2) {
2843
+ initialized2 = true;
2844
+ mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
2845
+ }
2846
+ const mwApiWithNext = {
2847
+ ...mwApi,
2848
+ next
2849
+ };
2850
+ const stateBefore = mwApi.getState();
2851
+ const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore);
2852
+ let res;
2853
+ if (actionShouldContinue) {
2854
+ res = next(action);
2855
+ } else {
2856
+ res = internalProbeResult;
2857
+ }
2858
+ if (!!mwApi.getState()[reducerPath]) {
2859
+ windowEventsHandler(action, mwApiWithNext, stateBefore);
2860
+ if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {
2861
+ for (const handler of handlers) {
2862
+ handler(action, mwApiWithNext, stateBefore);
2863
+ }
2864
+ }
2865
+ }
2866
+ return res;
2867
+ };
2868
+ };
2869
+ };
2870
+ return {
2871
+ middleware,
2872
+ actions: actions2
2873
+ };
2874
+ function refetchQuery(querySubState) {
2875
+ return input.api.endpoints[querySubState.endpointName].initiate(querySubState.originalArgs, {
2876
+ subscribe: false,
2877
+ forceRefetch: true
2878
+ });
2879
+ }
2880
+ }
2881
+
2882
+ // src/query/core/module.ts
2883
+ var coreModuleName = /* @__PURE__ */ Symbol();
2884
+ var coreModule = ({
2885
+ createSelector: createSelector2 = import_toolkit.createSelector
2886
+ } = {}) => ({
2887
+ name: coreModuleName,
2888
+ init(api, {
2889
+ baseQuery,
2890
+ tagTypes,
2891
+ reducerPath,
2892
+ serializeQueryArgs,
2893
+ keepUnusedDataFor,
2894
+ refetchOnMountOrArgChange,
2895
+ refetchOnFocus,
2896
+ refetchOnReconnect,
2897
+ invalidationBehavior,
2898
+ onSchemaFailure,
2899
+ catchSchemaFailure,
2900
+ skipSchemaValidation
2901
+ }, context) {
2902
+ (0, import_immer.enablePatches)();
2903
+ assertCast(serializeQueryArgs);
2904
+ const assertTagType = (tag) => {
2905
+ if (typeof process !== "undefined" && true) {
2906
+ if (!tagTypes.includes(tag.type)) {
2907
+ console.error(`Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`);
2908
+ }
2909
+ }
2910
+ return tag;
2911
+ };
2912
+ Object.assign(api, {
2913
+ reducerPath,
2914
+ endpoints: {},
2915
+ internalActions: {
2916
+ onOnline,
2917
+ onOffline,
2918
+ onFocus,
2919
+ onFocusLost
2920
+ },
2921
+ util: {}
2922
+ });
2923
+ const selectors = buildSelectors({
2924
+ serializeQueryArgs,
2925
+ reducerPath,
2926
+ createSelector: createSelector2
2927
+ });
2928
+ const {
2929
+ selectInvalidatedBy,
2930
+ selectCachedArgsForQuery,
2931
+ buildQuerySelector,
2932
+ buildInfiniteQuerySelector,
2933
+ buildMutationSelector
2934
+ } = selectors;
2935
+ safeAssign(api.util, {
2936
+ selectInvalidatedBy,
2937
+ selectCachedArgsForQuery
2938
+ });
2939
+ const {
2940
+ queryThunk,
2941
+ infiniteQueryThunk,
2942
+ mutationThunk,
2943
+ patchQueryData,
2944
+ updateQueryData,
2945
+ upsertQueryData,
2946
+ prefetch,
2947
+ buildMatchThunkActions
2948
+ } = buildThunks({
2949
+ baseQuery,
2950
+ reducerPath,
2951
+ context,
2952
+ api,
2953
+ serializeQueryArgs,
2954
+ assertTagType,
2955
+ selectors,
2956
+ onSchemaFailure,
2957
+ catchSchemaFailure,
2958
+ skipSchemaValidation
2959
+ });
2960
+ const {
2961
+ reducer,
2962
+ actions: sliceActions
2963
+ } = buildSlice({
2964
+ context,
2965
+ queryThunk,
2966
+ infiniteQueryThunk,
2967
+ mutationThunk,
2968
+ serializeQueryArgs,
2969
+ reducerPath,
2970
+ assertTagType,
2971
+ config: {
2972
+ refetchOnFocus,
2973
+ refetchOnReconnect,
2974
+ refetchOnMountOrArgChange,
2975
+ keepUnusedDataFor,
2976
+ reducerPath,
2977
+ invalidationBehavior
2978
+ }
2979
+ });
2980
+ safeAssign(api.util, {
2981
+ patchQueryData,
2982
+ updateQueryData,
2983
+ upsertQueryData,
2984
+ prefetch,
2985
+ resetApiState: sliceActions.resetApiState,
2986
+ upsertQueryEntries: sliceActions.cacheEntriesUpserted
2987
+ });
2988
+ safeAssign(api.internalActions, sliceActions);
2989
+ const internalStateMap = /* @__PURE__ */ new WeakMap();
2990
+ const getInternalState = (dispatch) => {
2991
+ const state = getOrInsertComputed(internalStateMap, dispatch, () => ({
2992
+ currentSubscriptions: /* @__PURE__ */ new Map(),
2993
+ currentPolls: /* @__PURE__ */ new Map(),
2994
+ runningQueries: /* @__PURE__ */ new Map(),
2995
+ runningMutations: /* @__PURE__ */ new Map()
2996
+ }));
2997
+ return state;
2998
+ };
2999
+ const {
3000
+ buildInitiateQuery,
3001
+ buildInitiateInfiniteQuery,
3002
+ buildInitiateMutation,
3003
+ getRunningMutationThunk,
3004
+ getRunningMutationsThunk,
3005
+ getRunningQueriesThunk,
3006
+ getRunningQueryThunk
3007
+ } = buildInitiate({
3008
+ queryThunk,
3009
+ mutationThunk,
3010
+ infiniteQueryThunk,
3011
+ api,
3012
+ serializeQueryArgs,
3013
+ context,
3014
+ getInternalState
3015
+ });
3016
+ safeAssign(api.util, {
3017
+ getRunningMutationThunk,
3018
+ getRunningMutationsThunk,
3019
+ getRunningQueryThunk,
3020
+ getRunningQueriesThunk
3021
+ });
3022
+ const {
3023
+ middleware,
3024
+ actions: middlewareActions
3025
+ } = buildMiddleware({
3026
+ reducerPath,
3027
+ context,
3028
+ queryThunk,
3029
+ mutationThunk,
3030
+ infiniteQueryThunk,
3031
+ api,
3032
+ assertTagType,
3033
+ selectors,
3034
+ getRunningQueryThunk,
3035
+ getInternalState
3036
+ });
3037
+ safeAssign(api.util, middlewareActions);
3038
+ safeAssign(api, {
3039
+ reducer,
3040
+ middleware
3041
+ });
3042
+ return {
3043
+ name: coreModuleName,
3044
+ injectEndpoint(endpointName, definition) {
3045
+ const anyApi = api;
3046
+ const endpoint = anyApi.endpoints[endpointName] ??= {};
3047
+ if (isQueryDefinition(definition)) {
3048
+ safeAssign(endpoint, {
3049
+ name: endpointName,
3050
+ select: buildQuerySelector(endpointName, definition),
3051
+ initiate: buildInitiateQuery(endpointName, definition)
3052
+ }, buildMatchThunkActions(queryThunk, endpointName));
3053
+ }
3054
+ if (isMutationDefinition(definition)) {
3055
+ safeAssign(endpoint, {
3056
+ name: endpointName,
3057
+ select: buildMutationSelector(),
3058
+ initiate: buildInitiateMutation(endpointName)
3059
+ }, buildMatchThunkActions(mutationThunk, endpointName));
3060
+ }
3061
+ if (isInfiniteQueryDefinition(definition)) {
3062
+ safeAssign(endpoint, {
3063
+ name: endpointName,
3064
+ select: buildInfiniteQuerySelector(endpointName, definition),
3065
+ initiate: buildInitiateInfiniteQuery(endpointName, definition)
3066
+ }, buildMatchThunkActions(queryThunk, endpointName));
3067
+ }
3068
+ }
3069
+ };
3070
+ }
3071
+ });
3072
+
3073
+ // src/query/core/index.ts
3074
+ var createApi = /* @__PURE__ */ buildCreateApi(coreModule());
3075
+ // Annotate the CommonJS export names for ESM import in node:
3076
+ 0 && (module.exports = {
3077
+ NamedSchemaError,
3078
+ QueryStatus,
3079
+ _NEVER,
3080
+ buildCreateApi,
3081
+ copyWithStructuralSharing,
3082
+ coreModule,
3083
+ coreModuleName,
3084
+ createApi,
3085
+ defaultSerializeQueryArgs,
3086
+ fakeBaseQuery,
3087
+ fetchBaseQuery,
3088
+ retry,
3089
+ setupListeners,
3090
+ skipToken
3091
+ });
3092
+ //# sourceMappingURL=rtk-query.development.cjs.map