| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360 |
- // src/query/core/apiState.ts
- var QueryStatus = /* @__PURE__ */ ((QueryStatus2) => {
- QueryStatus2["uninitialized"] = "uninitialized";
- QueryStatus2["pending"] = "pending";
- QueryStatus2["fulfilled"] = "fulfilled";
- QueryStatus2["rejected"] = "rejected";
- return QueryStatus2;
- })(QueryStatus || {});
- function getRequestStatusFlags(status) {
- return {
- status,
- isUninitialized: status === "uninitialized" /* uninitialized */,
- isLoading: status === "pending" /* pending */,
- isSuccess: status === "fulfilled" /* fulfilled */,
- isError: status === "rejected" /* rejected */
- };
- }
- // src/query/utils/isAbsoluteUrl.ts
- function isAbsoluteUrl(url) {
- return new RegExp(`(^|:)//`).test(url);
- }
- // src/query/utils/joinUrls.ts
- var withoutTrailingSlash = (url) => url.replace(/\/$/, "");
- var withoutLeadingSlash = (url) => url.replace(/^\//, "");
- function joinUrls(base, url) {
- if (!base) {
- return url;
- }
- if (!url) {
- return base;
- }
- if (isAbsoluteUrl(url)) {
- return url;
- }
- const delimiter = base.endsWith("/") || !url.startsWith("?") ? "/" : "";
- base = withoutTrailingSlash(base);
- url = withoutLeadingSlash(url);
- return `${base}${delimiter}${url}`;
- }
- // src/query/utils/flatten.ts
- var flatten = (arr) => [].concat(...arr);
- // src/query/utils/isOnline.ts
- function isOnline() {
- return typeof navigator === "undefined" ? true : navigator.onLine === void 0 ? true : navigator.onLine;
- }
- // src/query/utils/isDocumentVisible.ts
- function isDocumentVisible() {
- if (typeof document === "undefined") {
- return true;
- }
- return document.visibilityState !== "hidden";
- }
- // src/query/core/rtkImports.ts
- import { createAction, createSlice, createSelector, createAsyncThunk, combineReducers, createNextState, isAnyOf, isAllOf, isAction, isPending, isRejected, isFulfilled, isRejectedWithValue, isAsyncThunkAction, prepareAutoBatched, SHOULD_AUTOBATCH, isPlainObject, nanoid } from "@reduxjs/toolkit";
- // src/query/utils/copyWithStructuralSharing.ts
- var isPlainObject2 = isPlainObject;
- function copyWithStructuralSharing(oldObj, newObj) {
- if (oldObj === newObj || !(isPlainObject2(oldObj) && isPlainObject2(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {
- return newObj;
- }
- const newKeys = Object.keys(newObj);
- const oldKeys = Object.keys(oldObj);
- let isSameObject = newKeys.length === oldKeys.length;
- const mergeObj = Array.isArray(newObj) ? [] : {};
- for (const key of newKeys) {
- mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);
- if (isSameObject)
- isSameObject = oldObj[key] === mergeObj[key];
- }
- return isSameObject ? oldObj : mergeObj;
- }
- // src/query/fetchBaseQuery.ts
- var defaultFetchFn = (...args) => fetch(...args);
- var defaultValidateStatus = (response) => response.status >= 200 && response.status <= 299;
- var defaultIsJsonContentType = (headers) => (
- /*applicat*/
- /ion\/(vnd\.api\+)?json/.test(headers.get("content-type") || "")
- );
- function stripUndefined(obj) {
- if (!isPlainObject(obj)) {
- return obj;
- }
- const copy = {
- ...obj
- };
- for (const [k, v] of Object.entries(copy)) {
- if (v === void 0)
- delete copy[k];
- }
- return copy;
- }
- function fetchBaseQuery({
- baseUrl,
- prepareHeaders = (x) => x,
- fetchFn = defaultFetchFn,
- paramsSerializer,
- isJsonContentType = defaultIsJsonContentType,
- jsonContentType = "application/json",
- jsonReplacer,
- timeout: defaultTimeout,
- responseHandler: globalResponseHandler,
- validateStatus: globalValidateStatus,
- ...baseFetchOptions
- } = {}) {
- if (typeof fetch === "undefined" && fetchFn === defaultFetchFn) {
- console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.");
- }
- return async (arg, api) => {
- const {
- signal,
- getState,
- extra,
- endpoint,
- forced,
- type
- } = api;
- let meta;
- let {
- url,
- headers = new Headers(baseFetchOptions.headers),
- params = void 0,
- responseHandler = globalResponseHandler ?? "json",
- validateStatus = globalValidateStatus ?? defaultValidateStatus,
- timeout = defaultTimeout,
- ...rest
- } = typeof arg == "string" ? {
- url: arg
- } : arg;
- let config = {
- ...baseFetchOptions,
- signal,
- ...rest
- };
- headers = new Headers(stripUndefined(headers));
- config.headers = await prepareHeaders(headers, {
- getState,
- extra,
- endpoint,
- forced,
- type
- }) || headers;
- const isJsonifiable = (body) => typeof body === "object" && (isPlainObject(body) || Array.isArray(body) || typeof body.toJSON === "function");
- if (!config.headers.has("content-type") && isJsonifiable(config.body)) {
- config.headers.set("content-type", jsonContentType);
- }
- if (isJsonifiable(config.body) && isJsonContentType(config.headers)) {
- config.body = JSON.stringify(config.body, jsonReplacer);
- }
- if (params) {
- const divider = ~url.indexOf("?") ? "&" : "?";
- const query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params));
- url += divider + query;
- }
- url = joinUrls(baseUrl, url);
- const request = new Request(url, config);
- const requestClone = new Request(url, config);
- meta = {
- request: requestClone
- };
- let response, timedOut = false, timeoutId = timeout && setTimeout(() => {
- timedOut = true;
- api.abort();
- }, timeout);
- try {
- response = await fetchFn(request);
- } catch (e) {
- return {
- error: {
- status: timedOut ? "TIMEOUT_ERROR" : "FETCH_ERROR",
- error: String(e)
- },
- meta
- };
- } finally {
- if (timeoutId)
- clearTimeout(timeoutId);
- }
- const responseClone = response.clone();
- meta.response = responseClone;
- let resultData;
- let responseText = "";
- try {
- let handleResponseError;
- await Promise.all([
- handleResponse(response, responseHandler).then((r) => resultData = r, (e) => handleResponseError = e),
- // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182
- // we *have* to "use up" both streams at the same time or they will stop running in node-fetch scenarios
- responseClone.text().then((r) => responseText = r, () => {
- })
- ]);
- if (handleResponseError)
- throw handleResponseError;
- } catch (e) {
- return {
- error: {
- status: "PARSING_ERROR",
- originalStatus: response.status,
- data: responseText,
- error: String(e)
- },
- meta
- };
- }
- return validateStatus(response, resultData) ? {
- data: resultData,
- meta
- } : {
- error: {
- status: response.status,
- data: resultData
- },
- meta
- };
- };
- async function handleResponse(response, responseHandler) {
- if (typeof responseHandler === "function") {
- return responseHandler(response);
- }
- if (responseHandler === "content-type") {
- responseHandler = isJsonContentType(response.headers) ? "json" : "text";
- }
- if (responseHandler === "json") {
- const text = await response.text();
- return text.length ? JSON.parse(text) : null;
- }
- return response.text();
- }
- }
- // src/query/HandledError.ts
- var HandledError = class {
- constructor(value, meta = void 0) {
- this.value = value;
- this.meta = meta;
- }
- };
- // src/query/retry.ts
- async function defaultBackoff(attempt = 0, maxRetries = 5) {
- const attempts = Math.min(attempt, maxRetries);
- const timeout = ~~((Math.random() + 0.4) * (300 << attempts));
- await new Promise((resolve) => setTimeout((res) => resolve(res), timeout));
- }
- function fail(e) {
- throw Object.assign(new HandledError({
- error: e
- }), {
- throwImmediately: true
- });
- }
- var EMPTY_OPTIONS = {};
- var retryWithBackoff = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {
- const possibleMaxRetries = [5, (defaultOptions || EMPTY_OPTIONS).maxRetries, (extraOptions || EMPTY_OPTIONS).maxRetries].filter((x) => x !== void 0);
- const [maxRetries] = possibleMaxRetries.slice(-1);
- const defaultRetryCondition = (_, __, {
- attempt
- }) => attempt <= maxRetries;
- const options = {
- maxRetries,
- backoff: defaultBackoff,
- retryCondition: defaultRetryCondition,
- ...defaultOptions,
- ...extraOptions
- };
- let retry2 = 0;
- while (true) {
- try {
- const result = await baseQuery(args, api, extraOptions);
- if (result.error) {
- throw new HandledError(result);
- }
- return result;
- } catch (e) {
- retry2++;
- if (e.throwImmediately) {
- if (e instanceof HandledError) {
- return e.value;
- }
- throw e;
- }
- if (e instanceof HandledError && !options.retryCondition(e.value.error, args, {
- attempt: retry2,
- baseQueryApi: api,
- extraOptions
- })) {
- return e.value;
- }
- await options.backoff(retry2, options.maxRetries);
- }
- }
- };
- var retry = /* @__PURE__ */ Object.assign(retryWithBackoff, {
- fail
- });
- // src/query/core/setupListeners.ts
- var onFocus = /* @__PURE__ */ createAction("__rtkq/focused");
- var onFocusLost = /* @__PURE__ */ createAction("__rtkq/unfocused");
- var onOnline = /* @__PURE__ */ createAction("__rtkq/online");
- var onOffline = /* @__PURE__ */ createAction("__rtkq/offline");
- var initialized = false;
- function setupListeners(dispatch, customHandler) {
- function defaultHandler() {
- const handleFocus = () => dispatch(onFocus());
- const handleFocusLost = () => dispatch(onFocusLost());
- const handleOnline = () => dispatch(onOnline());
- const handleOffline = () => dispatch(onOffline());
- const handleVisibilityChange = () => {
- if (window.document.visibilityState === "visible") {
- handleFocus();
- } else {
- handleFocusLost();
- }
- };
- if (!initialized) {
- if (typeof window !== "undefined" && window.addEventListener) {
- window.addEventListener("visibilitychange", handleVisibilityChange, false);
- window.addEventListener("focus", handleFocus, false);
- window.addEventListener("online", handleOnline, false);
- window.addEventListener("offline", handleOffline, false);
- initialized = true;
- }
- }
- const unsubscribe = () => {
- window.removeEventListener("focus", handleFocus);
- window.removeEventListener("visibilitychange", handleVisibilityChange);
- window.removeEventListener("online", handleOnline);
- window.removeEventListener("offline", handleOffline);
- initialized = false;
- };
- return unsubscribe;
- }
- return customHandler ? customHandler(dispatch, {
- onFocus,
- onFocusLost,
- onOffline,
- onOnline
- }) : defaultHandler();
- }
- // src/query/endpointDefinitions.ts
- function isQueryDefinition(e) {
- return e.type === "query" /* query */;
- }
- function isMutationDefinition(e) {
- return e.type === "mutation" /* mutation */;
- }
- function calculateProvidedBy(description, result, error, queryArg, meta, assertTagTypes) {
- if (isFunction(description)) {
- return description(result, error, queryArg, meta).map(expandTagDescription).map(assertTagTypes);
- }
- if (Array.isArray(description)) {
- return description.map(expandTagDescription).map(assertTagTypes);
- }
- return [];
- }
- function isFunction(t) {
- return typeof t === "function";
- }
- function expandTagDescription(description) {
- return typeof description === "string" ? {
- type: description
- } : description;
- }
- // src/query/core/buildInitiate.ts
- import { formatProdErrorMessage as _formatProdErrorMessage } from "@reduxjs/toolkit";
- // src/query/utils/isNotNullish.ts
- function isNotNullish(v) {
- return v != null;
- }
- // src/query/utils/countObjectKeys.ts
- function countObjectKeys(obj) {
- let count = 0;
- for (const _key in obj) {
- count++;
- }
- return count;
- }
- // src/query/core/buildInitiate.ts
- var forceQueryFnSymbol = Symbol("forceQueryFn");
- var isUpsertQuery = (arg) => typeof arg[forceQueryFnSymbol] === "function";
- function buildInitiate({
- serializeQueryArgs,
- queryThunk,
- mutationThunk,
- api,
- context
- }) {
- const runningQueries = /* @__PURE__ */ new Map();
- const runningMutations = /* @__PURE__ */ new Map();
- const {
- unsubscribeQueryResult,
- removeMutationResult,
- updateSubscriptionOptions
- } = api.internalActions;
- return {
- buildInitiateQuery,
- buildInitiateMutation,
- getRunningQueryThunk,
- getRunningMutationThunk,
- getRunningQueriesThunk,
- getRunningMutationsThunk
- };
- function getRunningQueryThunk(endpointName, queryArgs) {
- return (dispatch) => {
- const endpointDefinition = context.endpointDefinitions[endpointName];
- const queryCacheKey = serializeQueryArgs({
- queryArgs,
- endpointDefinition,
- endpointName
- });
- return runningQueries.get(dispatch)?.[queryCacheKey];
- };
- }
- function getRunningMutationThunk(_endpointName, fixedCacheKeyOrRequestId) {
- return (dispatch) => {
- return runningMutations.get(dispatch)?.[fixedCacheKeyOrRequestId];
- };
- }
- function getRunningQueriesThunk() {
- return (dispatch) => Object.values(runningQueries.get(dispatch) || {}).filter(isNotNullish);
- }
- function getRunningMutationsThunk() {
- return (dispatch) => Object.values(runningMutations.get(dispatch) || {}).filter(isNotNullish);
- }
- function middlewareWarning(dispatch) {
- if (process.env.NODE_ENV !== "production") {
- if (middlewareWarning.triggered)
- return;
- const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
- middlewareWarning.triggered = true;
- if (typeof returnedValue !== "object" || typeof returnedValue?.type === "string") {
- throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage(34) : `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
- You must add the middleware for RTK-Query to function correctly!`);
- }
- }
- }
- function buildInitiateQuery(endpointName, endpointDefinition) {
- const queryAction = (arg, {
- subscribe = true,
- forceRefetch,
- subscriptionOptions,
- [forceQueryFnSymbol]: forceQueryFn
- } = {}) => (dispatch, getState) => {
- const queryCacheKey = serializeQueryArgs({
- queryArgs: arg,
- endpointDefinition,
- endpointName
- });
- const thunk = queryThunk({
- type: "query",
- subscribe,
- forceRefetch,
- subscriptionOptions,
- endpointName,
- originalArgs: arg,
- queryCacheKey,
- [forceQueryFnSymbol]: forceQueryFn
- });
- const selector = api.endpoints[endpointName].select(arg);
- const thunkResult = dispatch(thunk);
- const stateAfter = selector(getState());
- middlewareWarning(dispatch);
- const {
- requestId,
- abort
- } = thunkResult;
- const skippedSynchronously = stateAfter.requestId !== requestId;
- const runningQuery = runningQueries.get(dispatch)?.[queryCacheKey];
- const selectFromState = () => selector(getState());
- const statePromise = Object.assign(forceQueryFn ? (
- // a query has been forced (upsertQueryData)
- // -> we want to resolve it once data has been written with the data that will be written
- thunkResult.then(selectFromState)
- ) : skippedSynchronously && !runningQuery ? (
- // a query has been skipped due to a condition and we do not have any currently running query
- // -> we want to resolve it immediately with the current data
- Promise.resolve(stateAfter)
- ) : (
- // query just started or one is already in flight
- // -> wait for the running query, then resolve with data from after that
- Promise.all([runningQuery, thunkResult]).then(selectFromState)
- ), {
- arg,
- requestId,
- subscriptionOptions,
- queryCacheKey,
- abort,
- async unwrap() {
- const result = await statePromise;
- if (result.isError) {
- throw result.error;
- }
- return result.data;
- },
- refetch: () => dispatch(queryAction(arg, {
- subscribe: false,
- forceRefetch: true
- })),
- unsubscribe() {
- if (subscribe)
- dispatch(unsubscribeQueryResult({
- queryCacheKey,
- requestId
- }));
- },
- updateSubscriptionOptions(options) {
- statePromise.subscriptionOptions = options;
- dispatch(updateSubscriptionOptions({
- endpointName,
- requestId,
- queryCacheKey,
- options
- }));
- }
- });
- if (!runningQuery && !skippedSynchronously && !forceQueryFn) {
- const running = runningQueries.get(dispatch) || {};
- running[queryCacheKey] = statePromise;
- runningQueries.set(dispatch, running);
- statePromise.then(() => {
- delete running[queryCacheKey];
- if (!countObjectKeys(running)) {
- runningQueries.delete(dispatch);
- }
- });
- }
- return statePromise;
- };
- return queryAction;
- }
- function buildInitiateMutation(endpointName) {
- return (arg, {
- track = true,
- fixedCacheKey
- } = {}) => (dispatch, getState) => {
- const thunk = mutationThunk({
- type: "mutation",
- endpointName,
- originalArgs: arg,
- track,
- fixedCacheKey
- });
- const thunkResult = dispatch(thunk);
- middlewareWarning(dispatch);
- const {
- requestId,
- abort,
- unwrap
- } = thunkResult;
- const returnValuePromise = thunkResult.unwrap().then((data) => ({
- data
- })).catch((error) => ({
- error
- }));
- const reset = () => {
- dispatch(removeMutationResult({
- requestId,
- fixedCacheKey
- }));
- };
- const ret = Object.assign(returnValuePromise, {
- arg: thunkResult.arg,
- requestId,
- abort,
- unwrap,
- reset
- });
- const running = runningMutations.get(dispatch) || {};
- runningMutations.set(dispatch, running);
- running[requestId] = ret;
- ret.then(() => {
- delete running[requestId];
- if (!countObjectKeys(running)) {
- runningMutations.delete(dispatch);
- }
- });
- if (fixedCacheKey) {
- running[fixedCacheKey] = ret;
- ret.then(() => {
- if (running[fixedCacheKey] === ret) {
- delete running[fixedCacheKey];
- if (!countObjectKeys(running)) {
- runningMutations.delete(dispatch);
- }
- }
- });
- }
- return ret;
- };
- }
- }
- // src/query/core/buildThunks.ts
- import { isDraftable, produceWithPatches } from "immer";
- function defaultTransformResponse(baseQueryReturnValue) {
- return baseQueryReturnValue;
- }
- function buildThunks({
- reducerPath,
- baseQuery,
- context: {
- endpointDefinitions
- },
- serializeQueryArgs,
- api,
- assertTagType
- }) {
- const patchQueryData = (endpointName, args, patches, updateProvided) => (dispatch, getState) => {
- const endpointDefinition = endpointDefinitions[endpointName];
- const queryCacheKey = serializeQueryArgs({
- queryArgs: args,
- endpointDefinition,
- endpointName
- });
- dispatch(api.internalActions.queryResultPatched({
- queryCacheKey,
- patches
- }));
- if (!updateProvided) {
- return;
- }
- const newValue = api.endpoints[endpointName].select(args)(
- // Work around TS 4.1 mismatch
- getState()
- );
- const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, void 0, args, {}, assertTagType);
- dispatch(api.internalActions.updateProvidedBy({
- queryCacheKey,
- providedTags
- }));
- };
- const updateQueryData = (endpointName, args, updateRecipe, updateProvided = true) => (dispatch, getState) => {
- const endpointDefinition = api.endpoints[endpointName];
- const currentState = endpointDefinition.select(args)(
- // Work around TS 4.1 mismatch
- getState()
- );
- let ret = {
- patches: [],
- inversePatches: [],
- undo: () => dispatch(api.util.patchQueryData(endpointName, args, ret.inversePatches, updateProvided))
- };
- if (currentState.status === "uninitialized" /* uninitialized */) {
- return ret;
- }
- let newValue;
- if ("data" in currentState) {
- if (isDraftable(currentState.data)) {
- const [value, patches, inversePatches] = produceWithPatches(currentState.data, updateRecipe);
- ret.patches.push(...patches);
- ret.inversePatches.push(...inversePatches);
- newValue = value;
- } else {
- newValue = updateRecipe(currentState.data);
- ret.patches.push({
- op: "replace",
- path: [],
- value: newValue
- });
- ret.inversePatches.push({
- op: "replace",
- path: [],
- value: currentState.data
- });
- }
- }
- dispatch(api.util.patchQueryData(endpointName, args, ret.patches, updateProvided));
- return ret;
- };
- const upsertQueryData = (endpointName, args, value) => (dispatch) => {
- return dispatch(api.endpoints[endpointName].initiate(args, {
- subscribe: false,
- forceRefetch: true,
- [forceQueryFnSymbol]: () => ({
- data: value
- })
- }));
- };
- const executeEndpoint = async (arg, {
- signal,
- abort,
- rejectWithValue,
- fulfillWithValue,
- dispatch,
- getState,
- extra
- }) => {
- const endpointDefinition = endpointDefinitions[arg.endpointName];
- try {
- let transformResponse = defaultTransformResponse;
- let result;
- const baseQueryApi = {
- signal,
- abort,
- dispatch,
- getState,
- extra,
- endpoint: arg.endpointName,
- type: arg.type,
- forced: arg.type === "query" ? isForcedQuery(arg, getState()) : void 0
- };
- const forceQueryFn = arg.type === "query" ? arg[forceQueryFnSymbol] : void 0;
- if (forceQueryFn) {
- result = forceQueryFn();
- } else if (endpointDefinition.query) {
- result = await baseQuery(endpointDefinition.query(arg.originalArgs), baseQueryApi, endpointDefinition.extraOptions);
- if (endpointDefinition.transformResponse) {
- transformResponse = endpointDefinition.transformResponse;
- }
- } else {
- result = await endpointDefinition.queryFn(arg.originalArgs, baseQueryApi, endpointDefinition.extraOptions, (arg2) => baseQuery(arg2, baseQueryApi, endpointDefinition.extraOptions));
- }
- if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
- const what = endpointDefinition.query ? "`baseQuery`" : "`queryFn`";
- let err;
- if (!result) {
- err = `${what} did not return anything.`;
- } else if (typeof result !== "object") {
- err = `${what} did not return an object.`;
- } else if (result.error && result.data) {
- err = `${what} returned an object containing both \`error\` and \`result\`.`;
- } else if (result.error === void 0 && result.data === void 0) {
- err = `${what} returned an object containing neither a valid \`error\` and \`result\`. At least one of them should not be \`undefined\``;
- } else {
- for (const key of Object.keys(result)) {
- if (key !== "error" && key !== "data" && key !== "meta") {
- err = `The object returned by ${what} has the unknown property ${key}.`;
- break;
- }
- }
- }
- if (err) {
- console.error(`Error encountered handling the endpoint ${arg.endpointName}.
- ${err}
- It needs to return an object with either the shape \`{ data: <value> }\` or \`{ error: <value> }\` that may contain an optional \`meta\` property.
- Object returned was:`, result);
- }
- }
- if (result.error)
- throw new HandledError(result.error, result.meta);
- return fulfillWithValue(await transformResponse(result.data, result.meta, arg.originalArgs), {
- fulfilledTimeStamp: Date.now(),
- baseQueryMeta: result.meta,
- [SHOULD_AUTOBATCH]: true
- });
- } catch (error) {
- let catchedError = error;
- if (catchedError instanceof HandledError) {
- let transformErrorResponse = defaultTransformResponse;
- if (endpointDefinition.query && endpointDefinition.transformErrorResponse) {
- transformErrorResponse = endpointDefinition.transformErrorResponse;
- }
- try {
- return rejectWithValue(await transformErrorResponse(catchedError.value, catchedError.meta, arg.originalArgs), {
- baseQueryMeta: catchedError.meta,
- [SHOULD_AUTOBATCH]: true
- });
- } catch (e) {
- catchedError = e;
- }
- }
- if (typeof process !== "undefined" && process.env.NODE_ENV !== "production") {
- console.error(`An unhandled error occurred processing a request for the endpoint "${arg.endpointName}".
- In the case of an unhandled error, no tags will be "provided" or "invalidated".`, catchedError);
- } else {
- console.error(catchedError);
- }
- throw catchedError;
- }
- };
- function isForcedQuery(arg, state) {
- const requestState = state[reducerPath]?.queries?.[arg.queryCacheKey];
- const baseFetchOnMountOrArgChange = state[reducerPath]?.config.refetchOnMountOrArgChange;
- const fulfilledVal = requestState?.fulfilledTimeStamp;
- const refetchVal = arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange);
- if (refetchVal) {
- return refetchVal === true || (Number(/* @__PURE__ */ new Date()) - Number(fulfilledVal)) / 1e3 >= refetchVal;
- }
- return false;
- }
- const queryThunk = createAsyncThunk(`${reducerPath}/executeQuery`, executeEndpoint, {
- getPendingMeta() {
- return {
- startedTimeStamp: Date.now(),
- [SHOULD_AUTOBATCH]: true
- };
- },
- condition(queryThunkArgs, {
- getState
- }) {
- const state = getState();
- const requestState = state[reducerPath]?.queries?.[queryThunkArgs.queryCacheKey];
- const fulfilledVal = requestState?.fulfilledTimeStamp;
- const currentArg = queryThunkArgs.originalArgs;
- const previousArg = requestState?.originalArgs;
- const endpointDefinition = endpointDefinitions[queryThunkArgs.endpointName];
- if (isUpsertQuery(queryThunkArgs)) {
- return true;
- }
- if (requestState?.status === "pending") {
- return false;
- }
- if (isForcedQuery(queryThunkArgs, state)) {
- return true;
- }
- if (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({
- currentArg,
- previousArg,
- endpointState: requestState,
- state
- })) {
- return true;
- }
- if (fulfilledVal) {
- return false;
- }
- return true;
- },
- dispatchConditionRejection: true
- });
- const mutationThunk = createAsyncThunk(`${reducerPath}/executeMutation`, executeEndpoint, {
- getPendingMeta() {
- return {
- startedTimeStamp: Date.now(),
- [SHOULD_AUTOBATCH]: true
- };
- }
- });
- const hasTheForce = (options) => "force" in options;
- const hasMaxAge = (options) => "ifOlderThan" in options;
- const prefetch = (endpointName, arg, options) => (dispatch, getState) => {
- const force = hasTheForce(options) && options.force;
- const maxAge = hasMaxAge(options) && options.ifOlderThan;
- const queryAction = (force2 = true) => api.endpoints[endpointName].initiate(arg, {
- forceRefetch: force2
- });
- const latestStateValue = api.endpoints[endpointName].select(arg)(getState());
- if (force) {
- dispatch(queryAction());
- } else if (maxAge) {
- const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp;
- if (!lastFulfilledTs) {
- dispatch(queryAction());
- return;
- }
- const shouldRetrigger = (Number(/* @__PURE__ */ new Date()) - Number(new Date(lastFulfilledTs))) / 1e3 >= maxAge;
- if (shouldRetrigger) {
- dispatch(queryAction());
- }
- } else {
- dispatch(queryAction(false));
- }
- };
- function matchesEndpoint(endpointName) {
- return (action) => action?.meta?.arg?.endpointName === endpointName;
- }
- function buildMatchThunkActions(thunk, endpointName) {
- return {
- matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),
- matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),
- matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))
- };
- }
- return {
- queryThunk,
- mutationThunk,
- prefetch,
- updateQueryData,
- upsertQueryData,
- patchQueryData,
- buildMatchThunkActions
- };
- }
- function calculateProvidedByThunk(action, type, endpointDefinitions, assertTagType) {
- 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);
- }
- // src/query/core/buildSlice.ts
- import { isDraft } from "immer";
- import { applyPatches, original } from "immer";
- function updateQuerySubstateIfExists(state, queryCacheKey, update) {
- const substate = state[queryCacheKey];
- if (substate) {
- update(substate);
- }
- }
- function getMutationCacheKey(id) {
- return ("arg" in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId;
- }
- function updateMutationSubstateIfExists(state, id, update) {
- const substate = state[getMutationCacheKey(id)];
- if (substate) {
- update(substate);
- }
- }
- var initialState = {};
- function buildSlice({
- reducerPath,
- queryThunk,
- mutationThunk,
- context: {
- endpointDefinitions: definitions,
- apiUid,
- extractRehydrationInfo,
- hasRehydrationInfo
- },
- assertTagType,
- config
- }) {
- const resetApiState = createAction(`${reducerPath}/resetApiState`);
- const querySlice = createSlice({
- name: `${reducerPath}/queries`,
- initialState,
- reducers: {
- removeQueryResult: {
- reducer(draft, {
- payload: {
- queryCacheKey
- }
- }) {
- delete draft[queryCacheKey];
- },
- prepare: prepareAutoBatched()
- },
- queryResultPatched: {
- reducer(draft, {
- payload: {
- queryCacheKey,
- patches
- }
- }) {
- updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {
- substate.data = applyPatches(substate.data, patches.concat());
- });
- },
- prepare: prepareAutoBatched()
- }
- },
- extraReducers(builder) {
- builder.addCase(queryThunk.pending, (draft, {
- meta,
- meta: {
- arg
- }
- }) => {
- const upserting = isUpsertQuery(arg);
- draft[arg.queryCacheKey] ??= {
- status: "uninitialized" /* uninitialized */,
- endpointName: arg.endpointName
- };
- updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
- substate.status = "pending" /* pending */;
- substate.requestId = upserting && substate.requestId ? (
- // for `upsertQuery` **updates**, keep the current `requestId`
- substate.requestId
- ) : (
- // for normal queries or `upsertQuery` **inserts** always update the `requestId`
- meta.requestId
- );
- if (arg.originalArgs !== void 0) {
- substate.originalArgs = arg.originalArgs;
- }
- substate.startedTimeStamp = meta.startedTimeStamp;
- });
- }).addCase(queryThunk.fulfilled, (draft, {
- meta,
- payload
- }) => {
- updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, (substate) => {
- if (substate.requestId !== meta.requestId && !isUpsertQuery(meta.arg))
- return;
- const {
- merge
- } = definitions[meta.arg.endpointName];
- substate.status = "fulfilled" /* fulfilled */;
- if (merge) {
- if (substate.data !== void 0) {
- const {
- fulfilledTimeStamp,
- arg,
- baseQueryMeta,
- requestId
- } = meta;
- let newData = createNextState(substate.data, (draftSubstateData) => {
- return merge(draftSubstateData, payload, {
- arg: arg.originalArgs,
- baseQueryMeta,
- fulfilledTimeStamp,
- requestId
- });
- });
- substate.data = newData;
- } else {
- substate.data = payload;
- }
- } else {
- substate.data = definitions[meta.arg.endpointName].structuralSharing ?? true ? copyWithStructuralSharing(isDraft(substate.data) ? original(substate.data) : substate.data, payload) : payload;
- }
- delete substate.error;
- substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
- });
- }).addCase(queryThunk.rejected, (draft, {
- meta: {
- condition,
- arg,
- requestId
- },
- error,
- payload
- }) => {
- updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
- if (condition) {
- } else {
- if (substate.requestId !== requestId)
- return;
- substate.status = "rejected" /* rejected */;
- substate.error = payload ?? error;
- }
- });
- }).addMatcher(hasRehydrationInfo, (draft, action) => {
- const {
- queries
- } = extractRehydrationInfo(action);
- for (const [key, entry] of Object.entries(queries)) {
- if (
- // do not rehydrate entries that were currently in flight.
- entry?.status === "fulfilled" /* fulfilled */ || entry?.status === "rejected" /* rejected */
- ) {
- draft[key] = entry;
- }
- }
- });
- }
- });
- const mutationSlice = createSlice({
- name: `${reducerPath}/mutations`,
- initialState,
- reducers: {
- removeMutationResult: {
- reducer(draft, {
- payload
- }) {
- const cacheKey = getMutationCacheKey(payload);
- if (cacheKey in draft) {
- delete draft[cacheKey];
- }
- },
- prepare: prepareAutoBatched()
- }
- },
- extraReducers(builder) {
- builder.addCase(mutationThunk.pending, (draft, {
- meta,
- meta: {
- requestId,
- arg,
- startedTimeStamp
- }
- }) => {
- if (!arg.track)
- return;
- draft[getMutationCacheKey(meta)] = {
- requestId,
- status: "pending" /* pending */,
- endpointName: arg.endpointName,
- startedTimeStamp
- };
- }).addCase(mutationThunk.fulfilled, (draft, {
- payload,
- meta
- }) => {
- if (!meta.arg.track)
- return;
- updateMutationSubstateIfExists(draft, meta, (substate) => {
- if (substate.requestId !== meta.requestId)
- return;
- substate.status = "fulfilled" /* fulfilled */;
- substate.data = payload;
- substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
- });
- }).addCase(mutationThunk.rejected, (draft, {
- payload,
- error,
- meta
- }) => {
- if (!meta.arg.track)
- return;
- updateMutationSubstateIfExists(draft, meta, (substate) => {
- if (substate.requestId !== meta.requestId)
- return;
- substate.status = "rejected" /* rejected */;
- substate.error = payload ?? error;
- });
- }).addMatcher(hasRehydrationInfo, (draft, action) => {
- const {
- mutations
- } = extractRehydrationInfo(action);
- for (const [key, entry] of Object.entries(mutations)) {
- if (
- // do not rehydrate entries that were currently in flight.
- (entry?.status === "fulfilled" /* fulfilled */ || entry?.status === "rejected" /* rejected */) && // only rehydrate endpoints that were persisted using a `fixedCacheKey`
- key !== entry?.requestId
- ) {
- draft[key] = entry;
- }
- }
- });
- }
- });
- const invalidationSlice = createSlice({
- name: `${reducerPath}/invalidation`,
- initialState,
- reducers: {
- updateProvidedBy: {
- reducer(draft, action) {
- const {
- queryCacheKey,
- providedTags
- } = action.payload;
- for (const tagTypeSubscriptions of Object.values(draft)) {
- for (const idSubscriptions of Object.values(tagTypeSubscriptions)) {
- const foundAt = idSubscriptions.indexOf(queryCacheKey);
- if (foundAt !== -1) {
- idSubscriptions.splice(foundAt, 1);
- }
- }
- }
- for (const {
- type,
- id
- } of providedTags) {
- const subscribedQueries = (draft[type] ??= {})[id || "__internal_without_id"] ??= [];
- const alreadySubscribed = subscribedQueries.includes(queryCacheKey);
- if (!alreadySubscribed) {
- subscribedQueries.push(queryCacheKey);
- }
- }
- },
- prepare: prepareAutoBatched()
- }
- },
- extraReducers(builder) {
- builder.addCase(querySlice.actions.removeQueryResult, (draft, {
- payload: {
- queryCacheKey
- }
- }) => {
- for (const tagTypeSubscriptions of Object.values(draft)) {
- for (const idSubscriptions of Object.values(tagTypeSubscriptions)) {
- const foundAt = idSubscriptions.indexOf(queryCacheKey);
- if (foundAt !== -1) {
- idSubscriptions.splice(foundAt, 1);
- }
- }
- }
- }).addMatcher(hasRehydrationInfo, (draft, action) => {
- const {
- provided
- } = extractRehydrationInfo(action);
- for (const [type, incomingTags] of Object.entries(provided)) {
- for (const [id, cacheKeys] of Object.entries(incomingTags)) {
- const subscribedQueries = (draft[type] ??= {})[id || "__internal_without_id"] ??= [];
- for (const queryCacheKey of cacheKeys) {
- const alreadySubscribed = subscribedQueries.includes(queryCacheKey);
- if (!alreadySubscribed) {
- subscribedQueries.push(queryCacheKey);
- }
- }
- }
- }
- }).addMatcher(isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)), (draft, action) => {
- const providedTags = calculateProvidedByThunk(action, "providesTags", definitions, assertTagType);
- const {
- queryCacheKey
- } = action.meta.arg;
- invalidationSlice.caseReducers.updateProvidedBy(draft, invalidationSlice.actions.updateProvidedBy({
- queryCacheKey,
- providedTags
- }));
- });
- }
- });
- const subscriptionSlice = createSlice({
- name: `${reducerPath}/subscriptions`,
- initialState,
- reducers: {
- updateSubscriptionOptions(d, a) {
- },
- unsubscribeQueryResult(d, a) {
- },
- internal_getRTKQSubscriptions() {
- }
- }
- });
- const internalSubscriptionsSlice = createSlice({
- name: `${reducerPath}/internalSubscriptions`,
- initialState,
- reducers: {
- subscriptionsUpdated: {
- reducer(state, action) {
- return applyPatches(state, action.payload);
- },
- prepare: prepareAutoBatched()
- }
- }
- });
- const configSlice = createSlice({
- name: `${reducerPath}/config`,
- initialState: {
- online: isOnline(),
- focused: isDocumentVisible(),
- middlewareRegistered: false,
- ...config
- },
- reducers: {
- middlewareRegistered(state, {
- payload
- }) {
- state.middlewareRegistered = state.middlewareRegistered === "conflict" || apiUid !== payload ? "conflict" : true;
- }
- },
- extraReducers: (builder) => {
- builder.addCase(onOnline, (state) => {
- state.online = true;
- }).addCase(onOffline, (state) => {
- state.online = false;
- }).addCase(onFocus, (state) => {
- state.focused = true;
- }).addCase(onFocusLost, (state) => {
- state.focused = false;
- }).addMatcher(hasRehydrationInfo, (draft) => ({
- ...draft
- }));
- }
- });
- const combinedReducer = combineReducers({
- queries: querySlice.reducer,
- mutations: mutationSlice.reducer,
- provided: invalidationSlice.reducer,
- subscriptions: internalSubscriptionsSlice.reducer,
- config: configSlice.reducer
- });
- const reducer = (state, action) => combinedReducer(resetApiState.match(action) ? void 0 : state, action);
- const actions = {
- ...configSlice.actions,
- ...querySlice.actions,
- ...subscriptionSlice.actions,
- ...internalSubscriptionsSlice.actions,
- ...mutationSlice.actions,
- ...invalidationSlice.actions,
- resetApiState
- };
- return {
- reducer,
- actions
- };
- }
- // src/query/core/buildSelectors.ts
- var skipToken = /* @__PURE__ */ Symbol.for("RTKQ/skipToken");
- var initialSubState = {
- status: "uninitialized" /* uninitialized */
- };
- var defaultQuerySubState = /* @__PURE__ */ createNextState(initialSubState, () => {
- });
- var defaultMutationSubState = /* @__PURE__ */ createNextState(initialSubState, () => {
- });
- function buildSelectors({
- serializeQueryArgs,
- reducerPath
- }) {
- const selectSkippedQuery = (state) => defaultQuerySubState;
- const selectSkippedMutation = (state) => defaultMutationSubState;
- return {
- buildQuerySelector,
- buildMutationSelector,
- selectInvalidatedBy,
- selectCachedArgsForQuery
- };
- function withRequestFlags(substate) {
- return {
- ...substate,
- ...getRequestStatusFlags(substate.status)
- };
- }
- function selectInternalState(rootState) {
- const state = rootState[reducerPath];
- if (process.env.NODE_ENV !== "production") {
- if (!state) {
- if (selectInternalState.triggered)
- return state;
- selectInternalState.triggered = true;
- console.error(`Error: No data found at \`state.${reducerPath}\`. Did you forget to add the reducer to the store?`);
- }
- }
- return state;
- }
- function buildQuerySelector(endpointName, endpointDefinition) {
- return (queryArgs) => {
- const serializedArgs = serializeQueryArgs({
- queryArgs,
- endpointDefinition,
- endpointName
- });
- const selectQuerySubstate = (state) => selectInternalState(state)?.queries?.[serializedArgs] ?? defaultQuerySubState;
- const finalSelectQuerySubState = queryArgs === skipToken ? selectSkippedQuery : selectQuerySubstate;
- return createSelector(finalSelectQuerySubState, withRequestFlags);
- };
- }
- function buildMutationSelector() {
- return (id) => {
- let mutationId;
- if (typeof id === "object") {
- mutationId = getMutationCacheKey(id) ?? skipToken;
- } else {
- mutationId = id;
- }
- const selectMutationSubstate = (state) => selectInternalState(state)?.mutations?.[mutationId] ?? defaultMutationSubState;
- const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;
- return createSelector(finalSelectMutationSubstate, withRequestFlags);
- };
- }
- function selectInvalidatedBy(state, tags) {
- const apiState = state[reducerPath];
- const toInvalidate = /* @__PURE__ */ new Set();
- for (const tag of tags.map(expandTagDescription)) {
- const provided = apiState.provided[tag.type];
- if (!provided) {
- continue;
- }
- let invalidateSubscriptions = (tag.id !== void 0 ? (
- // id given: invalidate all queries that provide this type & id
- provided[tag.id]
- ) : (
- // no id: invalidate all queries that provide this type
- flatten(Object.values(provided))
- )) ?? [];
- for (const invalidate of invalidateSubscriptions) {
- toInvalidate.add(invalidate);
- }
- }
- return flatten(Array.from(toInvalidate.values()).map((queryCacheKey) => {
- const querySubState = apiState.queries[queryCacheKey];
- return querySubState ? [{
- queryCacheKey,
- endpointName: querySubState.endpointName,
- originalArgs: querySubState.originalArgs
- }] : [];
- }));
- }
- function selectCachedArgsForQuery(state, queryName) {
- return Object.values(state[reducerPath].queries).filter((entry) => entry?.endpointName === queryName && entry.status !== "uninitialized" /* uninitialized */).map((entry) => entry.originalArgs);
- }
- }
- // src/query/defaultSerializeQueryArgs.ts
- var cache = WeakMap ? /* @__PURE__ */ new WeakMap() : void 0;
- var defaultSerializeQueryArgs = ({
- endpointName,
- queryArgs
- }) => {
- let serialized = "";
- const cached = cache?.get(queryArgs);
- if (typeof cached === "string") {
- serialized = cached;
- } else {
- const stringified = JSON.stringify(queryArgs, (key, value) => isPlainObject(value) ? Object.keys(value).sort().reduce((acc, key2) => {
- acc[key2] = value[key2];
- return acc;
- }, {}) : value);
- if (isPlainObject(queryArgs)) {
- cache?.set(queryArgs, stringified);
- }
- serialized = stringified;
- }
- return `${endpointName}(${serialized})`;
- };
- // src/query/createApi.ts
- import { weakMapMemoize } from "reselect";
- function buildCreateApi(...modules) {
- return function baseCreateApi(options) {
- const extractRehydrationInfo = weakMapMemoize((action) => options.extractRehydrationInfo?.(action, {
- reducerPath: options.reducerPath ?? "api"
- }));
- const optionsWithDefaults = {
- reducerPath: "api",
- keepUnusedDataFor: 60,
- refetchOnMountOrArgChange: false,
- refetchOnFocus: false,
- refetchOnReconnect: false,
- invalidationBehavior: "delayed",
- ...options,
- extractRehydrationInfo,
- serializeQueryArgs(queryArgsApi) {
- let finalSerializeQueryArgs = defaultSerializeQueryArgs;
- if ("serializeQueryArgs" in queryArgsApi.endpointDefinition) {
- const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs;
- finalSerializeQueryArgs = (queryArgsApi2) => {
- const initialResult = endpointSQA(queryArgsApi2);
- if (typeof initialResult === "string") {
- return initialResult;
- } else {
- return defaultSerializeQueryArgs({
- ...queryArgsApi2,
- queryArgs: initialResult
- });
- }
- };
- } else if (options.serializeQueryArgs) {
- finalSerializeQueryArgs = options.serializeQueryArgs;
- }
- return finalSerializeQueryArgs(queryArgsApi);
- },
- tagTypes: [...options.tagTypes || []]
- };
- const context = {
- endpointDefinitions: {},
- batch(fn) {
- fn();
- },
- apiUid: nanoid(),
- extractRehydrationInfo,
- hasRehydrationInfo: weakMapMemoize((action) => extractRehydrationInfo(action) != null)
- };
- const api = {
- injectEndpoints,
- enhanceEndpoints({
- addTagTypes,
- endpoints
- }) {
- if (addTagTypes) {
- for (const eT of addTagTypes) {
- if (!optionsWithDefaults.tagTypes.includes(eT)) {
- ;
- optionsWithDefaults.tagTypes.push(eT);
- }
- }
- }
- if (endpoints) {
- for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {
- if (typeof partialDefinition === "function") {
- partialDefinition(context.endpointDefinitions[endpointName]);
- } else {
- Object.assign(context.endpointDefinitions[endpointName] || {}, partialDefinition);
- }
- }
- }
- return api;
- }
- };
- const initializedModules = modules.map((m) => m.init(api, optionsWithDefaults, context));
- function injectEndpoints(inject) {
- const evaluatedEndpoints = inject.endpoints({
- query: (x) => ({
- ...x,
- type: "query" /* query */
- }),
- mutation: (x) => ({
- ...x,
- type: "mutation" /* mutation */
- })
- });
- for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {
- if (!inject.overrideExisting && endpointName in context.endpointDefinitions) {
- if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
- console.error(`called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``);
- }
- continue;
- }
- context.endpointDefinitions[endpointName] = definition;
- for (const m of initializedModules) {
- m.injectEndpoint(endpointName, definition);
- }
- }
- return api;
- }
- return api.injectEndpoints({
- endpoints: options.endpoints
- });
- };
- }
- // src/query/fakeBaseQuery.ts
- import { formatProdErrorMessage as _formatProdErrorMessage2 } from "@reduxjs/toolkit";
- function fakeBaseQuery() {
- return function() {
- throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage2(33) : "When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.");
- };
- }
- // src/query/core/buildMiddleware/cacheCollection.ts
- function isObjectEmpty(obj) {
- for (let k in obj) {
- return false;
- }
- return true;
- }
- var THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2147483647 / 1e3 - 1;
- var buildCacheCollectionHandler = ({
- reducerPath,
- api,
- context,
- internalState
- }) => {
- const {
- removeQueryResult,
- unsubscribeQueryResult
- } = api.internalActions;
- function anySubscriptionsRemainingForKey(queryCacheKey) {
- const subscriptions = internalState.currentSubscriptions[queryCacheKey];
- return !!subscriptions && !isObjectEmpty(subscriptions);
- }
- const currentRemovalTimeouts = {};
- const handler = (action, mwApi, internalState2) => {
- if (unsubscribeQueryResult.match(action)) {
- const state = mwApi.getState()[reducerPath];
- const {
- queryCacheKey
- } = action.payload;
- handleUnsubscribe(queryCacheKey, state.queries[queryCacheKey]?.endpointName, mwApi, state.config);
- }
- if (api.util.resetApiState.match(action)) {
- for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {
- if (timeout)
- clearTimeout(timeout);
- delete currentRemovalTimeouts[key];
- }
- }
- if (context.hasRehydrationInfo(action)) {
- const state = mwApi.getState()[reducerPath];
- const {
- queries
- } = context.extractRehydrationInfo(action);
- for (const [queryCacheKey, queryState] of Object.entries(queries)) {
- handleUnsubscribe(queryCacheKey, queryState?.endpointName, mwApi, state.config);
- }
- }
- };
- function handleUnsubscribe(queryCacheKey, endpointName, api2, config) {
- const endpointDefinition = context.endpointDefinitions[endpointName];
- const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;
- if (keepUnusedDataFor === Infinity) {
- return;
- }
- const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));
- if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
- const currentTimeout = currentRemovalTimeouts[queryCacheKey];
- if (currentTimeout) {
- clearTimeout(currentTimeout);
- }
- currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {
- if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
- api2.dispatch(removeQueryResult({
- queryCacheKey
- }));
- }
- delete currentRemovalTimeouts[queryCacheKey];
- }, finalKeepUnusedDataFor * 1e3);
- }
- }
- return handler;
- };
- // src/query/core/buildMiddleware/invalidationByTags.ts
- var buildInvalidationByTagsHandler = ({
- reducerPath,
- context,
- context: {
- endpointDefinitions
- },
- mutationThunk,
- queryThunk,
- api,
- assertTagType,
- refetchQuery,
- internalState
- }) => {
- const {
- removeQueryResult
- } = api.internalActions;
- const isThunkActionWithTags = isAnyOf(isFulfilled(mutationThunk), isRejectedWithValue(mutationThunk));
- const isQueryEnd = isAnyOf(isFulfilled(mutationThunk, queryThunk), isRejected(mutationThunk, queryThunk));
- let pendingTagInvalidations = [];
- const handler = (action, mwApi) => {
- if (isThunkActionWithTags(action)) {
- invalidateTags(calculateProvidedByThunk(action, "invalidatesTags", endpointDefinitions, assertTagType), mwApi);
- } else if (isQueryEnd(action)) {
- invalidateTags([], mwApi);
- } else if (api.util.invalidateTags.match(action)) {
- invalidateTags(calculateProvidedBy(action.payload, void 0, void 0, void 0, void 0, assertTagType), mwApi);
- }
- };
- function hasPendingRequests(state) {
- for (const key in state.queries) {
- if (state.queries[key]?.status === "pending" /* pending */)
- return true;
- }
- for (const key in state.mutations) {
- if (state.mutations[key]?.status === "pending" /* pending */)
- return true;
- }
- return false;
- }
- function invalidateTags(newTags, mwApi) {
- const rootState = mwApi.getState();
- const state = rootState[reducerPath];
- pendingTagInvalidations.push(...newTags);
- if (state.config.invalidationBehavior === "delayed" && hasPendingRequests(state)) {
- return;
- }
- const tags = pendingTagInvalidations;
- pendingTagInvalidations = [];
- if (tags.length === 0)
- return;
- const toInvalidate = api.util.selectInvalidatedBy(rootState, tags);
- context.batch(() => {
- const valuesArray = Array.from(toInvalidate.values());
- for (const {
- queryCacheKey
- } of valuesArray) {
- const querySubState = state.queries[queryCacheKey];
- const subscriptionSubState = internalState.currentSubscriptions[queryCacheKey] ?? {};
- if (querySubState) {
- if (countObjectKeys(subscriptionSubState) === 0) {
- mwApi.dispatch(removeQueryResult({
- queryCacheKey
- }));
- } else if (querySubState.status !== "uninitialized" /* uninitialized */) {
- mwApi.dispatch(refetchQuery(querySubState, queryCacheKey));
- }
- }
- }
- });
- }
- return handler;
- };
- // src/query/core/buildMiddleware/polling.ts
- var buildPollingHandler = ({
- reducerPath,
- queryThunk,
- api,
- refetchQuery,
- internalState
- }) => {
- const currentPolls = {};
- const handler = (action, mwApi) => {
- if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) {
- updatePollingInterval(action.payload, mwApi);
- }
- if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {
- updatePollingInterval(action.meta.arg, mwApi);
- }
- if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {
- startNextPoll(action.meta.arg, mwApi);
- }
- if (api.util.resetApiState.match(action)) {
- clearPolls();
- }
- };
- function startNextPoll({
- queryCacheKey
- }, api2) {
- const state = api2.getState()[reducerPath];
- const querySubState = state.queries[queryCacheKey];
- const subscriptions = internalState.currentSubscriptions[queryCacheKey];
- if (!querySubState || querySubState.status === "uninitialized" /* uninitialized */)
- return;
- const lowestPollingInterval = findLowestPollingInterval(subscriptions);
- if (!Number.isFinite(lowestPollingInterval))
- return;
- const currentPoll = currentPolls[queryCacheKey];
- if (currentPoll?.timeout) {
- clearTimeout(currentPoll.timeout);
- currentPoll.timeout = void 0;
- }
- const nextPollTimestamp = Date.now() + lowestPollingInterval;
- const currentInterval = currentPolls[queryCacheKey] = {
- nextPollTimestamp,
- pollingInterval: lowestPollingInterval,
- timeout: setTimeout(() => {
- currentInterval.timeout = void 0;
- api2.dispatch(refetchQuery(querySubState, queryCacheKey));
- }, lowestPollingInterval)
- };
- }
- function updatePollingInterval({
- queryCacheKey
- }, api2) {
- const state = api2.getState()[reducerPath];
- const querySubState = state.queries[queryCacheKey];
- const subscriptions = internalState.currentSubscriptions[queryCacheKey];
- if (!querySubState || querySubState.status === "uninitialized" /* uninitialized */) {
- return;
- }
- const lowestPollingInterval = findLowestPollingInterval(subscriptions);
- if (!Number.isFinite(lowestPollingInterval)) {
- cleanupPollForKey(queryCacheKey);
- return;
- }
- const currentPoll = currentPolls[queryCacheKey];
- const nextPollTimestamp = Date.now() + lowestPollingInterval;
- if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {
- startNextPoll({
- queryCacheKey
- }, api2);
- }
- }
- function cleanupPollForKey(key) {
- const existingPoll = currentPolls[key];
- if (existingPoll?.timeout) {
- clearTimeout(existingPoll.timeout);
- }
- delete currentPolls[key];
- }
- function clearPolls() {
- for (const key of Object.keys(currentPolls)) {
- cleanupPollForKey(key);
- }
- }
- function findLowestPollingInterval(subscribers = {}) {
- let lowestPollingInterval = Number.POSITIVE_INFINITY;
- for (let key in subscribers) {
- if (!!subscribers[key].pollingInterval) {
- lowestPollingInterval = Math.min(subscribers[key].pollingInterval, lowestPollingInterval);
- }
- }
- return lowestPollingInterval;
- }
- return handler;
- };
- // src/query/core/buildMiddleware/windowEventHandling.ts
- var buildWindowEventHandler = ({
- reducerPath,
- context,
- api,
- refetchQuery,
- internalState
- }) => {
- const {
- removeQueryResult
- } = api.internalActions;
- const handler = (action, mwApi) => {
- if (onFocus.match(action)) {
- refetchValidQueries(mwApi, "refetchOnFocus");
- }
- if (onOnline.match(action)) {
- refetchValidQueries(mwApi, "refetchOnReconnect");
- }
- };
- function refetchValidQueries(api2, type) {
- const state = api2.getState()[reducerPath];
- const queries = state.queries;
- const subscriptions = internalState.currentSubscriptions;
- context.batch(() => {
- for (const queryCacheKey of Object.keys(subscriptions)) {
- const querySubState = queries[queryCacheKey];
- const subscriptionSubState = subscriptions[queryCacheKey];
- if (!subscriptionSubState || !querySubState)
- continue;
- const shouldRefetch = Object.values(subscriptionSubState).some((sub) => sub[type] === true) || Object.values(subscriptionSubState).every((sub) => sub[type] === void 0) && state.config[type];
- if (shouldRefetch) {
- if (countObjectKeys(subscriptionSubState) === 0) {
- api2.dispatch(removeQueryResult({
- queryCacheKey
- }));
- } else if (querySubState.status !== "uninitialized" /* uninitialized */) {
- api2.dispatch(refetchQuery(querySubState, queryCacheKey));
- }
- }
- }
- });
- }
- return handler;
- };
- // src/query/core/buildMiddleware/cacheLifecycle.ts
- var neverResolvedError = new Error("Promise never resolved before cacheEntryRemoved.");
- var buildCacheLifecycleHandler = ({
- api,
- reducerPath,
- context,
- queryThunk,
- mutationThunk,
- internalState
- }) => {
- const isQueryThunk = isAsyncThunkAction(queryThunk);
- const isMutationThunk = isAsyncThunkAction(mutationThunk);
- const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk);
- const lifecycleMap = {};
- const handler = (action, mwApi, stateBefore) => {
- const cacheKey = getCacheKey(action);
- if (queryThunk.pending.match(action)) {
- const oldState = stateBefore[reducerPath].queries[cacheKey];
- const state = mwApi.getState()[reducerPath].queries[cacheKey];
- if (!oldState && state) {
- handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);
- }
- } else if (mutationThunk.pending.match(action)) {
- const state = mwApi.getState()[reducerPath].mutations[cacheKey];
- if (state) {
- handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);
- }
- } else if (isFulfilledThunk(action)) {
- const lifecycle = lifecycleMap[cacheKey];
- if (lifecycle?.valueResolved) {
- lifecycle.valueResolved({
- data: action.payload,
- meta: action.meta.baseQueryMeta
- });
- delete lifecycle.valueResolved;
- }
- } else if (api.internalActions.removeQueryResult.match(action) || api.internalActions.removeMutationResult.match(action)) {
- const lifecycle = lifecycleMap[cacheKey];
- if (lifecycle) {
- delete lifecycleMap[cacheKey];
- lifecycle.cacheEntryRemoved();
- }
- } else if (api.util.resetApiState.match(action)) {
- for (const [cacheKey2, lifecycle] of Object.entries(lifecycleMap)) {
- delete lifecycleMap[cacheKey2];
- lifecycle.cacheEntryRemoved();
- }
- }
- };
- function getCacheKey(action) {
- if (isQueryThunk(action))
- return action.meta.arg.queryCacheKey;
- if (isMutationThunk(action))
- return action.meta.requestId;
- if (api.internalActions.removeQueryResult.match(action))
- return action.payload.queryCacheKey;
- if (api.internalActions.removeMutationResult.match(action))
- return getMutationCacheKey(action.payload);
- return "";
- }
- function handleNewKey(endpointName, originalArgs, queryCacheKey, mwApi, requestId) {
- const endpointDefinition = context.endpointDefinitions[endpointName];
- const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;
- if (!onCacheEntryAdded)
- return;
- let lifecycle = {};
- const cacheEntryRemoved = new Promise((resolve) => {
- lifecycle.cacheEntryRemoved = resolve;
- });
- const cacheDataLoaded = Promise.race([new Promise((resolve) => {
- lifecycle.valueResolved = resolve;
- }), cacheEntryRemoved.then(() => {
- throw neverResolvedError;
- })]);
- cacheDataLoaded.catch(() => {
- });
- lifecycleMap[queryCacheKey] = lifecycle;
- const selector = api.endpoints[endpointName].select(endpointDefinition.type === "query" /* query */ ? originalArgs : queryCacheKey);
- const extra = mwApi.dispatch((_, __, extra2) => extra2);
- const lifecycleApi = {
- ...mwApi,
- getCacheEntry: () => selector(mwApi.getState()),
- requestId,
- extra,
- updateCachedData: endpointDefinition.type === "query" /* query */ ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
- cacheDataLoaded,
- cacheEntryRemoved
- };
- const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi);
- Promise.resolve(runningHandler).catch((e) => {
- if (e === neverResolvedError)
- return;
- throw e;
- });
- }
- return handler;
- };
- // src/query/core/buildMiddleware/queryLifecycle.ts
- var buildQueryLifecycleHandler = ({
- api,
- context,
- queryThunk,
- mutationThunk
- }) => {
- const isPendingThunk = isPending(queryThunk, mutationThunk);
- const isRejectedThunk = isRejected(queryThunk, mutationThunk);
- const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk);
- const lifecycleMap = {};
- const handler = (action, mwApi) => {
- if (isPendingThunk(action)) {
- const {
- requestId,
- arg: {
- endpointName,
- originalArgs
- }
- } = action.meta;
- const endpointDefinition = context.endpointDefinitions[endpointName];
- const onQueryStarted = endpointDefinition?.onQueryStarted;
- if (onQueryStarted) {
- const lifecycle = {};
- const queryFulfilled = new Promise((resolve, reject) => {
- lifecycle.resolve = resolve;
- lifecycle.reject = reject;
- });
- queryFulfilled.catch(() => {
- });
- lifecycleMap[requestId] = lifecycle;
- const selector = api.endpoints[endpointName].select(endpointDefinition.type === "query" /* query */ ? originalArgs : requestId);
- const extra = mwApi.dispatch((_, __, extra2) => extra2);
- const lifecycleApi = {
- ...mwApi,
- getCacheEntry: () => selector(mwApi.getState()),
- requestId,
- extra,
- updateCachedData: endpointDefinition.type === "query" /* query */ ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
- queryFulfilled
- };
- onQueryStarted(originalArgs, lifecycleApi);
- }
- } else if (isFullfilledThunk(action)) {
- const {
- requestId,
- baseQueryMeta
- } = action.meta;
- lifecycleMap[requestId]?.resolve({
- data: action.payload,
- meta: baseQueryMeta
- });
- delete lifecycleMap[requestId];
- } else if (isRejectedThunk(action)) {
- const {
- requestId,
- rejectedWithValue,
- baseQueryMeta
- } = action.meta;
- lifecycleMap[requestId]?.reject({
- error: action.payload ?? action.error,
- isUnhandledError: !rejectedWithValue,
- meta: baseQueryMeta
- });
- delete lifecycleMap[requestId];
- }
- };
- return handler;
- };
- // src/query/core/buildMiddleware/devMiddleware.ts
- var buildDevCheckHandler = ({
- api,
- context: {
- apiUid
- },
- reducerPath
- }) => {
- return (action, mwApi) => {
- if (api.util.resetApiState.match(action)) {
- mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
- }
- if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
- if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && mwApi.getState()[reducerPath]?.config?.middlewareRegistered === "conflict") {
- console.warn(`There is a mismatch between slice and middleware for the reducerPath "${reducerPath}".
- You can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === "api" ? `
- If you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ""}`);
- }
- }
- };
- };
- // src/query/core/buildMiddleware/batchActions.ts
- import { produceWithPatches as produceWithPatches2 } from "immer";
- var buildBatchedActionsHandler = ({
- api,
- queryThunk,
- internalState
- }) => {
- const subscriptionsPrefix = `${api.reducerPath}/subscriptions`;
- let previousSubscriptions = null;
- let updateSyncTimer = null;
- const {
- updateSubscriptionOptions,
- unsubscribeQueryResult
- } = api.internalActions;
- const actuallyMutateSubscriptions = (mutableState, action) => {
- if (updateSubscriptionOptions.match(action)) {
- const {
- queryCacheKey,
- requestId,
- options
- } = action.payload;
- if (mutableState?.[queryCacheKey]?.[requestId]) {
- mutableState[queryCacheKey][requestId] = options;
- }
- return true;
- }
- if (unsubscribeQueryResult.match(action)) {
- const {
- queryCacheKey,
- requestId
- } = action.payload;
- if (mutableState[queryCacheKey]) {
- delete mutableState[queryCacheKey][requestId];
- }
- return true;
- }
- if (api.internalActions.removeQueryResult.match(action)) {
- delete mutableState[action.payload.queryCacheKey];
- return true;
- }
- if (queryThunk.pending.match(action)) {
- const {
- meta: {
- arg,
- requestId
- }
- } = action;
- const substate = mutableState[arg.queryCacheKey] ??= {};
- substate[`${requestId}_running`] = {};
- if (arg.subscribe) {
- substate[requestId] = arg.subscriptionOptions ?? substate[requestId] ?? {};
- }
- return true;
- }
- let mutated = false;
- if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action)) {
- const state = mutableState[action.meta.arg.queryCacheKey] || {};
- const key = `${action.meta.requestId}_running`;
- mutated ||= !!state[key];
- delete state[key];
- }
- if (queryThunk.rejected.match(action)) {
- const {
- meta: {
- condition,
- arg,
- requestId
- }
- } = action;
- if (condition && arg.subscribe) {
- const substate = mutableState[arg.queryCacheKey] ??= {};
- substate[requestId] = arg.subscriptionOptions ?? substate[requestId] ?? {};
- mutated = true;
- }
- }
- return mutated;
- };
- const getSubscriptions = () => internalState.currentSubscriptions;
- const getSubscriptionCount = (queryCacheKey) => {
- const subscriptions = getSubscriptions();
- const subscriptionsForQueryArg = subscriptions[queryCacheKey] ?? {};
- return countObjectKeys(subscriptionsForQueryArg);
- };
- const isRequestSubscribed = (queryCacheKey, requestId) => {
- const subscriptions = getSubscriptions();
- return !!subscriptions?.[queryCacheKey]?.[requestId];
- };
- const subscriptionSelectors = {
- getSubscriptions,
- getSubscriptionCount,
- isRequestSubscribed
- };
- return (action, mwApi) => {
- if (!previousSubscriptions) {
- previousSubscriptions = JSON.parse(JSON.stringify(internalState.currentSubscriptions));
- }
- if (api.util.resetApiState.match(action)) {
- previousSubscriptions = internalState.currentSubscriptions = {};
- updateSyncTimer = null;
- return [true, false];
- }
- if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {
- return [false, subscriptionSelectors];
- }
- const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);
- let actionShouldContinue = true;
- if (didMutate) {
- if (!updateSyncTimer) {
- updateSyncTimer = setTimeout(() => {
- const newSubscriptions = JSON.parse(JSON.stringify(internalState.currentSubscriptions));
- const [, patches] = produceWithPatches2(previousSubscriptions, () => newSubscriptions);
- mwApi.next(api.internalActions.subscriptionsUpdated(patches));
- previousSubscriptions = newSubscriptions;
- updateSyncTimer = null;
- }, 500);
- }
- const isSubscriptionSliceAction = typeof action.type == "string" && !!action.type.startsWith(subscriptionsPrefix);
- const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;
- actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;
- }
- return [actionShouldContinue, false];
- };
- };
- // src/query/core/buildMiddleware/index.ts
- function buildMiddleware(input) {
- const {
- reducerPath,
- queryThunk,
- api,
- context
- } = input;
- const {
- apiUid
- } = context;
- const actions = {
- invalidateTags: createAction(`${reducerPath}/invalidateTags`)
- };
- const isThisApiSliceAction = (action) => action.type.startsWith(`${reducerPath}/`);
- const handlerBuilders = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler];
- const middleware = (mwApi) => {
- let initialized2 = false;
- let internalState = {
- currentSubscriptions: {}
- };
- const builderArgs = {
- ...input,
- internalState,
- refetchQuery,
- isThisApiSliceAction
- };
- const handlers = handlerBuilders.map((build) => build(builderArgs));
- const batchedActionsHandler = buildBatchedActionsHandler(builderArgs);
- const windowEventsHandler = buildWindowEventHandler(builderArgs);
- return (next) => {
- return (action) => {
- if (!isAction(action)) {
- return next(action);
- }
- if (!initialized2) {
- initialized2 = true;
- mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
- }
- const mwApiWithNext = {
- ...mwApi,
- next
- };
- const stateBefore = mwApi.getState();
- const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore);
- let res;
- if (actionShouldContinue) {
- res = next(action);
- } else {
- res = internalProbeResult;
- }
- if (!!mwApi.getState()[reducerPath]) {
- windowEventsHandler(action, mwApiWithNext, stateBefore);
- if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {
- for (let handler of handlers) {
- handler(action, mwApiWithNext, stateBefore);
- }
- }
- }
- return res;
- };
- };
- };
- return {
- middleware,
- actions
- };
- function refetchQuery(querySubState, queryCacheKey, override = {}) {
- return queryThunk({
- type: "query",
- endpointName: querySubState.endpointName,
- originalArgs: querySubState.originalArgs,
- subscribe: false,
- forceRefetch: true,
- queryCacheKey,
- ...override
- });
- }
- }
- // src/query/tsHelpers.ts
- function assertCast(v) {
- }
- function safeAssign(target, ...args) {
- return Object.assign(target, ...args);
- }
- // src/query/core/module.ts
- import { enablePatches } from "immer";
- var coreModuleName = /* @__PURE__ */ Symbol();
- var coreModule = () => ({
- name: coreModuleName,
- init(api, {
- baseQuery,
- tagTypes,
- reducerPath,
- serializeQueryArgs,
- keepUnusedDataFor,
- refetchOnMountOrArgChange,
- refetchOnFocus,
- refetchOnReconnect,
- invalidationBehavior
- }, context) {
- enablePatches();
- assertCast(serializeQueryArgs);
- const assertTagType = (tag) => {
- if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
- if (!tagTypes.includes(tag.type)) {
- console.error(`Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`);
- }
- }
- return tag;
- };
- Object.assign(api, {
- reducerPath,
- endpoints: {},
- internalActions: {
- onOnline,
- onOffline,
- onFocus,
- onFocusLost
- },
- util: {}
- });
- const {
- queryThunk,
- mutationThunk,
- patchQueryData,
- updateQueryData,
- upsertQueryData,
- prefetch,
- buildMatchThunkActions
- } = buildThunks({
- baseQuery,
- reducerPath,
- context,
- api,
- serializeQueryArgs,
- assertTagType
- });
- const {
- reducer,
- actions: sliceActions
- } = buildSlice({
- context,
- queryThunk,
- mutationThunk,
- reducerPath,
- assertTagType,
- config: {
- refetchOnFocus,
- refetchOnReconnect,
- refetchOnMountOrArgChange,
- keepUnusedDataFor,
- reducerPath,
- invalidationBehavior
- }
- });
- safeAssign(api.util, {
- patchQueryData,
- updateQueryData,
- upsertQueryData,
- prefetch,
- resetApiState: sliceActions.resetApiState
- });
- safeAssign(api.internalActions, sliceActions);
- const {
- middleware,
- actions: middlewareActions
- } = buildMiddleware({
- reducerPath,
- context,
- queryThunk,
- mutationThunk,
- api,
- assertTagType
- });
- safeAssign(api.util, middlewareActions);
- safeAssign(api, {
- reducer,
- middleware
- });
- const {
- buildQuerySelector,
- buildMutationSelector,
- selectInvalidatedBy,
- selectCachedArgsForQuery
- } = buildSelectors({
- serializeQueryArgs,
- reducerPath
- });
- safeAssign(api.util, {
- selectInvalidatedBy,
- selectCachedArgsForQuery
- });
- const {
- buildInitiateQuery,
- buildInitiateMutation,
- getRunningMutationThunk,
- getRunningMutationsThunk,
- getRunningQueriesThunk,
- getRunningQueryThunk
- } = buildInitiate({
- queryThunk,
- mutationThunk,
- api,
- serializeQueryArgs,
- context
- });
- safeAssign(api.util, {
- getRunningMutationThunk,
- getRunningMutationsThunk,
- getRunningQueryThunk,
- getRunningQueriesThunk
- });
- return {
- name: coreModuleName,
- injectEndpoint(endpointName, definition) {
- const anyApi = api;
- anyApi.endpoints[endpointName] ??= {};
- if (isQueryDefinition(definition)) {
- safeAssign(anyApi.endpoints[endpointName], {
- name: endpointName,
- select: buildQuerySelector(endpointName, definition),
- initiate: buildInitiateQuery(endpointName, definition)
- }, buildMatchThunkActions(queryThunk, endpointName));
- } else if (isMutationDefinition(definition)) {
- safeAssign(anyApi.endpoints[endpointName], {
- name: endpointName,
- select: buildMutationSelector(),
- initiate: buildInitiateMutation(endpointName)
- }, buildMatchThunkActions(mutationThunk, endpointName));
- }
- }
- };
- }
- });
- // src/query/core/index.ts
- var createApi = /* @__PURE__ */ buildCreateApi(coreModule());
- export {
- QueryStatus,
- buildCreateApi,
- copyWithStructuralSharing,
- coreModule,
- coreModuleName,
- createApi,
- defaultSerializeQueryArgs,
- fakeBaseQuery,
- fetchBaseQuery,
- retry,
- setupListeners,
- skipToken
- };
- //# sourceMappingURL=rtk-query.modern.mjs.map
|