Debian Codegraph @

install/freeipa-webui/node_modules/@reduxjs/toolkit/dist/query/rtk-query.legacy-esm.js

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