UNPKG

94.7 kBJavaScriptView Raw
1var __generator = (this && this.__generator) || function (thisArg, body) {
2 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
3 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
4 function verb(n) { return function (v) { return step([n, v]); }; }
5 function step(op) {
6 if (f) throw new TypeError("Generator is already executing.");
7 while (_) try {
8 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
9 if (y = 0, t) op = [op[0] & 2, t.value];
10 switch (op[0]) {
11 case 0: case 1: t = op; break;
12 case 4: _.label++; return { value: op[1], done: false };
13 case 5: _.label++; y = op[1]; op = [0]; continue;
14 case 7: op = _.ops.pop(); _.trys.pop(); continue;
15 default:
16 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
17 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
18 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
19 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
20 if (t[2]) _.ops.pop();
21 _.trys.pop(); continue;
22 }
23 op = body.call(thisArg, _);
24 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
25 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
26 }
27};
28var __spreadArray = (this && this.__spreadArray) || function (to, from) {
29 for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
30 to[j] = from[i];
31 return to;
32};
33var __defProp = Object.defineProperty;
34var __defProps = Object.defineProperties;
35var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
36var __getOwnPropSymbols = Object.getOwnPropertySymbols;
37var __hasOwnProp = Object.prototype.hasOwnProperty;
38var __propIsEnum = Object.prototype.propertyIsEnumerable;
39var __defNormalProp = function (obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; };
40var __spreadValues = function (a, b) {
41 for (var prop in b || (b = {}))
42 if (__hasOwnProp.call(b, prop))
43 __defNormalProp(a, prop, b[prop]);
44 if (__getOwnPropSymbols)
45 for (var _i = 0, _e = __getOwnPropSymbols(b); _i < _e.length; _i++) {
46 var prop = _e[_i];
47 if (__propIsEnum.call(b, prop))
48 __defNormalProp(a, prop, b[prop]);
49 }
50 return a;
51};
52var __spreadProps = function (a, b) { return __defProps(a, __getOwnPropDescs(b)); };
53var __objRest = function (source, exclude) {
54 var target = {};
55 for (var prop in source)
56 if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
57 target[prop] = source[prop];
58 if (source != null && __getOwnPropSymbols)
59 for (var _i = 0, _e = __getOwnPropSymbols(source); _i < _e.length; _i++) {
60 var prop = _e[_i];
61 if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
62 target[prop] = source[prop];
63 }
64 return target;
65};
66var __async = function (__this, __arguments, generator) {
67 return new Promise(function (resolve, reject) {
68 var fulfilled = function (value) {
69 try {
70 step(generator.next(value));
71 }
72 catch (e) {
73 reject(e);
74 }
75 };
76 var rejected = function (value) {
77 try {
78 step(generator.throw(value));
79 }
80 catch (e) {
81 reject(e);
82 }
83 };
84 var step = function (x) { return x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); };
85 step((generator = generator.apply(__this, __arguments)).next());
86 });
87};
88// src/query/core/apiState.ts
89var QueryStatus;
90(function (QueryStatus2) {
91 QueryStatus2["uninitialized"] = "uninitialized";
92 QueryStatus2["pending"] = "pending";
93 QueryStatus2["fulfilled"] = "fulfilled";
94 QueryStatus2["rejected"] = "rejected";
95})(QueryStatus || (QueryStatus = {}));
96function getRequestStatusFlags(status) {
97 return {
98 status: status,
99 isUninitialized: status === QueryStatus.uninitialized,
100 isLoading: status === QueryStatus.pending,
101 isSuccess: status === QueryStatus.fulfilled,
102 isError: status === QueryStatus.rejected
103 };
104}
105// src/query/utils/isAbsoluteUrl.ts
106function isAbsoluteUrl(url) {
107 return new RegExp("(^|:)//").test(url);
108}
109// src/query/utils/joinUrls.ts
110var withoutTrailingSlash = function (url) { return url.replace(/\/$/, ""); };
111var withoutLeadingSlash = function (url) { return url.replace(/^\//, ""); };
112function joinUrls(base, url) {
113 if (!base) {
114 return url;
115 }
116 if (!url) {
117 return base;
118 }
119 if (isAbsoluteUrl(url)) {
120 return url;
121 }
122 base = withoutTrailingSlash(base);
123 url = withoutLeadingSlash(url);
124 return base + "/" + url;
125}
126// src/query/utils/flatten.ts
127var flatten = function (arr) { return [].concat.apply([], arr); };
128// src/query/utils/isOnline.ts
129function isOnline() {
130 return typeof navigator === "undefined" ? true : navigator.onLine === void 0 ? true : navigator.onLine;
131}
132// src/query/utils/isDocumentVisible.ts
133function isDocumentVisible() {
134 if (typeof document === "undefined") {
135 return true;
136 }
137 return document.visibilityState !== "hidden";
138}
139// src/query/utils/copyWithStructuralSharing.ts
140import { isPlainObject as _iPO } from "@reduxjs/toolkit";
141var isPlainObject = _iPO;
142function copyWithStructuralSharing(oldObj, newObj) {
143 if (oldObj === newObj || !(isPlainObject(oldObj) && isPlainObject(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {
144 return newObj;
145 }
146 var newKeys = Object.keys(newObj);
147 var oldKeys = Object.keys(oldObj);
148 var isSameObject = newKeys.length === oldKeys.length;
149 var mergeObj = Array.isArray(newObj) ? [] : {};
150 for (var _i = 0, newKeys_1 = newKeys; _i < newKeys_1.length; _i++) {
151 var key = newKeys_1[_i];
152 mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);
153 if (isSameObject)
154 isSameObject = oldObj[key] === mergeObj[key];
155 }
156 return isSameObject ? oldObj : mergeObj;
157}
158// src/query/fetchBaseQuery.ts
159import { isPlainObject as isPlainObject2 } from "@reduxjs/toolkit";
160var defaultFetchFn = function () {
161 var args = [];
162 for (var _i = 0; _i < arguments.length; _i++) {
163 args[_i] = arguments[_i];
164 }
165 return fetch.apply(void 0, args);
166};
167var defaultValidateStatus = function (response) { return response.status >= 200 && response.status <= 299; };
168var isJsonContentType = function (headers) {
169 var _a, _b;
170 return (_b = (_a = headers.get("content-type")) == null ? void 0 : _a.trim()) == null ? void 0 : _b.startsWith("application/json");
171};
172var handleResponse = function (response, responseHandler) { return __async(void 0, null, function () {
173 var text;
174 return __generator(this, function (_e) {
175 switch (_e.label) {
176 case 0:
177 if (typeof responseHandler === "function") {
178 return [2 /*return*/, responseHandler(response)];
179 }
180 if (responseHandler === "text") {
181 return [2 /*return*/, response.text()];
182 }
183 if (!(responseHandler === "json")) return [3 /*break*/, 2];
184 return [4 /*yield*/, response.text()];
185 case 1:
186 text = _e.sent();
187 return [2 /*return*/, text.length ? JSON.parse(text) : null];
188 case 2: return [2 /*return*/];
189 }
190 });
191}); };
192function stripUndefined(obj) {
193 if (!isPlainObject2(obj)) {
194 return obj;
195 }
196 var copy = __spreadValues({}, obj);
197 for (var _i = 0, _e = Object.entries(copy); _i < _e.length; _i++) {
198 var _f = _e[_i], k = _f[0], v = _f[1];
199 if (typeof v === "undefined")
200 delete copy[k];
201 }
202 return copy;
203}
204function fetchBaseQuery(_a) {
205 var _this = this;
206 if (_a === void 0) { _a = {}; }
207 var _b = _a, baseUrl = _b.baseUrl, _e = _b.prepareHeaders, prepareHeaders = _e === void 0 ? function (x) { return x; } : _e, _f = _b.fetchFn, fetchFn = _f === void 0 ? defaultFetchFn : _f, paramsSerializer = _b.paramsSerializer, baseFetchOptions = __objRest(_b, [
208 "baseUrl",
209 "prepareHeaders",
210 "fetchFn",
211 "paramsSerializer"
212 ]);
213 if (typeof fetch === "undefined" && fetchFn === defaultFetchFn) {
214 console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.");
215 }
216 return function (arg, api) { return __async(_this, null, function () {
217 var signal, getState, extra, endpoint, forced, type, meta, _a2, url, _e, method, _f, headers, _g, body, _h, params, _j, responseHandler, _k, validateStatus, rest, config, _l, isJsonifiable, divider, query, request, requestClone, response, e_1, responseClone, resultData, responseText, handleResponseError_1, e_2;
218 return __generator(this, function (_m) {
219 switch (_m.label) {
220 case 0:
221 signal = api.signal, getState = api.getState, extra = api.extra, endpoint = api.endpoint, forced = api.forced, type = api.type;
222 _a2 = typeof arg == "string" ? { url: arg } : arg, url = _a2.url, _e = _a2.method, method = _e === void 0 ? "GET" : _e, _f = _a2.headers, headers = _f === void 0 ? new Headers({}) : _f, _g = _a2.body, body = _g === void 0 ? void 0 : _g, _h = _a2.params, params = _h === void 0 ? void 0 : _h, _j = _a2.responseHandler, responseHandler = _j === void 0 ? "json" : _j, _k = _a2.validateStatus, validateStatus = _k === void 0 ? defaultValidateStatus : _k, rest = __objRest(_a2, [
223 "url",
224 "method",
225 "headers",
226 "body",
227 "params",
228 "responseHandler",
229 "validateStatus"
230 ]);
231 config = __spreadValues(__spreadProps(__spreadValues({}, baseFetchOptions), {
232 method: method,
233 signal: signal,
234 body: body
235 }), rest);
236 _l = config;
237 return [4 /*yield*/, prepareHeaders(new Headers(stripUndefined(headers)), { getState: getState, extra: extra, endpoint: endpoint, forced: forced, type: type })];
238 case 1:
239 _l.headers = _m.sent();
240 isJsonifiable = function (body2) { return typeof body2 === "object" && (isPlainObject2(body2) || Array.isArray(body2) || typeof body2.toJSON === "function"); };
241 if (!config.headers.has("content-type") && isJsonifiable(body)) {
242 config.headers.set("content-type", "application/json");
243 }
244 if (body && isJsonContentType(config.headers)) {
245 config.body = JSON.stringify(body);
246 }
247 if (params) {
248 divider = ~url.indexOf("?") ? "&" : "?";
249 query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params));
250 url += divider + query;
251 }
252 url = joinUrls(baseUrl, url);
253 request = new Request(url, config);
254 requestClone = request.clone();
255 meta = { request: requestClone };
256 _m.label = 2;
257 case 2:
258 _m.trys.push([2, 4, , 5]);
259 return [4 /*yield*/, fetchFn(request)];
260 case 3:
261 response = _m.sent();
262 return [3 /*break*/, 5];
263 case 4:
264 e_1 = _m.sent();
265 return [2 /*return*/, { error: { status: "FETCH_ERROR", error: String(e_1) }, meta: meta }];
266 case 5:
267 responseClone = response.clone();
268 meta.response = responseClone;
269 responseText = "";
270 _m.label = 6;
271 case 6:
272 _m.trys.push([6, 8, , 9]);
273 return [4 /*yield*/, Promise.all([
274 handleResponse(response, responseHandler).then(function (r) { return resultData = r; }, function (e) { return handleResponseError_1 = e; }),
275 responseClone.text().then(function (r) { return responseText = r; }, function () {
276 })
277 ])];
278 case 7:
279 _m.sent();
280 if (handleResponseError_1)
281 throw handleResponseError_1;
282 return [3 /*break*/, 9];
283 case 8:
284 e_2 = _m.sent();
285 return [2 /*return*/, {
286 error: {
287 status: "PARSING_ERROR",
288 originalStatus: response.status,
289 data: responseText,
290 error: String(e_2)
291 },
292 meta: meta
293 }];
294 case 9: return [2 /*return*/, validateStatus(response, resultData) ? {
295 data: resultData,
296 meta: meta
297 } : {
298 error: {
299 status: response.status,
300 data: resultData
301 },
302 meta: meta
303 }];
304 }
305 });
306 }); };
307}
308// src/query/HandledError.ts
309var HandledError = /** @class */ (function () {
310 function HandledError(value, meta) {
311 if (meta === void 0) { meta = void 0; }
312 this.value = value;
313 this.meta = meta;
314 }
315 return HandledError;
316}());
317// src/query/retry.ts
318function defaultBackoff(attempt, maxRetries) {
319 if (attempt === void 0) { attempt = 0; }
320 if (maxRetries === void 0) { maxRetries = 5; }
321 return __async(this, null, function () {
322 var attempts, timeout;
323 return __generator(this, function (_e) {
324 switch (_e.label) {
325 case 0:
326 attempts = Math.min(attempt, maxRetries);
327 timeout = ~~((Math.random() + 0.4) * (300 << attempts));
328 return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(function (res) { return resolve(res); }, timeout); })];
329 case 1:
330 _e.sent();
331 return [2 /*return*/];
332 }
333 });
334 });
335}
336function fail(e) {
337 throw Object.assign(new HandledError({ error: e }), {
338 throwImmediately: true
339 });
340}
341var retryWithBackoff = function (baseQuery, defaultOptions) { return function (args, api, extraOptions) { return __async(void 0, null, function () {
342 var options, retry2, result, e_3;
343 return __generator(this, function (_e) {
344 switch (_e.label) {
345 case 0:
346 options = __spreadValues(__spreadValues({
347 maxRetries: 5,
348 backoff: defaultBackoff
349 }, defaultOptions), extraOptions);
350 retry2 = 0;
351 _e.label = 1;
352 case 1:
353 if (!true) return [3 /*break*/, 7];
354 _e.label = 2;
355 case 2:
356 _e.trys.push([2, 4, , 6]);
357 return [4 /*yield*/, baseQuery(args, api, extraOptions)];
358 case 3:
359 result = _e.sent();
360 if (result.error) {
361 throw new HandledError(result);
362 }
363 return [2 /*return*/, result];
364 case 4:
365 e_3 = _e.sent();
366 retry2++;
367 if (e_3.throwImmediately || retry2 > options.maxRetries) {
368 if (e_3 instanceof HandledError) {
369 return [2 /*return*/, e_3.value];
370 }
371 throw e_3;
372 }
373 return [4 /*yield*/, options.backoff(retry2, options.maxRetries)];
374 case 5:
375 _e.sent();
376 return [3 /*break*/, 6];
377 case 6: return [3 /*break*/, 1];
378 case 7: return [2 /*return*/];
379 }
380 });
381}); }; };
382var retry = /* @__PURE__ */ Object.assign(retryWithBackoff, { fail: fail });
383// src/query/core/setupListeners.ts
384import { createAction } from "@reduxjs/toolkit";
385var onFocus = /* @__PURE__ */ createAction("__rtkq/focused");
386var onFocusLost = /* @__PURE__ */ createAction("__rtkq/unfocused");
387var onOnline = /* @__PURE__ */ createAction("__rtkq/online");
388var onOffline = /* @__PURE__ */ createAction("__rtkq/offline");
389var initialized = false;
390function setupListeners(dispatch, customHandler) {
391 function defaultHandler() {
392 var handleFocus = function () { return dispatch(onFocus()); };
393 var handleFocusLost = function () { return dispatch(onFocusLost()); };
394 var handleOnline = function () { return dispatch(onOnline()); };
395 var handleOffline = function () { return dispatch(onOffline()); };
396 var handleVisibilityChange = function () {
397 if (window.document.visibilityState === "visible") {
398 handleFocus();
399 }
400 else {
401 handleFocusLost();
402 }
403 };
404 if (!initialized) {
405 if (typeof window !== "undefined" && window.addEventListener) {
406 window.addEventListener("visibilitychange", handleVisibilityChange, false);
407 window.addEventListener("focus", handleFocus, false);
408 window.addEventListener("online", handleOnline, false);
409 window.addEventListener("offline", handleOffline, false);
410 initialized = true;
411 }
412 }
413 var unsubscribe = function () {
414 window.removeEventListener("focus", handleFocus);
415 window.removeEventListener("visibilitychange", handleVisibilityChange);
416 window.removeEventListener("online", handleOnline);
417 window.removeEventListener("offline", handleOffline);
418 initialized = false;
419 };
420 return unsubscribe;
421 }
422 return customHandler ? customHandler(dispatch, { onFocus: onFocus, onFocusLost: onFocusLost, onOffline: onOffline, onOnline: onOnline }) : defaultHandler();
423}
424// src/query/core/buildSelectors.ts
425import { createNextState, createSelector } from "@reduxjs/toolkit";
426// src/query/endpointDefinitions.ts
427var DefinitionType;
428(function (DefinitionType2) {
429 DefinitionType2["query"] = "query";
430 DefinitionType2["mutation"] = "mutation";
431})(DefinitionType || (DefinitionType = {}));
432function isQueryDefinition(e) {
433 return e.type === DefinitionType.query;
434}
435function isMutationDefinition(e) {
436 return e.type === DefinitionType.mutation;
437}
438function calculateProvidedBy(description, result, error, queryArg, meta, assertTagTypes) {
439 if (isFunction(description)) {
440 return description(result, error, queryArg, meta).map(expandTagDescription).map(assertTagTypes);
441 }
442 if (Array.isArray(description)) {
443 return description.map(expandTagDescription).map(assertTagTypes);
444 }
445 return [];
446}
447function isFunction(t) {
448 return typeof t === "function";
449}
450function expandTagDescription(description) {
451 return typeof description === "string" ? { type: description } : description;
452}
453// src/query/core/buildSlice.ts
454import { combineReducers, createAction as createAction2, createSlice, isAnyOf, isFulfilled as isFulfilled2, isRejectedWithValue as isRejectedWithValue2 } from "@reduxjs/toolkit";
455// src/query/core/buildThunks.ts
456import { isAllOf, isFulfilled, isPending, isRejected, isRejectedWithValue } from "@reduxjs/toolkit";
457import { isDraftable, produceWithPatches } from "immer";
458import { createAsyncThunk } from "@reduxjs/toolkit";
459function defaultTransformResponse(baseQueryReturnValue) {
460 return baseQueryReturnValue;
461}
462function buildThunks(_e) {
463 var _this = this;
464 var reducerPath = _e.reducerPath, baseQuery = _e.baseQuery, endpointDefinitions = _e.context.endpointDefinitions, serializeQueryArgs = _e.serializeQueryArgs, api = _e.api;
465 var patchQueryData = function (endpointName, args, patches) { return function (dispatch) {
466 var endpointDefinition = endpointDefinitions[endpointName];
467 dispatch(api.internalActions.queryResultPatched({
468 queryCacheKey: serializeQueryArgs({
469 queryArgs: args,
470 endpointDefinition: endpointDefinition,
471 endpointName: endpointName
472 }),
473 patches: patches
474 }));
475 }; };
476 var updateQueryData = function (endpointName, args, updateRecipe) { return function (dispatch, getState) {
477 var _e, _f;
478 var currentState = api.endpoints[endpointName].select(args)(getState());
479 var ret = {
480 patches: [],
481 inversePatches: [],
482 undo: function () { return dispatch(api.util.patchQueryData(endpointName, args, ret.inversePatches)); }
483 };
484 if (currentState.status === QueryStatus.uninitialized) {
485 return ret;
486 }
487 if ("data" in currentState) {
488 if (isDraftable(currentState.data)) {
489 var _g = produceWithPatches(currentState.data, updateRecipe), patches = _g[1], inversePatches = _g[2];
490 (_e = ret.patches).push.apply(_e, patches);
491 (_f = ret.inversePatches).push.apply(_f, inversePatches);
492 }
493 else {
494 var value = updateRecipe(currentState.data);
495 ret.patches.push({ op: "replace", path: [], value: value });
496 ret.inversePatches.push({
497 op: "replace",
498 path: [],
499 value: currentState.data
500 });
501 }
502 }
503 dispatch(api.util.patchQueryData(endpointName, args, ret.patches));
504 return ret;
505 }; };
506 var executeEndpoint = function (_0, _1) { return __async(_this, [_0, _1], function (arg, _e) {
507 var endpointDefinition, transformResponse, result, baseQueryApi_1, what, err, _i, _f, key, _g, error_1;
508 var signal = _e.signal, rejectWithValue = _e.rejectWithValue, fulfillWithValue = _e.fulfillWithValue, dispatch = _e.dispatch, getState = _e.getState, extra = _e.extra;
509 return __generator(this, function (_h) {
510 switch (_h.label) {
511 case 0:
512 endpointDefinition = endpointDefinitions[arg.endpointName];
513 _h.label = 1;
514 case 1:
515 _h.trys.push([1, 7, , 8]);
516 transformResponse = defaultTransformResponse;
517 result = void 0;
518 baseQueryApi_1 = {
519 signal: signal,
520 dispatch: dispatch,
521 getState: getState,
522 extra: extra,
523 endpoint: arg.endpointName,
524 type: arg.type,
525 forced: arg.type === "query" ? isForcedQuery(arg, getState()) : void 0
526 };
527 if (!endpointDefinition.query) return [3 /*break*/, 3];
528 return [4 /*yield*/, baseQuery(endpointDefinition.query(arg.originalArgs), baseQueryApi_1, endpointDefinition.extraOptions)];
529 case 2:
530 result = _h.sent();
531 if (endpointDefinition.transformResponse) {
532 transformResponse = endpointDefinition.transformResponse;
533 }
534 return [3 /*break*/, 5];
535 case 3: return [4 /*yield*/, endpointDefinition.queryFn(arg.originalArgs, baseQueryApi_1, endpointDefinition.extraOptions, function (arg2) { return baseQuery(arg2, baseQueryApi_1, endpointDefinition.extraOptions); })];
536 case 4:
537 result = _h.sent();
538 _h.label = 5;
539 case 5:
540 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
541 what = endpointDefinition.query ? "`baseQuery`" : "`queryFn`";
542 err = void 0;
543 if (!result) {
544 err = what + " did not return anything.";
545 }
546 else if (typeof result !== "object") {
547 err = what + " did not return an object.";
548 }
549 else if (result.error && result.data) {
550 err = what + " returned an object containing both `error` and `result`.";
551 }
552 else if (result.error === void 0 && result.data === void 0) {
553 err = what + " returned an object containing neither a valid `error` and `result`. At least one of them should not be `undefined`";
554 }
555 else {
556 for (_i = 0, _f = Object.keys(result); _i < _f.length; _i++) {
557 key = _f[_i];
558 if (key !== "error" && key !== "data" && key !== "meta") {
559 err = "The object returned by " + what + " has the unknown property " + key + ".";
560 break;
561 }
562 }
563 }
564 if (err) {
565 console.error("Error encountered handling the endpoint " + arg.endpointName + ".\n " + err + "\n It needs to return an object with either the shape `{ data: <value> }` or `{ error: <value> }` that may contain an optional `meta` property.\n Object returned was:", result);
566 }
567 }
568 if (result.error)
569 throw new HandledError(result.error, result.meta);
570 _g = fulfillWithValue;
571 return [4 /*yield*/, transformResponse(result.data, result.meta, arg.originalArgs)];
572 case 6: return [2 /*return*/, _g.apply(void 0, [_h.sent(), {
573 fulfilledTimeStamp: Date.now(),
574 baseQueryMeta: result.meta
575 }])];
576 case 7:
577 error_1 = _h.sent();
578 if (error_1 instanceof HandledError) {
579 return [2 /*return*/, rejectWithValue(error_1.value, { baseQueryMeta: error_1.meta })];
580 }
581 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
582 console.error("An unhandled error occured processing a request for the endpoint \"" + arg.endpointName + "\".\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".", error_1);
583 }
584 else {
585 console.error(error_1);
586 }
587 throw error_1;
588 case 8: return [2 /*return*/];
589 }
590 });
591 }); };
592 function isForcedQuery(arg, state) {
593 var _a, _b, _c, _d;
594 var requestState = (_b = (_a = state[reducerPath]) == null ? void 0 : _a.queries) == null ? void 0 : _b[arg.queryCacheKey];
595 var baseFetchOnMountOrArgChange = (_c = state[reducerPath]) == null ? void 0 : _c.config.refetchOnMountOrArgChange;
596 var fulfilledVal = requestState == null ? void 0 : requestState.fulfilledTimeStamp;
597 var refetchVal = (_d = arg.forceRefetch) != null ? _d : arg.subscribe && baseFetchOnMountOrArgChange;
598 if (refetchVal) {
599 return refetchVal === true || (Number(new Date()) - Number(fulfilledVal)) / 1e3 >= refetchVal;
600 }
601 return false;
602 }
603 var queryThunk = createAsyncThunk(reducerPath + "/executeQuery", executeEndpoint, {
604 getPendingMeta: function () {
605 return { startedTimeStamp: Date.now() };
606 },
607 condition: function (arg, _e) {
608 var getState = _e.getState;
609 var _a, _b;
610 var state = getState();
611 var requestState = (_b = (_a = state[reducerPath]) == null ? void 0 : _a.queries) == null ? void 0 : _b[arg.queryCacheKey];
612 var fulfilledVal = requestState == null ? void 0 : requestState.fulfilledTimeStamp;
613 if ((requestState == null ? void 0 : requestState.status) === "pending")
614 return false;
615 if (isForcedQuery(arg, state))
616 return true;
617 if (fulfilledVal)
618 return false;
619 return true;
620 },
621 dispatchConditionRejection: true
622 });
623 var mutationThunk = createAsyncThunk(reducerPath + "/executeMutation", executeEndpoint, {
624 getPendingMeta: function () {
625 return { startedTimeStamp: Date.now() };
626 }
627 });
628 var hasTheForce = function (options) { return "force" in options; };
629 var hasMaxAge = function (options) { return "ifOlderThan" in options; };
630 var prefetch = function (endpointName, arg, options) { return function (dispatch, getState) {
631 var force = hasTheForce(options) && options.force;
632 var maxAge = hasMaxAge(options) && options.ifOlderThan;
633 var queryAction = function (force2) {
634 if (force2 === void 0) { force2 = true; }
635 return api.endpoints[endpointName].initiate(arg, { forceRefetch: force2 });
636 };
637 var latestStateValue = api.endpoints[endpointName].select(arg)(getState());
638 if (force) {
639 dispatch(queryAction());
640 }
641 else if (maxAge) {
642 var lastFulfilledTs = latestStateValue == null ? void 0 : latestStateValue.fulfilledTimeStamp;
643 if (!lastFulfilledTs) {
644 dispatch(queryAction());
645 return;
646 }
647 var shouldRetrigger = (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1e3 >= maxAge;
648 if (shouldRetrigger) {
649 dispatch(queryAction());
650 }
651 }
652 else {
653 dispatch(queryAction(false));
654 }
655 }; };
656 function matchesEndpoint(endpointName) {
657 return function (action) {
658 var _a, _b;
659 return ((_b = (_a = action == null ? void 0 : action.meta) == null ? void 0 : _a.arg) == null ? void 0 : _b.endpointName) === endpointName;
660 };
661 }
662 function buildMatchThunkActions(thunk, endpointName) {
663 return {
664 matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),
665 matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),
666 matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))
667 };
668 }
669 return {
670 queryThunk: queryThunk,
671 mutationThunk: mutationThunk,
672 prefetch: prefetch,
673 updateQueryData: updateQueryData,
674 patchQueryData: patchQueryData,
675 buildMatchThunkActions: buildMatchThunkActions
676 };
677}
678function calculateProvidedByThunk(action, type, endpointDefinitions, assertTagType) {
679 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);
680}
681// src/query/core/buildSlice.ts
682import { applyPatches } from "immer";
683function updateQuerySubstateIfExists(state, queryCacheKey, update) {
684 var substate = state[queryCacheKey];
685 if (substate) {
686 update(substate);
687 }
688}
689function getMutationCacheKey(id) {
690 var _a;
691 return (_a = "arg" in id ? id.arg.fixedCacheKey : id.fixedCacheKey) != null ? _a : id.requestId;
692}
693function updateMutationSubstateIfExists(state, id, update) {
694 var substate = state[getMutationCacheKey(id)];
695 if (substate) {
696 update(substate);
697 }
698}
699var initialState = {};
700function buildSlice(_e) {
701 var reducerPath = _e.reducerPath, queryThunk = _e.queryThunk, mutationThunk = _e.mutationThunk, _f = _e.context, definitions = _f.endpointDefinitions, apiUid = _f.apiUid, extractRehydrationInfo = _f.extractRehydrationInfo, hasRehydrationInfo = _f.hasRehydrationInfo, assertTagType = _e.assertTagType, config = _e.config;
702 var resetApiState = createAction2(reducerPath + "/resetApiState");
703 var querySlice = createSlice({
704 name: reducerPath + "/queries",
705 initialState: initialState,
706 reducers: {
707 removeQueryResult: function (draft, _e) {
708 var queryCacheKey = _e.payload.queryCacheKey;
709 delete draft[queryCacheKey];
710 },
711 queryResultPatched: function (draft, _e) {
712 var _f = _e.payload, queryCacheKey = _f.queryCacheKey, patches = _f.patches;
713 updateQuerySubstateIfExists(draft, queryCacheKey, function (substate) {
714 substate.data = applyPatches(substate.data, patches.concat());
715 });
716 }
717 },
718 extraReducers: function (builder) {
719 builder.addCase(queryThunk.pending, function (draft, _e) {
720 var meta = _e.meta, arg = _e.meta.arg;
721 var _a, _b;
722 if (arg.subscribe) {
723 (_b = draft[_a = arg.queryCacheKey]) != null ? _b : draft[_a] = {
724 status: QueryStatus.uninitialized,
725 endpointName: arg.endpointName
726 };
727 }
728 updateQuerySubstateIfExists(draft, arg.queryCacheKey, function (substate) {
729 substate.status = QueryStatus.pending;
730 substate.requestId = meta.requestId;
731 if (arg.originalArgs !== void 0) {
732 substate.originalArgs = arg.originalArgs;
733 }
734 substate.startedTimeStamp = meta.startedTimeStamp;
735 });
736 }).addCase(queryThunk.fulfilled, function (draft, _e) {
737 var meta = _e.meta, payload = _e.payload;
738 updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, function (substate) {
739 var _a;
740 if (substate.requestId !== meta.requestId)
741 return;
742 substate.status = QueryStatus.fulfilled;
743 substate.data = ((_a = definitions[meta.arg.endpointName].structuralSharing) != null ? _a : true) ? copyWithStructuralSharing(substate.data, payload) : payload;
744 delete substate.error;
745 substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
746 });
747 }).addCase(queryThunk.rejected, function (draft, _e) {
748 var _f = _e.meta, condition = _f.condition, arg = _f.arg, requestId = _f.requestId, error = _e.error, payload = _e.payload;
749 updateQuerySubstateIfExists(draft, arg.queryCacheKey, function (substate) {
750 if (condition) {
751 }
752 else {
753 if (substate.requestId !== requestId)
754 return;
755 substate.status = QueryStatus.rejected;
756 substate.error = payload != null ? payload : error;
757 }
758 });
759 }).addMatcher(hasRehydrationInfo, function (draft, action) {
760 var queries = extractRehydrationInfo(action).queries;
761 for (var _i = 0, _e = Object.entries(queries); _i < _e.length; _i++) {
762 var _f = _e[_i], key = _f[0], entry = _f[1];
763 if ((entry == null ? void 0 : entry.status) === QueryStatus.fulfilled || (entry == null ? void 0 : entry.status) === QueryStatus.rejected) {
764 draft[key] = entry;
765 }
766 }
767 });
768 }
769 });
770 var mutationSlice = createSlice({
771 name: reducerPath + "/mutations",
772 initialState: initialState,
773 reducers: {
774 removeMutationResult: function (draft, _e) {
775 var payload = _e.payload;
776 var cacheKey = getMutationCacheKey(payload);
777 if (cacheKey in draft) {
778 delete draft[cacheKey];
779 }
780 }
781 },
782 extraReducers: function (builder) {
783 builder.addCase(mutationThunk.pending, function (draft, _e) {
784 var meta = _e.meta, _f = _e.meta, requestId = _f.requestId, arg = _f.arg, startedTimeStamp = _f.startedTimeStamp;
785 if (!arg.track)
786 return;
787 draft[getMutationCacheKey(meta)] = {
788 requestId: requestId,
789 status: QueryStatus.pending,
790 endpointName: arg.endpointName,
791 startedTimeStamp: startedTimeStamp
792 };
793 }).addCase(mutationThunk.fulfilled, function (draft, _e) {
794 var payload = _e.payload, meta = _e.meta;
795 if (!meta.arg.track)
796 return;
797 updateMutationSubstateIfExists(draft, meta, function (substate) {
798 if (substate.requestId !== meta.requestId)
799 return;
800 substate.status = QueryStatus.fulfilled;
801 substate.data = payload;
802 substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
803 });
804 }).addCase(mutationThunk.rejected, function (draft, _e) {
805 var payload = _e.payload, error = _e.error, meta = _e.meta;
806 if (!meta.arg.track)
807 return;
808 updateMutationSubstateIfExists(draft, meta, function (substate) {
809 if (substate.requestId !== meta.requestId)
810 return;
811 substate.status = QueryStatus.rejected;
812 substate.error = payload != null ? payload : error;
813 });
814 }).addMatcher(hasRehydrationInfo, function (draft, action) {
815 var mutations = extractRehydrationInfo(action).mutations;
816 for (var _i = 0, _e = Object.entries(mutations); _i < _e.length; _i++) {
817 var _f = _e[_i], key = _f[0], entry = _f[1];
818 if (((entry == null ? void 0 : entry.status) === QueryStatus.fulfilled || (entry == null ? void 0 : entry.status) === QueryStatus.rejected) && key !== (entry == null ? void 0 : entry.requestId)) {
819 draft[key] = entry;
820 }
821 }
822 });
823 }
824 });
825 var invalidationSlice = createSlice({
826 name: reducerPath + "/invalidation",
827 initialState: initialState,
828 reducers: {},
829 extraReducers: function (builder) {
830 builder.addCase(querySlice.actions.removeQueryResult, function (draft, _e) {
831 var queryCacheKey = _e.payload.queryCacheKey;
832 for (var _i = 0, _f = Object.values(draft); _i < _f.length; _i++) {
833 var tagTypeSubscriptions = _f[_i];
834 for (var _g = 0, _h = Object.values(tagTypeSubscriptions); _g < _h.length; _g++) {
835 var idSubscriptions = _h[_g];
836 var foundAt = idSubscriptions.indexOf(queryCacheKey);
837 if (foundAt !== -1) {
838 idSubscriptions.splice(foundAt, 1);
839 }
840 }
841 }
842 }).addMatcher(hasRehydrationInfo, function (draft, action) {
843 var _a, _b, _c, _d;
844 var provided = extractRehydrationInfo(action).provided;
845 for (var _i = 0, _e = Object.entries(provided); _i < _e.length; _i++) {
846 var _f = _e[_i], type = _f[0], incomingTags = _f[1];
847 for (var _g = 0, _h = Object.entries(incomingTags); _g < _h.length; _g++) {
848 var _j = _h[_g], id = _j[0], cacheKeys = _j[1];
849 var subscribedQueries = (_d = (_b = (_a = draft[type]) != null ? _a : draft[type] = {})[_c = id || "__internal_without_id"]) != null ? _d : _b[_c] = [];
850 for (var _k = 0, cacheKeys_1 = cacheKeys; _k < cacheKeys_1.length; _k++) {
851 var queryCacheKey = cacheKeys_1[_k];
852 var alreadySubscribed = subscribedQueries.includes(queryCacheKey);
853 if (!alreadySubscribed) {
854 subscribedQueries.push(queryCacheKey);
855 }
856 }
857 }
858 }
859 }).addMatcher(isAnyOf(isFulfilled2(queryThunk), isRejectedWithValue2(queryThunk)), function (draft, action) {
860 var _a, _b, _c, _d;
861 var providedTags = calculateProvidedByThunk(action, "providesTags", definitions, assertTagType);
862 var queryCacheKey = action.meta.arg.queryCacheKey;
863 for (var _i = 0, providedTags_1 = providedTags; _i < providedTags_1.length; _i++) {
864 var _e = providedTags_1[_i], type = _e.type, id = _e.id;
865 var subscribedQueries = (_d = (_b = (_a = draft[type]) != null ? _a : draft[type] = {})[_c = id || "__internal_without_id"]) != null ? _d : _b[_c] = [];
866 var alreadySubscribed = subscribedQueries.includes(queryCacheKey);
867 if (!alreadySubscribed) {
868 subscribedQueries.push(queryCacheKey);
869 }
870 }
871 });
872 }
873 });
874 var subscriptionSlice = createSlice({
875 name: reducerPath + "/subscriptions",
876 initialState: initialState,
877 reducers: {
878 updateSubscriptionOptions: function (draft, _e) {
879 var _f = _e.payload, queryCacheKey = _f.queryCacheKey, requestId = _f.requestId, options = _f.options;
880 var _a;
881 if ((_a = draft == null ? void 0 : draft[queryCacheKey]) == null ? void 0 : _a[requestId]) {
882 draft[queryCacheKey][requestId] = options;
883 }
884 },
885 unsubscribeQueryResult: function (draft, _e) {
886 var _f = _e.payload, queryCacheKey = _f.queryCacheKey, requestId = _f.requestId;
887 if (draft[queryCacheKey]) {
888 delete draft[queryCacheKey][requestId];
889 }
890 }
891 },
892 extraReducers: function (builder) {
893 builder.addCase(querySlice.actions.removeQueryResult, function (draft, _e) {
894 var queryCacheKey = _e.payload.queryCacheKey;
895 delete draft[queryCacheKey];
896 }).addCase(queryThunk.pending, function (draft, _e) {
897 var _f = _e.meta, arg = _f.arg, requestId = _f.requestId;
898 var _a, _b, _c, _d;
899 if (arg.subscribe) {
900 var substate = (_b = draft[_a = arg.queryCacheKey]) != null ? _b : draft[_a] = {};
901 substate[requestId] = (_d = (_c = arg.subscriptionOptions) != null ? _c : substate[requestId]) != null ? _d : {};
902 }
903 }).addCase(queryThunk.rejected, function (draft, _e) {
904 var _f = _e.meta, condition = _f.condition, arg = _f.arg, requestId = _f.requestId, error = _e.error, payload = _e.payload;
905 var _a, _b, _c, _d;
906 if (condition && arg.subscribe) {
907 var substate = (_b = draft[_a = arg.queryCacheKey]) != null ? _b : draft[_a] = {};
908 substate[requestId] = (_d = (_c = arg.subscriptionOptions) != null ? _c : substate[requestId]) != null ? _d : {};
909 }
910 }).addMatcher(hasRehydrationInfo, function (draft) { return __spreadValues({}, draft); });
911 }
912 });
913 var configSlice = createSlice({
914 name: reducerPath + "/config",
915 initialState: __spreadValues({
916 online: isOnline(),
917 focused: isDocumentVisible(),
918 middlewareRegistered: false
919 }, config),
920 reducers: {
921 middlewareRegistered: function (state, _e) {
922 var payload = _e.payload;
923 state.middlewareRegistered = state.middlewareRegistered === "conflict" || apiUid !== payload ? "conflict" : true;
924 }
925 },
926 extraReducers: function (builder) {
927 builder.addCase(onOnline, function (state) {
928 state.online = true;
929 }).addCase(onOffline, function (state) {
930 state.online = false;
931 }).addCase(onFocus, function (state) {
932 state.focused = true;
933 }).addCase(onFocusLost, function (state) {
934 state.focused = false;
935 }).addMatcher(hasRehydrationInfo, function (draft) { return __spreadValues({}, draft); });
936 }
937 });
938 var combinedReducer = combineReducers({
939 queries: querySlice.reducer,
940 mutations: mutationSlice.reducer,
941 provided: invalidationSlice.reducer,
942 subscriptions: subscriptionSlice.reducer,
943 config: configSlice.reducer
944 });
945 var reducer = function (state, action) { return combinedReducer(resetApiState.match(action) ? void 0 : state, action); };
946 var actions = __spreadProps(__spreadValues(__spreadValues(__spreadValues(__spreadValues({}, configSlice.actions), querySlice.actions), subscriptionSlice.actions), mutationSlice.actions), {
947 unsubscribeMutationResult: mutationSlice.actions.removeMutationResult,
948 resetApiState: resetApiState
949 });
950 return { reducer: reducer, actions: actions };
951}
952// src/query/core/buildSelectors.ts
953var skipToken = /* @__PURE__ */ Symbol.for("RTKQ/skipToken");
954var skipSelector = skipToken;
955var initialSubState = {
956 status: QueryStatus.uninitialized
957};
958var defaultQuerySubState = /* @__PURE__ */ createNextState(initialSubState, function () {
959});
960var defaultMutationSubState = /* @__PURE__ */ createNextState(initialSubState, function () {
961});
962function buildSelectors(_e) {
963 var serializeQueryArgs = _e.serializeQueryArgs, reducerPath = _e.reducerPath;
964 return { buildQuerySelector: buildQuerySelector, buildMutationSelector: buildMutationSelector, selectInvalidatedBy: selectInvalidatedBy };
965 function withRequestFlags(substate) {
966 return __spreadValues(__spreadValues({}, substate), getRequestStatusFlags(substate.status));
967 }
968 function selectInternalState(rootState) {
969 var state = rootState[reducerPath];
970 if (process.env.NODE_ENV !== "production") {
971 if (!state) {
972 if (selectInternalState.triggered)
973 return state;
974 selectInternalState.triggered = true;
975 console.error("Error: No data found at `state." + reducerPath + "`. Did you forget to add the reducer to the store?");
976 }
977 }
978 return state;
979 }
980 function buildQuerySelector(endpointName, endpointDefinition) {
981 return function (queryArgs) {
982 var selectQuerySubState = createSelector(selectInternalState, function (internalState) {
983 var _a, _b;
984 return (_b = queryArgs === skipToken ? void 0 : (_a = internalState == null ? void 0 : internalState.queries) == null ? void 0 : _a[serializeQueryArgs({
985 queryArgs: queryArgs,
986 endpointDefinition: endpointDefinition,
987 endpointName: endpointName
988 })]) != null ? _b : defaultQuerySubState;
989 });
990 return createSelector(selectQuerySubState, withRequestFlags);
991 };
992 }
993 function buildMutationSelector() {
994 return function (id) {
995 var _a;
996 var mutationId;
997 if (typeof id === "object") {
998 mutationId = (_a = getMutationCacheKey(id)) != null ? _a : skipToken;
999 }
1000 else {
1001 mutationId = id;
1002 }
1003 var selectMutationSubstate = createSelector(selectInternalState, function (internalState) {
1004 var _a2, _b;
1005 return (_b = mutationId === skipToken ? void 0 : (_a2 = internalState == null ? void 0 : internalState.mutations) == null ? void 0 : _a2[mutationId]) != null ? _b : defaultMutationSubState;
1006 });
1007 return createSelector(selectMutationSubstate, withRequestFlags);
1008 };
1009 }
1010 function selectInvalidatedBy(state, tags) {
1011 var _a;
1012 var apiState = state[reducerPath];
1013 var toInvalidate = new Set();
1014 for (var _i = 0, _e = tags.map(expandTagDescription); _i < _e.length; _i++) {
1015 var tag = _e[_i];
1016 var provided = apiState.provided[tag.type];
1017 if (!provided) {
1018 continue;
1019 }
1020 var invalidateSubscriptions = (_a = tag.id !== void 0 ? provided[tag.id] : flatten(Object.values(provided))) != null ? _a : [];
1021 for (var _f = 0, invalidateSubscriptions_1 = invalidateSubscriptions; _f < invalidateSubscriptions_1.length; _f++) {
1022 var invalidate = invalidateSubscriptions_1[_f];
1023 toInvalidate.add(invalidate);
1024 }
1025 }
1026 return flatten(Array.from(toInvalidate.values()).map(function (queryCacheKey) {
1027 var querySubState = apiState.queries[queryCacheKey];
1028 return querySubState ? [
1029 {
1030 queryCacheKey: queryCacheKey,
1031 endpointName: querySubState.endpointName,
1032 originalArgs: querySubState.originalArgs
1033 }
1034 ] : [];
1035 }));
1036 }
1037}
1038// src/query/defaultSerializeQueryArgs.ts
1039import { isPlainObject as isPlainObject3 } from "@reduxjs/toolkit";
1040var defaultSerializeQueryArgs = function (_e) {
1041 var endpointName = _e.endpointName, queryArgs = _e.queryArgs;
1042 return endpointName + "(" + JSON.stringify(queryArgs, function (key, value) { return isPlainObject3(value) ? Object.keys(value).sort().reduce(function (acc, key2) {
1043 acc[key2] = value[key2];
1044 return acc;
1045 }, {}) : value; }) + ")";
1046};
1047// src/query/createApi.ts
1048import { nanoid } from "@reduxjs/toolkit";
1049import { defaultMemoize } from "reselect";
1050function buildCreateApi() {
1051 var modules = [];
1052 for (var _i = 0; _i < arguments.length; _i++) {
1053 modules[_i] = arguments[_i];
1054 }
1055 return function baseCreateApi(options) {
1056 var extractRehydrationInfo = defaultMemoize(function (action) {
1057 var _a, _b;
1058 return (_b = options.extractRehydrationInfo) == null ? void 0 : _b.call(options, action, {
1059 reducerPath: (_a = options.reducerPath) != null ? _a : "api"
1060 });
1061 });
1062 var optionsWithDefaults = __spreadProps(__spreadValues({
1063 reducerPath: "api",
1064 serializeQueryArgs: defaultSerializeQueryArgs,
1065 keepUnusedDataFor: 60,
1066 refetchOnMountOrArgChange: false,
1067 refetchOnFocus: false,
1068 refetchOnReconnect: false
1069 }, options), {
1070 extractRehydrationInfo: extractRehydrationInfo,
1071 tagTypes: __spreadArray([], options.tagTypes || [])
1072 });
1073 var context = {
1074 endpointDefinitions: {},
1075 batch: function (fn) {
1076 fn();
1077 },
1078 apiUid: nanoid(),
1079 extractRehydrationInfo: extractRehydrationInfo,
1080 hasRehydrationInfo: defaultMemoize(function (action) { return extractRehydrationInfo(action) != null; })
1081 };
1082 var api = {
1083 injectEndpoints: injectEndpoints,
1084 enhanceEndpoints: function (_e) {
1085 var addTagTypes = _e.addTagTypes, endpoints = _e.endpoints;
1086 if (addTagTypes) {
1087 for (var _i = 0, addTagTypes_1 = addTagTypes; _i < addTagTypes_1.length; _i++) {
1088 var eT = addTagTypes_1[_i];
1089 if (!optionsWithDefaults.tagTypes.includes(eT)) {
1090 optionsWithDefaults.tagTypes.push(eT);
1091 }
1092 }
1093 }
1094 if (endpoints) {
1095 for (var _f = 0, _g = Object.entries(endpoints); _f < _g.length; _f++) {
1096 var _h = _g[_f], endpointName = _h[0], partialDefinition = _h[1];
1097 if (typeof partialDefinition === "function") {
1098 partialDefinition(context.endpointDefinitions[endpointName]);
1099 }
1100 Object.assign(context.endpointDefinitions[endpointName] || {}, partialDefinition);
1101 }
1102 }
1103 return api;
1104 }
1105 };
1106 var initializedModules = modules.map(function (m) { return m.init(api, optionsWithDefaults, context); });
1107 function injectEndpoints(inject) {
1108 var evaluatedEndpoints = inject.endpoints({
1109 query: function (x) { return __spreadProps(__spreadValues({}, x), { type: DefinitionType.query }); },
1110 mutation: function (x) { return __spreadProps(__spreadValues({}, x), { type: DefinitionType.mutation }); }
1111 });
1112 for (var _i = 0, _e = Object.entries(evaluatedEndpoints); _i < _e.length; _i++) {
1113 var _f = _e[_i], endpointName = _f[0], definition = _f[1];
1114 if (!inject.overrideExisting && endpointName in context.endpointDefinitions) {
1115 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
1116 console.error("called `injectEndpoints` to override already-existing endpointName " + endpointName + " without specifying `overrideExisting: true`");
1117 }
1118 continue;
1119 }
1120 context.endpointDefinitions[endpointName] = definition;
1121 for (var _g = 0, initializedModules_1 = initializedModules; _g < initializedModules_1.length; _g++) {
1122 var m = initializedModules_1[_g];
1123 m.injectEndpoint(endpointName, definition);
1124 }
1125 }
1126 return api;
1127 }
1128 return api.injectEndpoints({ endpoints: options.endpoints });
1129 };
1130}
1131// src/query/fakeBaseQuery.ts
1132function fakeBaseQuery() {
1133 return function () {
1134 throw new Error("When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.");
1135 };
1136}
1137// src/query/core/buildMiddleware/index.ts
1138import { compose } from "redux";
1139import { createAction as createAction3 } from "@reduxjs/toolkit";
1140// src/query/core/buildMiddleware/cacheCollection.ts
1141var build = function (_e) {
1142 var reducerPath = _e.reducerPath, api = _e.api, context = _e.context;
1143 var _f = api.internalActions, removeQueryResult = _f.removeQueryResult, unsubscribeQueryResult = _f.unsubscribeQueryResult;
1144 return function (mwApi) {
1145 var currentRemovalTimeouts = {};
1146 return function (next) { return function (action) {
1147 var _a;
1148 var result = next(action);
1149 if (unsubscribeQueryResult.match(action)) {
1150 var state = mwApi.getState()[reducerPath];
1151 var queryCacheKey = action.payload.queryCacheKey;
1152 handleUnsubscribe(queryCacheKey, (_a = state.queries[queryCacheKey]) == null ? void 0 : _a.endpointName, mwApi, state.config);
1153 }
1154 if (api.util.resetApiState.match(action)) {
1155 for (var _i = 0, _e = Object.entries(currentRemovalTimeouts); _i < _e.length; _i++) {
1156 var _f = _e[_i], key = _f[0], timeout = _f[1];
1157 if (timeout)
1158 clearTimeout(timeout);
1159 delete currentRemovalTimeouts[key];
1160 }
1161 }
1162 if (context.hasRehydrationInfo(action)) {
1163 var state = mwApi.getState()[reducerPath];
1164 var queries = context.extractRehydrationInfo(action).queries;
1165 for (var _g = 0, _h = Object.entries(queries); _g < _h.length; _g++) {
1166 var _j = _h[_g], queryCacheKey = _j[0], queryState = _j[1];
1167 handleUnsubscribe(queryCacheKey, queryState == null ? void 0 : queryState.endpointName, mwApi, state.config);
1168 }
1169 }
1170 return result;
1171 }; };
1172 function handleUnsubscribe(queryCacheKey, endpointName, api2, config) {
1173 var _a;
1174 var endpointDefinition = context.endpointDefinitions[endpointName];
1175 var keepUnusedDataFor = (_a = endpointDefinition == null ? void 0 : endpointDefinition.keepUnusedDataFor) != null ? _a : config.keepUnusedDataFor;
1176 var currentTimeout = currentRemovalTimeouts[queryCacheKey];
1177 if (currentTimeout) {
1178 clearTimeout(currentTimeout);
1179 }
1180 currentRemovalTimeouts[queryCacheKey] = setTimeout(function () {
1181 var subscriptions = api2.getState()[reducerPath].subscriptions[queryCacheKey];
1182 if (!subscriptions || Object.keys(subscriptions).length === 0) {
1183 api2.dispatch(removeQueryResult({ queryCacheKey: queryCacheKey }));
1184 }
1185 delete currentRemovalTimeouts[queryCacheKey];
1186 }, keepUnusedDataFor * 1e3);
1187 }
1188 };
1189};
1190// src/query/core/buildMiddleware/invalidationByTags.ts
1191import { isAnyOf as isAnyOf2, isFulfilled as isFulfilled3, isRejectedWithValue as isRejectedWithValue3 } from "@reduxjs/toolkit";
1192var build2 = function (_e) {
1193 var reducerPath = _e.reducerPath, context = _e.context, endpointDefinitions = _e.context.endpointDefinitions, mutationThunk = _e.mutationThunk, api = _e.api, assertTagType = _e.assertTagType, refetchQuery = _e.refetchQuery;
1194 var removeQueryResult = api.internalActions.removeQueryResult;
1195 return function (mwApi) { return function (next) { return function (action) {
1196 var result = next(action);
1197 if (isAnyOf2(isFulfilled3(mutationThunk), isRejectedWithValue3(mutationThunk))(action)) {
1198 invalidateTags(calculateProvidedByThunk(action, "invalidatesTags", endpointDefinitions, assertTagType), mwApi);
1199 }
1200 if (api.util.invalidateTags.match(action)) {
1201 invalidateTags(calculateProvidedBy(action.payload, void 0, void 0, void 0, void 0, assertTagType), mwApi);
1202 }
1203 return result;
1204 }; }; };
1205 function invalidateTags(tags, mwApi) {
1206 var rootState = mwApi.getState();
1207 var state = rootState[reducerPath];
1208 var toInvalidate = api.util.selectInvalidatedBy(rootState, tags);
1209 context.batch(function () {
1210 var valuesArray = Array.from(toInvalidate.values());
1211 for (var _i = 0, valuesArray_1 = valuesArray; _i < valuesArray_1.length; _i++) {
1212 var queryCacheKey = valuesArray_1[_i].queryCacheKey;
1213 var querySubState = state.queries[queryCacheKey];
1214 var subscriptionSubState = state.subscriptions[queryCacheKey];
1215 if (querySubState && subscriptionSubState) {
1216 if (Object.keys(subscriptionSubState).length === 0) {
1217 mwApi.dispatch(removeQueryResult({
1218 queryCacheKey: queryCacheKey
1219 }));
1220 }
1221 else if (querySubState.status !== QueryStatus.uninitialized) {
1222 mwApi.dispatch(refetchQuery(querySubState, queryCacheKey));
1223 }
1224 else {
1225 }
1226 }
1227 }
1228 });
1229 }
1230};
1231// src/query/core/buildMiddleware/polling.ts
1232var build3 = function (_e) {
1233 var reducerPath = _e.reducerPath, queryThunk = _e.queryThunk, api = _e.api, refetchQuery = _e.refetchQuery;
1234 return function (mwApi) {
1235 var currentPolls = {};
1236 return function (next) { return function (action) {
1237 var result = next(action);
1238 if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) {
1239 updatePollingInterval(action.payload, mwApi);
1240 }
1241 if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {
1242 updatePollingInterval(action.meta.arg, mwApi);
1243 }
1244 if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {
1245 startNextPoll(action.meta.arg, mwApi);
1246 }
1247 if (api.util.resetApiState.match(action)) {
1248 clearPolls();
1249 }
1250 return result;
1251 }; };
1252 function startNextPoll(_e, api2) {
1253 var queryCacheKey = _e.queryCacheKey;
1254 var state = api2.getState()[reducerPath];
1255 var querySubState = state.queries[queryCacheKey];
1256 var subscriptions = state.subscriptions[queryCacheKey];
1257 if (!querySubState || querySubState.status === QueryStatus.uninitialized)
1258 return;
1259 var lowestPollingInterval = findLowestPollingInterval(subscriptions);
1260 if (!Number.isFinite(lowestPollingInterval))
1261 return;
1262 var currentPoll = currentPolls[queryCacheKey];
1263 if (currentPoll == null ? void 0 : currentPoll.timeout) {
1264 clearTimeout(currentPoll.timeout);
1265 currentPoll.timeout = void 0;
1266 }
1267 var nextPollTimestamp = Date.now() + lowestPollingInterval;
1268 var currentInterval = currentPolls[queryCacheKey] = {
1269 nextPollTimestamp: nextPollTimestamp,
1270 pollingInterval: lowestPollingInterval,
1271 timeout: setTimeout(function () {
1272 currentInterval.timeout = void 0;
1273 api2.dispatch(refetchQuery(querySubState, queryCacheKey));
1274 }, lowestPollingInterval)
1275 };
1276 }
1277 function updatePollingInterval(_e, api2) {
1278 var queryCacheKey = _e.queryCacheKey;
1279 var state = api2.getState()[reducerPath];
1280 var querySubState = state.queries[queryCacheKey];
1281 var subscriptions = state.subscriptions[queryCacheKey];
1282 if (!querySubState || querySubState.status === QueryStatus.uninitialized) {
1283 return;
1284 }
1285 var lowestPollingInterval = findLowestPollingInterval(subscriptions);
1286 if (!Number.isFinite(lowestPollingInterval)) {
1287 cleanupPollForKey(queryCacheKey);
1288 return;
1289 }
1290 var currentPoll = currentPolls[queryCacheKey];
1291 var nextPollTimestamp = Date.now() + lowestPollingInterval;
1292 if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {
1293 startNextPoll({ queryCacheKey: queryCacheKey }, api2);
1294 }
1295 }
1296 function cleanupPollForKey(key) {
1297 var existingPoll = currentPolls[key];
1298 if (existingPoll == null ? void 0 : existingPoll.timeout) {
1299 clearTimeout(existingPoll.timeout);
1300 }
1301 delete currentPolls[key];
1302 }
1303 function clearPolls() {
1304 for (var _i = 0, _e = Object.keys(currentPolls); _i < _e.length; _i++) {
1305 var key = _e[_i];
1306 cleanupPollForKey(key);
1307 }
1308 }
1309 };
1310 function findLowestPollingInterval(subscribers) {
1311 if (subscribers === void 0) { subscribers = {}; }
1312 var lowestPollingInterval = Number.POSITIVE_INFINITY;
1313 for (var _i = 0, _e = Object.values(subscribers); _i < _e.length; _i++) {
1314 var subscription = _e[_i];
1315 if (!!subscription.pollingInterval)
1316 lowestPollingInterval = Math.min(subscription.pollingInterval, lowestPollingInterval);
1317 }
1318 return lowestPollingInterval;
1319 }
1320};
1321// src/query/core/buildMiddleware/windowEventHandling.ts
1322var build4 = function (_e) {
1323 var reducerPath = _e.reducerPath, context = _e.context, api = _e.api, refetchQuery = _e.refetchQuery;
1324 var removeQueryResult = api.internalActions.removeQueryResult;
1325 return function (mwApi) { return function (next) { return function (action) {
1326 var result = next(action);
1327 if (onFocus.match(action)) {
1328 refetchValidQueries(mwApi, "refetchOnFocus");
1329 }
1330 if (onOnline.match(action)) {
1331 refetchValidQueries(mwApi, "refetchOnReconnect");
1332 }
1333 return result;
1334 }; }; };
1335 function refetchValidQueries(api2, type) {
1336 var state = api2.getState()[reducerPath];
1337 var queries = state.queries;
1338 var subscriptions = state.subscriptions;
1339 context.batch(function () {
1340 for (var _i = 0, _e = Object.keys(subscriptions); _i < _e.length; _i++) {
1341 var queryCacheKey = _e[_i];
1342 var querySubState = queries[queryCacheKey];
1343 var subscriptionSubState = subscriptions[queryCacheKey];
1344 if (!subscriptionSubState || !querySubState)
1345 continue;
1346 var shouldRefetch = Object.values(subscriptionSubState).some(function (sub) { return sub[type] === true; }) || Object.values(subscriptionSubState).every(function (sub) { return sub[type] === void 0; }) && state.config[type];
1347 if (shouldRefetch) {
1348 if (Object.keys(subscriptionSubState).length === 0) {
1349 api2.dispatch(removeQueryResult({
1350 queryCacheKey: queryCacheKey
1351 }));
1352 }
1353 else if (querySubState.status !== QueryStatus.uninitialized) {
1354 api2.dispatch(refetchQuery(querySubState, queryCacheKey));
1355 }
1356 }
1357 }
1358 });
1359 }
1360};
1361// src/query/core/buildMiddleware/cacheLifecycle.ts
1362import { isAsyncThunkAction, isFulfilled as isFulfilled4 } from "@reduxjs/toolkit";
1363var neverResolvedError = new Error("Promise never resolved before cacheEntryRemoved.");
1364var build5 = function (_e) {
1365 var api = _e.api, reducerPath = _e.reducerPath, context = _e.context, queryThunk = _e.queryThunk, mutationThunk = _e.mutationThunk;
1366 var isQueryThunk = isAsyncThunkAction(queryThunk);
1367 var isMutationThunk = isAsyncThunkAction(mutationThunk);
1368 var isFullfilledThunk = isFulfilled4(queryThunk, mutationThunk);
1369 return function (mwApi) {
1370 var lifecycleMap = {};
1371 return function (next) { return function (action) {
1372 var stateBefore = mwApi.getState();
1373 var result = next(action);
1374 var cacheKey = getCacheKey(action);
1375 if (queryThunk.pending.match(action)) {
1376 var oldState = stateBefore[reducerPath].queries[cacheKey];
1377 var state = mwApi.getState()[reducerPath].queries[cacheKey];
1378 if (!oldState && state) {
1379 handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);
1380 }
1381 }
1382 else if (mutationThunk.pending.match(action)) {
1383 var state = mwApi.getState()[reducerPath].mutations[cacheKey];
1384 if (state) {
1385 handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);
1386 }
1387 }
1388 else if (isFullfilledThunk(action)) {
1389 var lifecycle = lifecycleMap[cacheKey];
1390 if (lifecycle == null ? void 0 : lifecycle.valueResolved) {
1391 lifecycle.valueResolved({
1392 data: action.payload,
1393 meta: action.meta.baseQueryMeta
1394 });
1395 delete lifecycle.valueResolved;
1396 }
1397 }
1398 else if (api.internalActions.removeQueryResult.match(action) || api.internalActions.removeMutationResult.match(action)) {
1399 var lifecycle = lifecycleMap[cacheKey];
1400 if (lifecycle) {
1401 delete lifecycleMap[cacheKey];
1402 lifecycle.cacheEntryRemoved();
1403 }
1404 }
1405 else if (api.util.resetApiState.match(action)) {
1406 for (var _i = 0, _e = Object.entries(lifecycleMap); _i < _e.length; _i++) {
1407 var _f = _e[_i], cacheKey2 = _f[0], lifecycle = _f[1];
1408 delete lifecycleMap[cacheKey2];
1409 lifecycle.cacheEntryRemoved();
1410 }
1411 }
1412 return result;
1413 }; };
1414 function getCacheKey(action) {
1415 if (isQueryThunk(action))
1416 return action.meta.arg.queryCacheKey;
1417 if (isMutationThunk(action))
1418 return action.meta.requestId;
1419 if (api.internalActions.removeQueryResult.match(action))
1420 return action.payload.queryCacheKey;
1421 if (api.internalActions.removeMutationResult.match(action))
1422 return getMutationCacheKey(action.payload);
1423 return "";
1424 }
1425 function handleNewKey(endpointName, originalArgs, queryCacheKey, mwApi2, requestId) {
1426 var endpointDefinition = context.endpointDefinitions[endpointName];
1427 var onCacheEntryAdded = endpointDefinition == null ? void 0 : endpointDefinition.onCacheEntryAdded;
1428 if (!onCacheEntryAdded)
1429 return;
1430 var lifecycle = {};
1431 var cacheEntryRemoved = new Promise(function (resolve) {
1432 lifecycle.cacheEntryRemoved = resolve;
1433 });
1434 var cacheDataLoaded = Promise.race([
1435 new Promise(function (resolve) {
1436 lifecycle.valueResolved = resolve;
1437 }),
1438 cacheEntryRemoved.then(function () {
1439 throw neverResolvedError;
1440 })
1441 ]);
1442 cacheDataLoaded.catch(function () {
1443 });
1444 lifecycleMap[queryCacheKey] = lifecycle;
1445 var selector = api.endpoints[endpointName].select(endpointDefinition.type === DefinitionType.query ? originalArgs : queryCacheKey);
1446 var extra = mwApi2.dispatch(function (_, __, extra2) { return extra2; });
1447 var lifecycleApi = __spreadProps(__spreadValues({}, mwApi2), {
1448 getCacheEntry: function () { return selector(mwApi2.getState()); },
1449 requestId: requestId,
1450 extra: extra,
1451 updateCachedData: endpointDefinition.type === DefinitionType.query ? function (updateRecipe) { return mwApi2.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)); } : void 0,
1452 cacheDataLoaded: cacheDataLoaded,
1453 cacheEntryRemoved: cacheEntryRemoved
1454 });
1455 var runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi);
1456 Promise.resolve(runningHandler).catch(function (e) {
1457 if (e === neverResolvedError)
1458 return;
1459 throw e;
1460 });
1461 }
1462 };
1463};
1464// src/query/core/buildMiddleware/queryLifecycle.ts
1465import { isPending as isPending2, isRejected as isRejected2, isFulfilled as isFulfilled5 } from "@reduxjs/toolkit";
1466var build6 = function (_e) {
1467 var api = _e.api, context = _e.context, queryThunk = _e.queryThunk, mutationThunk = _e.mutationThunk;
1468 var isPendingThunk = isPending2(queryThunk, mutationThunk);
1469 var isRejectedThunk = isRejected2(queryThunk, mutationThunk);
1470 var isFullfilledThunk = isFulfilled5(queryThunk, mutationThunk);
1471 return function (mwApi) {
1472 var lifecycleMap = {};
1473 return function (next) { return function (action) {
1474 var _a, _b, _c;
1475 var result = next(action);
1476 if (isPendingThunk(action)) {
1477 var _e = action.meta, requestId = _e.requestId, _f = _e.arg, endpointName_1 = _f.endpointName, originalArgs_1 = _f.originalArgs;
1478 var endpointDefinition = context.endpointDefinitions[endpointName_1];
1479 var onQueryStarted = endpointDefinition == null ? void 0 : endpointDefinition.onQueryStarted;
1480 if (onQueryStarted) {
1481 var lifecycle_1 = {};
1482 var queryFulfilled = new Promise(function (resolve, reject) {
1483 lifecycle_1.resolve = resolve;
1484 lifecycle_1.reject = reject;
1485 });
1486 queryFulfilled.catch(function () {
1487 });
1488 lifecycleMap[requestId] = lifecycle_1;
1489 var selector_1 = api.endpoints[endpointName_1].select(endpointDefinition.type === DefinitionType.query ? originalArgs_1 : requestId);
1490 var extra = mwApi.dispatch(function (_, __, extra2) { return extra2; });
1491 var lifecycleApi = __spreadProps(__spreadValues({}, mwApi), {
1492 getCacheEntry: function () { return selector_1(mwApi.getState()); },
1493 requestId: requestId,
1494 extra: extra,
1495 updateCachedData: endpointDefinition.type === DefinitionType.query ? function (updateRecipe) { return mwApi.dispatch(api.util.updateQueryData(endpointName_1, originalArgs_1, updateRecipe)); } : void 0,
1496 queryFulfilled: queryFulfilled
1497 });
1498 onQueryStarted(originalArgs_1, lifecycleApi);
1499 }
1500 }
1501 else if (isFullfilledThunk(action)) {
1502 var _g = action.meta, requestId = _g.requestId, baseQueryMeta = _g.baseQueryMeta;
1503 (_a = lifecycleMap[requestId]) == null ? void 0 : _a.resolve({
1504 data: action.payload,
1505 meta: baseQueryMeta
1506 });
1507 delete lifecycleMap[requestId];
1508 }
1509 else if (isRejectedThunk(action)) {
1510 var _h = action.meta, requestId = _h.requestId, rejectedWithValue = _h.rejectedWithValue, baseQueryMeta = _h.baseQueryMeta;
1511 (_c = lifecycleMap[requestId]) == null ? void 0 : _c.reject({
1512 error: (_b = action.payload) != null ? _b : action.error,
1513 isUnhandledError: !rejectedWithValue,
1514 meta: baseQueryMeta
1515 });
1516 delete lifecycleMap[requestId];
1517 }
1518 return result;
1519 }; };
1520 };
1521};
1522// src/query/core/buildMiddleware/devMiddleware.ts
1523var build7 = function (_e) {
1524 var api = _e.api, apiUid = _e.context.apiUid, reducerPath = _e.reducerPath;
1525 return function (mwApi) {
1526 var initialized2 = false;
1527 return function (next) { return function (action) {
1528 var _a, _b;
1529 if (!initialized2) {
1530 initialized2 = true;
1531 mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
1532 }
1533 var result = next(action);
1534 if (api.util.resetApiState.match(action)) {
1535 mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
1536 }
1537 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
1538 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") {
1539 console.warn("There is a mismatch between slice and middleware for the reducerPath \"" + reducerPath + "\".\nYou can only have one api per reducer path, this will lead to crashes in various situations!" + (reducerPath === "api" ? "\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!" : ""));
1540 }
1541 }
1542 return result;
1543 }; };
1544 };
1545};
1546// src/query/core/buildMiddleware/index.ts
1547function buildMiddleware(input) {
1548 var reducerPath = input.reducerPath, queryThunk = input.queryThunk;
1549 var actions = {
1550 invalidateTags: createAction3(reducerPath + "/invalidateTags")
1551 };
1552 var middlewares = [
1553 build7,
1554 build,
1555 build2,
1556 build3,
1557 build4,
1558 build5,
1559 build6
1560 ].map(function (build8) { return build8(__spreadProps(__spreadValues({}, input), {
1561 refetchQuery: refetchQuery
1562 })); });
1563 var middleware = function (mwApi) { return function (next) {
1564 var applied = compose.apply(void 0, middlewares.map(function (middleware2) { return middleware2(mwApi); }))(next);
1565 return function (action) {
1566 if (mwApi.getState()[reducerPath]) {
1567 return applied(action);
1568 }
1569 return next(action);
1570 };
1571 }; };
1572 return { middleware: middleware, actions: actions };
1573 function refetchQuery(querySubState, queryCacheKey, override) {
1574 if (override === void 0) { override = {}; }
1575 return queryThunk(__spreadValues({
1576 type: "query",
1577 endpointName: querySubState.endpointName,
1578 originalArgs: querySubState.originalArgs,
1579 subscribe: false,
1580 forceRefetch: true,
1581 queryCacheKey: queryCacheKey
1582 }, override));
1583 }
1584}
1585// src/query/core/buildInitiate.ts
1586function buildInitiate(_e) {
1587 var serializeQueryArgs = _e.serializeQueryArgs, queryThunk = _e.queryThunk, mutationThunk = _e.mutationThunk, api = _e.api, context = _e.context;
1588 var runningQueries = {};
1589 var runningMutations = {};
1590 var _f = api.internalActions, unsubscribeQueryResult = _f.unsubscribeQueryResult, removeMutationResult = _f.removeMutationResult, updateSubscriptionOptions = _f.updateSubscriptionOptions;
1591 return {
1592 buildInitiateQuery: buildInitiateQuery,
1593 buildInitiateMutation: buildInitiateMutation,
1594 getRunningOperationPromises: getRunningOperationPromises,
1595 getRunningOperationPromise: getRunningOperationPromise
1596 };
1597 function getRunningOperationPromise(endpointName, argOrRequestId) {
1598 var endpointDefinition = context.endpointDefinitions[endpointName];
1599 if (endpointDefinition.type === DefinitionType.query) {
1600 var queryCacheKey = serializeQueryArgs({
1601 queryArgs: argOrRequestId,
1602 endpointDefinition: endpointDefinition,
1603 endpointName: endpointName
1604 });
1605 return runningQueries[queryCacheKey];
1606 }
1607 else {
1608 return runningMutations[argOrRequestId];
1609 }
1610 }
1611 function getRunningOperationPromises() {
1612 return __spreadArray(__spreadArray([], Object.values(runningQueries)), Object.values(runningMutations)).filter(function (t) { return !!t; });
1613 }
1614 function middlewareWarning(getState) {
1615 var _a, _b;
1616 if (process.env.NODE_ENV !== "production") {
1617 if (middlewareWarning.triggered)
1618 return;
1619 var registered = (_b = (_a = getState()[api.reducerPath]) == null ? void 0 : _a.config) == null ? void 0 : _b.middlewareRegistered;
1620 if (registered !== void 0) {
1621 ;
1622 middlewareWarning.triggered = true;
1623 }
1624 if (registered === false) {
1625 console.warn("Warning: Middleware for RTK-Query API at reducerPath \"" + api.reducerPath + "\" has not been added to the store.\nFeatures like automatic cache collection, automatic refetching etc. will not be available.");
1626 }
1627 }
1628 }
1629 function buildInitiateQuery(endpointName, endpointDefinition) {
1630 var queryAction = function (arg, _e) {
1631 var _f = _e === void 0 ? {} : _e, _g = _f.subscribe, subscribe = _g === void 0 ? true : _g, forceRefetch = _f.forceRefetch, subscriptionOptions = _f.subscriptionOptions;
1632 return function (dispatch, getState) {
1633 var queryCacheKey = serializeQueryArgs({
1634 queryArgs: arg,
1635 endpointDefinition: endpointDefinition,
1636 endpointName: endpointName
1637 });
1638 var thunk = queryThunk({
1639 type: "query",
1640 subscribe: subscribe,
1641 forceRefetch: forceRefetch,
1642 subscriptionOptions: subscriptionOptions,
1643 endpointName: endpointName,
1644 originalArgs: arg,
1645 queryCacheKey: queryCacheKey
1646 });
1647 var thunkResult = dispatch(thunk);
1648 middlewareWarning(getState);
1649 var requestId = thunkResult.requestId, abort = thunkResult.abort;
1650 var statePromise = Object.assign(Promise.all([runningQueries[queryCacheKey], thunkResult]).then(function () { return api.endpoints[endpointName].select(arg)(getState()); }), {
1651 arg: arg,
1652 requestId: requestId,
1653 subscriptionOptions: subscriptionOptions,
1654 queryCacheKey: queryCacheKey,
1655 abort: abort,
1656 unwrap: function () {
1657 return __async(this, null, function () {
1658 var result;
1659 return __generator(this, function (_e) {
1660 switch (_e.label) {
1661 case 0: return [4 /*yield*/, statePromise];
1662 case 1:
1663 result = _e.sent();
1664 if (result.isError) {
1665 throw result.error;
1666 }
1667 return [2 /*return*/, result.data];
1668 }
1669 });
1670 });
1671 },
1672 refetch: function () {
1673 dispatch(queryAction(arg, { subscribe: false, forceRefetch: true }));
1674 },
1675 unsubscribe: function () {
1676 if (subscribe)
1677 dispatch(unsubscribeQueryResult({
1678 queryCacheKey: queryCacheKey,
1679 requestId: requestId
1680 }));
1681 },
1682 updateSubscriptionOptions: function (options) {
1683 statePromise.subscriptionOptions = options;
1684 dispatch(updateSubscriptionOptions({
1685 endpointName: endpointName,
1686 requestId: requestId,
1687 queryCacheKey: queryCacheKey,
1688 options: options
1689 }));
1690 }
1691 });
1692 if (!runningQueries[queryCacheKey]) {
1693 runningQueries[queryCacheKey] = statePromise;
1694 statePromise.then(function () {
1695 delete runningQueries[queryCacheKey];
1696 });
1697 }
1698 return statePromise;
1699 };
1700 };
1701 return queryAction;
1702 }
1703 function buildInitiateMutation(endpointName) {
1704 return function (arg, _e) {
1705 var _f = _e === void 0 ? {} : _e, _g = _f.track, track = _g === void 0 ? true : _g, fixedCacheKey = _f.fixedCacheKey;
1706 return function (dispatch, getState) {
1707 var thunk = mutationThunk({
1708 type: "mutation",
1709 endpointName: endpointName,
1710 originalArgs: arg,
1711 track: track,
1712 fixedCacheKey: fixedCacheKey
1713 });
1714 var thunkResult = dispatch(thunk);
1715 middlewareWarning(getState);
1716 var requestId = thunkResult.requestId, abort = thunkResult.abort, unwrap = thunkResult.unwrap;
1717 var returnValuePromise = thunkResult.unwrap().then(function (data) { return ({ data: data }); }).catch(function (error) { return ({ error: error }); });
1718 var reset = function () {
1719 dispatch(removeMutationResult({ requestId: requestId, fixedCacheKey: fixedCacheKey }));
1720 };
1721 var ret = Object.assign(returnValuePromise, {
1722 arg: thunkResult.arg,
1723 requestId: requestId,
1724 abort: abort,
1725 unwrap: unwrap,
1726 unsubscribe: reset,
1727 reset: reset
1728 });
1729 runningMutations[requestId] = ret;
1730 ret.then(function () {
1731 delete runningMutations[requestId];
1732 });
1733 if (fixedCacheKey) {
1734 runningMutations[fixedCacheKey] = ret;
1735 ret.then(function () {
1736 if (runningMutations[fixedCacheKey] === ret)
1737 delete runningMutations[fixedCacheKey];
1738 });
1739 }
1740 return ret;
1741 };
1742 };
1743 }
1744}
1745// src/query/tsHelpers.ts
1746function assertCast(v) {
1747}
1748function safeAssign(target) {
1749 var args = [];
1750 for (var _i = 1; _i < arguments.length; _i++) {
1751 args[_i - 1] = arguments[_i];
1752 }
1753 Object.assign.apply(Object, __spreadArray([target], args));
1754}
1755// src/query/core/module.ts
1756import { enablePatches } from "immer";
1757var coreModuleName = /* @__PURE__ */ Symbol();
1758var coreModule = function () { return ({
1759 name: coreModuleName,
1760 init: function (api, _e, context) {
1761 var baseQuery = _e.baseQuery, tagTypes = _e.tagTypes, reducerPath = _e.reducerPath, serializeQueryArgs = _e.serializeQueryArgs, keepUnusedDataFor = _e.keepUnusedDataFor, refetchOnMountOrArgChange = _e.refetchOnMountOrArgChange, refetchOnFocus = _e.refetchOnFocus, refetchOnReconnect = _e.refetchOnReconnect;
1762 enablePatches();
1763 assertCast(serializeQueryArgs);
1764 var assertTagType = function (tag) {
1765 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
1766 if (!tagTypes.includes(tag.type)) {
1767 console.error("Tag type '" + tag.type + "' was used, but not specified in `tagTypes`!");
1768 }
1769 }
1770 return tag;
1771 };
1772 Object.assign(api, {
1773 reducerPath: reducerPath,
1774 endpoints: {},
1775 internalActions: {
1776 onOnline: onOnline,
1777 onOffline: onOffline,
1778 onFocus: onFocus,
1779 onFocusLost: onFocusLost
1780 },
1781 util: {}
1782 });
1783 var _f = buildThunks({
1784 baseQuery: baseQuery,
1785 reducerPath: reducerPath,
1786 context: context,
1787 api: api,
1788 serializeQueryArgs: serializeQueryArgs
1789 }), queryThunk = _f.queryThunk, mutationThunk = _f.mutationThunk, patchQueryData = _f.patchQueryData, updateQueryData = _f.updateQueryData, prefetch = _f.prefetch, buildMatchThunkActions = _f.buildMatchThunkActions;
1790 var _g = buildSlice({
1791 context: context,
1792 queryThunk: queryThunk,
1793 mutationThunk: mutationThunk,
1794 reducerPath: reducerPath,
1795 assertTagType: assertTagType,
1796 config: {
1797 refetchOnFocus: refetchOnFocus,
1798 refetchOnReconnect: refetchOnReconnect,
1799 refetchOnMountOrArgChange: refetchOnMountOrArgChange,
1800 keepUnusedDataFor: keepUnusedDataFor,
1801 reducerPath: reducerPath
1802 }
1803 }), reducer = _g.reducer, sliceActions = _g.actions;
1804 safeAssign(api.util, {
1805 patchQueryData: patchQueryData,
1806 updateQueryData: updateQueryData,
1807 prefetch: prefetch,
1808 resetApiState: sliceActions.resetApiState
1809 });
1810 safeAssign(api.internalActions, sliceActions);
1811 Object.defineProperty(api.util, "updateQueryResult", {
1812 get: function () {
1813 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
1814 console.warn("`api.util.updateQueryResult` has been renamed to `api.util.updateQueryData`, please change your code accordingly");
1815 }
1816 return api.util.updateQueryData;
1817 }
1818 });
1819 Object.defineProperty(api.util, "patchQueryResult", {
1820 get: function () {
1821 if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
1822 console.warn("`api.util.patchQueryResult` has been renamed to `api.util.patchQueryData`, please change your code accordingly");
1823 }
1824 return api.util.patchQueryData;
1825 }
1826 });
1827 var _h = buildMiddleware({
1828 reducerPath: reducerPath,
1829 context: context,
1830 queryThunk: queryThunk,
1831 mutationThunk: mutationThunk,
1832 api: api,
1833 assertTagType: assertTagType
1834 }), middleware = _h.middleware, middlewareActions = _h.actions;
1835 safeAssign(api.util, middlewareActions);
1836 safeAssign(api, { reducer: reducer, middleware: middleware });
1837 var _j = buildSelectors({
1838 serializeQueryArgs: serializeQueryArgs,
1839 reducerPath: reducerPath
1840 }), buildQuerySelector = _j.buildQuerySelector, buildMutationSelector = _j.buildMutationSelector, selectInvalidatedBy = _j.selectInvalidatedBy;
1841 safeAssign(api.util, { selectInvalidatedBy: selectInvalidatedBy });
1842 var _k = buildInitiate({
1843 queryThunk: queryThunk,
1844 mutationThunk: mutationThunk,
1845 api: api,
1846 serializeQueryArgs: serializeQueryArgs,
1847 context: context
1848 }), buildInitiateQuery = _k.buildInitiateQuery, buildInitiateMutation = _k.buildInitiateMutation, getRunningOperationPromises = _k.getRunningOperationPromises, getRunningOperationPromise = _k.getRunningOperationPromise;
1849 safeAssign(api.util, {
1850 getRunningOperationPromises: getRunningOperationPromises,
1851 getRunningOperationPromise: getRunningOperationPromise
1852 });
1853 return {
1854 name: coreModuleName,
1855 injectEndpoint: function (endpointName, definition) {
1856 var _a, _b;
1857 var anyApi = api;
1858 (_b = (_a = anyApi.endpoints)[endpointName]) != null ? _b : _a[endpointName] = {};
1859 if (isQueryDefinition(definition)) {
1860 safeAssign(anyApi.endpoints[endpointName], {
1861 select: buildQuerySelector(endpointName, definition),
1862 initiate: buildInitiateQuery(endpointName, definition)
1863 }, buildMatchThunkActions(queryThunk, endpointName));
1864 }
1865 else if (isMutationDefinition(definition)) {
1866 safeAssign(anyApi.endpoints[endpointName], {
1867 select: buildMutationSelector(),
1868 initiate: buildInitiateMutation(endpointName)
1869 }, buildMatchThunkActions(mutationThunk, endpointName));
1870 }
1871 }
1872 };
1873 }
1874}); };
1875// src/query/core/index.ts
1876var createApi = /* @__PURE__ */ buildCreateApi(coreModule());
1877export { QueryStatus, buildCreateApi, copyWithStructuralSharing, coreModule, createApi, fakeBaseQuery, fetchBaseQuery, retry, setupListeners, skipSelector, skipToken };
1878//# sourceMappingURL=rtk-query.esm.js.map
\No newline at end of file