rtk-query.modern.js 89 KB

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