UNPKG

215 kBSource Map (JSON)View Raw
1{"version":3,"sources":["../../src/query/core/apiState.ts","../../src/query/utils/flatten.ts","../../src/query/utils/copyWithStructuralSharing.ts","../../src/query/fetchBaseQuery.ts","../../src/query/utils/joinUrls.ts","../../src/query/utils/isAbsoluteUrl.ts","../../src/query/HandledError.ts","../../src/query/retry.ts","../../src/query/core/setupListeners.ts","../../src/query/endpointDefinitions.ts","../../src/query/core/buildSelectors.ts","../../src/query/core/buildSlice.ts","../../src/query/core/buildThunks.ts","../../src/query/defaultSerializeQueryArgs.ts","../../src/query/createApi.ts","../../src/query/fakeBaseQuery.ts","../../src/query/core/buildMiddleware/index.ts","../../src/query/core/buildMiddleware/cacheCollection.ts","../../src/query/core/buildMiddleware/invalidationByTags.ts","../../src/query/core/buildMiddleware/polling.ts","../../src/query/core/buildMiddleware/windowEventHandling.ts","../../src/query/core/buildMiddleware/cacheLifecycle.ts","../../src/query/core/buildMiddleware/queryLifecycle.ts","../../src/query/core/buildMiddleware/devMiddleware.ts","../../src/query/tsHelpers.ts","../../src/query/core/module.ts","../../src/query/utils/isOnline.ts","../../src/query/utils/isDocumentVisible.ts","../../src/query/core/buildInitiate.ts","../../src/query/core/index.ts"],"names":["QueryStatus","QueryStatus2","flatten","arr","concat","_iPO","isPlainObject","copyWithStructuralSharing","oldObj","newObj","Array","isArray","newKeys","Object","keys","oldKeys","isSameObject","length","mergeObj","key","isPlainObject2","defaultFetchFn","args","fetch","defaultValidateStatus","response","status","handleResponse","async","responseHandler","text","JSON","parse","stripUndefined","obj","copy","__spreadValues","k","v","entries","fetchBaseQuery","_a","_b","baseUrl","prepareHeaders","x","fetchFn","paramsSerializer","baseFetchOptions","__objRest","console","warn","arg","api","signal","getState","extra","endpoint","forced","type","meta","_a2","url","method","headers","Headers","body","params","validateStatus","rest","config","__spreadProps","body2","has","toJSON","set","get","trim","startsWith","isJsonContentType","stringify","divider","indexOf","URLSearchParams","base","RegExp","test","isAbsoluteUrl","replace","withoutTrailingSlash","withoutLeadingSlash","joinUrls","request","Request","clone","e","error","String","responseClone","resultData","responseText","handleResponseError","Promise","all","then","r","originalStatus","data","HandledError","constructor","value","this","defaultBackoff","attempt","maxRetries","attempts","Math","min","timeout","random","resolve","setTimeout","res","retry","assign","baseQuery","defaultOptions","extraOptions","options","backoff","retry2","result","throwImmediately","fail","createAction","DefinitionType","DefinitionType2","onFocus","onFocusLost","onOnline","onOffline","initialized","setupListeners","dispatch","customHandler","handleFocus","handleOnline","handleOffline","handleVisibilityChange","window","document","visibilityState","addEventListener","removeEventListener","defaultHandler","createNextState","createSelector","calculateProvidedBy","description","queryArg","assertTagTypes","map","expandTagDescription","combineReducers","createAction2","createSlice","isAnyOf","isFulfilled2","isRejectedWithValue2","isAllOf","isFulfilled","isPending","isRejected","isRejectedWithValue","isDraftable","produceWithPatches","createAsyncThunk","defaultTransformResponse","baseQueryReturnValue","calculateProvidedByThunk","action","endpointDefinitions","assertTagType","endpointName","payload","originalArgs","baseQueryMeta","applyPatches","updateQuerySubstateIfExists","state","queryCacheKey","update","substate","getMutationCacheKey","id","fixedCacheKey","requestId","updateMutationSubstateIfExists","initialState","skipToken","Symbol","for","skipSelector","initialSubState","uninitialized","defaultQuerySubState","defaultMutationSubState","isPlainObject3","defaultSerializeQueryArgs","queryArgs","sort","reduce","acc","key2","nanoid","defaultMemoize","buildCreateApi","modules","extractRehydrationInfo","call","reducerPath","optionsWithDefaults","serializeQueryArgs","keepUnusedDataFor","refetchOnMountOrArgChange","refetchOnFocus","refetchOnReconnect","tagTypes","context","batch","fn","apiUid","hasRehydrationInfo","injectEndpoints","inject","evaluatedEndpoints","endpoints","query","mutation","definition","overrideExisting","m","initializedModules","injectEndpoint","enhanceEndpoints","addTagTypes","eT","includes","push","partialDefinition","init","fakeBaseQuery","Error","compose","createAction3","build","removeQueryResult","unsubscribeQueryResult","internalActions","mwApi","currentRemovalTimeouts","next","match","handleUnsubscribe","queries","util","resetApiState","clearTimeout","queryState","api2","endpointDefinition","currentTimeout","subscriptions","isAnyOf2","isFulfilled3","isRejectedWithValue3","build2","mutationThunk","refetchQuery","invalidateTags","tags","rootState","toInvalidate","selectInvalidatedBy","valuesArray","from","values","querySubState","subscriptionSubState","build3","queryThunk","currentPolls","updateSubscriptionOptions","updatePollingInterval","pending","rejected","condition","fulfilled","startNextPoll","cleanupPollForKey","clearPolls","lowestPollingInterval","findLowestPollingInterval","Number","isFinite","currentPoll","nextPollTimestamp","Date","now","currentInterval","pollingInterval","existingPoll","subscribers","POSITIVE_INFINITY","subscription","build4","refetchValidQueries","some","sub","every","isAsyncThunkAction","isFulfilled4","neverResolvedError","build5","isQueryThunk","isMutationThunk","isFullfilledThunk","lifecycleMap","stateBefore","cacheKey","removeMutationResult","getCacheKey","oldState","handleNewKey","mutations","lifecycle","valueResolved","cacheEntryRemoved","cacheKey2","mwApi2","onCacheEntryAdded","cacheDataLoaded","race","catch","selector","select","_","__","extra2","lifecycleApi","getCacheEntry","updateCachedData","updateRecipe","updateQueryData","runningHandler","isPending2","isRejected2","isFulfilled5","build6","isPendingThunk","isRejectedThunk","_c","onQueryStarted","queryFulfilled","reject","rejectedWithValue","isUnhandledError","build7","initialized2","middlewareRegistered","safeAssign","target","enablePatches","coreModuleName","coreModule","name","tag","patchQueryData","prefetch","buildMatchThunkActions","executeEndpoint","rejectWithValue","fulfillWithValue","transformResponse","baseQueryApi","isForcedQuery","queryFn","arg2","fulfilledTimeStamp","_d","requestState","baseFetchOnMountOrArgChange","fulfilledVal","refetchVal","forceRefetch","subscribe","matchesEndpoint","getPendingMeta","startedTimeStamp","dispatchConditionRejection","force","hasTheForce","maxAge","hasMaxAge","ifOlderThan","queryAction","force2","initiate","latestStateValue","lastFulfilledTs","currentState","ret","patches","inversePatches","undo","op","path","queryResultPatched","thunk","matchPending","matchFulfilled","matchRejected","buildThunks","reducer","actions","sliceActions","definitions","querySlice","reducers","draft","extraReducers","builder","addCase","structuralSharing","addMatcher","entry","mutationSlice","track","invalidationSlice","tagTypeSubscriptions","idSubscriptions","foundAt","splice","provided","incomingTags","cacheKeys","subscribedQueries","providedTags","subscriptionSlice","subscriptionOptions","configSlice","online","navigator","onLine","focused","combinedReducer","unsubscribeMutationResult","buildSlice","defineProperty","middleware","middlewareActions","input","middlewares","build8","applied","middleware2","override","buildMiddleware","buildQuerySelector","buildMutationSelector","selectQuerySubState","selectInternalState","internalState","withRequestFlags","mutationId","selectMutationSubstate","apiState","Set","invalidateSubscriptions","invalidate","add","isUninitialized","isLoading","isSuccess","isError","buildSelectors","buildInitiateQuery","buildInitiateMutation","getRunningOperationPromises","getRunningOperationPromise","runningQueries","runningMutations","thunkResult","abort","statePromise","refetch","unsubscribe","unwrap","returnValuePromise","reset","filter","t","argOrRequestId","buildInitiate","anyApi","createApi"],"mappings":"IAiCYA,EAAAC,0jBAAAA,EAAAD,IAAAA,EAAA,KACV,cAAgB,gBAChBC,EAAA,QAAU,UACVA,EAAA,UAAY,YACZA,EAAA,SAAW,WChCN,IAAMC,EAAWC,GAAwB,GAAGC,UAAUD,2BCL7DE,MAAA,mBAGA,IAAMC,EAAqCD,EAGpC,SAAAE,EAAmCC,EAAaC,GACrD,GACED,IAAWC,KAERH,EAAcE,IAAWF,EAAcG,IACvCC,MAAMC,QAAQH,IAAWE,MAAMC,QAAQF,IAG1C,OAAOA,EAET,MAAMG,EAAUC,OAAOC,KAAKL,GACtBM,EAAUF,OAAOC,KAAKN,GAE5B,IAAIQ,EAAeJ,EAAQK,SAAWF,EAAQE,OAC9C,MAAMC,EAAgBR,MAAMC,QAAQF,GAAU,GAAK,GACnD,IAAA,MAAWU,KAAOP,EAChBM,EAASC,GAAOZ,EAA0BC,EAAOW,GAAMV,EAAOU,IAC1DH,IAAcA,EAAeR,EAAOW,KAASD,EAASC,IAE5D,OAAOH,EAAeR,EAASU,0BCxBjCE,MAAA,mBAiCA,IAAMC,EAA+B,IAAIC,IAASC,SAASD,GAErDE,EAAyBC,GAC7BA,EAASC,QAAU,KAAOD,EAASC,QAAU,IAKz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C,2BAAAA,KAGK,CACLlH,KAAMF,GACNlI,eAAe5D,EAAcwD,GA9fnC,IAAAtM,EA+fQ,MAAM+c,EAASnc,EAOf,OAAAZ,EAAA+c,EAAO5Q,WAAPrD,KAAA9I,EAAA8I,GAAmC,IACbwD,EhB7InBpL,OAAS4E,EAAesG,MgB8IzBqI,GACEsI,EAAO5Q,UAAUrD,GACjB,CACEkK,OAAQ2H,EAAmB7R,EAAcwD,GACzCwK,SAAU+E,EAAmB/S,EAAcwD,IAE7C4I,EAAuBzF,EAAY3G,IAEPwD,EhBhJ7BpL,OAAS4E,EAAeuG,UgBiJzBoI,GACEsI,EAAO5Q,UAAUrD,GACjB,CACEkK,OAAQ4H,IACR9D,SAAUgF,EAAsBhT,IAElCoM,EAAuBtG,EAAe9F,SIphB5CkU,GAA4BjS,GAAe8J","sourcesContent":["import type { SerializedError } from '@reduxjs/toolkit'\r\nimport type { BaseQueryError } from '../baseQueryTypes'\r\nimport type {\r\n QueryDefinition,\r\n MutationDefinition,\r\n EndpointDefinitions,\r\n BaseEndpointDefinition,\r\n ResultTypeFrom,\r\n QueryArgFrom,\r\n} from '../endpointDefinitions'\r\nimport type { Id, WithRequiredProp } from '../tsHelpers'\r\n\r\nexport type QueryCacheKey = string & { _type: 'queryCacheKey' }\r\nexport type QuerySubstateIdentifier = { queryCacheKey: QueryCacheKey }\r\nexport type MutationSubstateIdentifier =\r\n | {\r\n requestId: string\r\n fixedCacheKey?: string\r\n }\r\n | {\r\n requestId?: string\r\n fixedCacheKey: string\r\n }\r\n\r\nexport type RefetchConfigOptions = {\r\n refetchOnMountOrArgChange: boolean | number\r\n refetchOnReconnect: boolean\r\n refetchOnFocus: boolean\r\n}\r\n\r\n/**\r\n * Strings describing the query state at any given time.\r\n */\r\nexport enum QueryStatus {\r\n uninitialized = 'uninitialized',\r\n pending = 'pending',\r\n fulfilled = 'fulfilled',\r\n rejected = 'rejected',\r\n}\r\n\r\nexport type RequestStatusFlags =\r\n | {\r\n status: QueryStatus.uninitialized\r\n isUninitialized: true\r\n isLoading: false\r\n isSuccess: false\r\n isError: false\r\n }\r\n | {\r\n status: QueryStatus.pending\r\n isUninitialized: false\r\n isLoading: true\r\n isSuccess: false\r\n isError: false\r\n }\r\n | {\r\n status: QueryStatus.fulfilled\r\n isUninitialized: false\r\n isLoading: false\r\n isSuccess: true\r\n isError: false\r\n }\r\n | {\r\n status: QueryStatus.rejected\r\n isUninitialized: false\r\n isLoading: false\r\n isSuccess: false\r\n isError: true\r\n }\r\n\r\nexport function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags {\r\n return {\r\n status,\r\n isUninitialized: status === QueryStatus.uninitialized,\r\n isLoading: status === QueryStatus.pending,\r\n isSuccess: status === QueryStatus.fulfilled,\r\n isError: status === QueryStatus.rejected,\r\n } as any\r\n}\r\n\r\nexport type SubscriptionOptions = {\r\n /**\r\n * How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).\r\n */\r\n pollingInterval?: number\r\n /**\r\n * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\r\n *\r\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\r\n *\r\n * Note: requires [`setupListeners`](./setupListeners) to have been called.\r\n */\r\n refetchOnReconnect?: boolean\r\n /**\r\n * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\r\n *\r\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\r\n *\r\n * Note: requires [`setupListeners`](./setupListeners) to have been called.\r\n */\r\n refetchOnFocus?: boolean\r\n}\r\nexport type Subscribers = { [requestId: string]: SubscriptionOptions }\r\nexport type QueryKeys<Definitions extends EndpointDefinitions> = {\r\n [K in keyof Definitions]: Definitions[K] extends QueryDefinition<\r\n any,\r\n any,\r\n any,\r\n any\r\n >\r\n ? K\r\n : never\r\n}[keyof Definitions]\r\nexport type MutationKeys<Definitions extends EndpointDefinitions> = {\r\n [K in keyof Definitions]: Definitions[K] extends MutationDefinition<\r\n any,\r\n any,\r\n any,\r\n any\r\n >\r\n ? K\r\n : never\r\n}[keyof Definitions]\r\n\r\ntype BaseQuerySubState<D extends BaseEndpointDefinition<any, any, any>> = {\r\n /**\r\n * The argument originally passed into the hook or `initiate` action call\r\n */\r\n originalArgs: QueryArgFrom<D>\r\n /**\r\n * A unique ID associated with the request\r\n */\r\n requestId: string\r\n /**\r\n * The received data from the query\r\n */\r\n data?: ResultTypeFrom<D>\r\n /**\r\n * The received error if applicable\r\n */\r\n error?:\r\n | SerializedError\r\n | (D extends QueryDefinition<any, infer BaseQuery, any, any>\r\n ? BaseQueryError<BaseQuery>\r\n : never)\r\n /**\r\n * The name of the endpoint associated with the query\r\n */\r\n endpointName: string\r\n /**\r\n * Time that the latest query started\r\n */\r\n startedTimeStamp: number\r\n /**\r\n * Time that the latest query was fulfilled\r\n */\r\n fulfilledTimeStamp?: number\r\n}\r\n\r\nexport type QuerySubState<D extends BaseEndpointDefinition<any, any, any>> = Id<\r\n | ({\r\n status: QueryStatus.fulfilled\r\n } & WithRequiredProp<\r\n BaseQuerySubState<D>,\r\n 'data' | 'fulfilledTimeStamp'\r\n > & { error: undefined })\r\n | ({\r\n status: QueryStatus.pending\r\n } & BaseQuerySubState<D>)\r\n | ({\r\n status: QueryStatus.rejected\r\n } & WithRequiredProp<BaseQuerySubState<D>, 'error'>)\r\n | {\r\n status: QueryStatus.uninitialized\r\n originalArgs?: undefined\r\n data?: undefined\r\n error?: undefined\r\n requestId?: undefined\r\n endpointName?: string\r\n startedTimeStamp?: undefined\r\n fulfilledTimeStamp?: undefined\r\n }\r\n>\r\n\r\ntype BaseMutationSubState<D extends BaseEndpointDefinition<any, any, any>> = {\r\n requestId: string\r\n data?: ResultTypeFrom<D>\r\n error?:\r\n | SerializedError\r\n | (D extends MutationDefinition<any, infer BaseQuery, any, any>\r\n ? BaseQueryError<BaseQuery>\r\n : never)\r\n endpointName: string\r\n startedTimeStamp: number\r\n fulfilledTimeStamp?: number\r\n}\r\n\r\nexport type MutationSubState<D extends BaseEndpointDefinition<any, any, any>> =\r\n | (({\r\n status: QueryStatus.fulfilled\r\n } & WithRequiredProp<\r\n BaseMutationSubState<D>,\r\n 'data' | 'fulfilledTimeStamp'\r\n >) & { error: undefined })\r\n | (({\r\n status: QueryStatus.pending\r\n } & BaseMutationSubState<D>) & { data?: undefined })\r\n | ({\r\n status: QueryStatus.rejected\r\n } & WithRequiredProp<BaseMutationSubState<D>, 'error'>)\r\n | {\r\n requestId?: undefined\r\n status: QueryStatus.uninitialized\r\n data?: undefined\r\n error?: undefined\r\n endpointName?: string\r\n startedTimeStamp?: undefined\r\n fulfilledTimeStamp?: undefined\r\n }\r\n\r\nexport type CombinedState<\r\n D extends EndpointDefinitions,\r\n E extends string,\r\n ReducerPath extends string\r\n> = {\r\n queries: QueryState<D>\r\n mutations: MutationState<D>\r\n provided: InvalidationState<E>\r\n subscriptions: SubscriptionState\r\n config: ConfigState<ReducerPath>\r\n}\r\n\r\nexport type InvalidationState<TagTypes extends string> = {\r\n [_ in TagTypes]: {\r\n [id: string]: Array<QueryCacheKey>\r\n [id: number]: Array<QueryCacheKey>\r\n }\r\n}\r\n\r\nexport type QueryState<D extends EndpointDefinitions> = {\r\n [queryCacheKey: string]: QuerySubState<D[string]> | undefined\r\n}\r\n\r\nexport type SubscriptionState = {\r\n [queryCacheKey: string]: Subscribers | undefined\r\n}\r\n\r\nexport type ConfigState<ReducerPath> = RefetchConfigOptions & {\r\n reducerPath: ReducerPath\r\n online: boolean\r\n focused: boolean\r\n middlewareRegistered: boolean | 'conflict'\r\n} & ModifiableConfigState\r\n\r\nexport type ModifiableConfigState = {\r\n keepUnusedDataFor: number\r\n} & RefetchConfigOptions\r\n\r\nexport type MutationState<D extends EndpointDefinitions> = {\r\n [requestId: string]: MutationSubState<D[string]> | undefined\r\n}\r\n\r\nexport type RootState<\r\n Definitions extends EndpointDefinitions,\r\n TagTypes extends string,\r\n ReducerPath extends string\r\n> = {\r\n [P in ReducerPath]: CombinedState<Definitions, TagTypes, P>\r\n}\r\n","/**\r\n * Alternative to `Array.flat(1)`\r\n * @param arr An array like [1,2,3,[1,2]]\r\n * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat\r\n */\r\nexport const flatten = (arr: readonly any[]) => [].concat(...arr)\r\n","import { isPlainObject as _iPO } from '@reduxjs/toolkit'\r\n\r\n// remove type guard\r\nconst isPlainObject: (_: any) => boolean = _iPO\r\n\r\nexport function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T\r\nexport function copyWithStructuralSharing(oldObj: any, newObj: any): any {\r\n if (\r\n oldObj === newObj ||\r\n !(\r\n (isPlainObject(oldObj) && isPlainObject(newObj)) ||\r\n (Array.isArray(oldObj) && Array.isArray(newObj))\r\n )\r\n ) {\r\n return newObj\r\n }\r\n const newKeys = Object.keys(newObj)\r\n const oldKeys = Object.keys(oldObj)\r\n\r\n let isSameObject = newKeys.length === oldKeys.length\r\n const mergeObj: any = Array.isArray(newObj) ? [] : {}\r\n for (const key of newKeys) {\r\n mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key])\r\n if (isSameObject) isSameObject = oldObj[key] === mergeObj[key]\r\n }\r\n return isSameObject ? oldObj : mergeObj\r\n}\r\n","import { joinUrls } from './utils'\r\nimport { isPlainObject } from '@reduxjs/toolkit'\r\nimport type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes'\r\nimport type { MaybePromise, Override } from './tsHelpers'\r\n\r\nexport type ResponseHandler =\r\n | 'json'\r\n | 'text'\r\n | ((response: Response) => Promise<any>)\r\n\r\ntype CustomRequestInit = Override<\r\n RequestInit,\r\n {\r\n headers?:\r\n | Headers\r\n | string[][]\r\n | Record<string, string | undefined>\r\n | undefined\r\n }\r\n>\r\n\r\nexport interface FetchArgs extends CustomRequestInit {\r\n url: string\r\n params?: Record<string, any>\r\n body?: any\r\n responseHandler?: ResponseHandler\r\n validateStatus?: (response: Response, body: any) => boolean\r\n}\r\n\r\n/**\r\n * A mini-wrapper that passes arguments straight through to\r\n * {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.\r\n * Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.\r\n */\r\nconst defaultFetchFn: typeof fetch = (...args) => fetch(...args)\r\n\r\nconst defaultValidateStatus = (response: Response) =>\r\n response.status >= 200 && response.status <= 299\r\n\r\nconst isJsonContentType = (headers: Headers) =>\r\n headers.get('content-type')?.trim()?.startsWith('application/json')\r\n\r\nconst handleResponse = async (\r\n response: Response,\r\n responseHandler: ResponseHandler\r\n) => {\r\n if (typeof responseHandler === 'function') {\r\n return responseHandler(response)\r\n }\r\n\r\n if (responseHandler === 'text') {\r\n return response.text()\r\n }\r\n\r\n if (responseHandler === 'json') {\r\n const text = await response.text()\r\n return text.length ? JSON.parse(text) : null\r\n }\r\n}\r\n\r\nexport type FetchBaseQueryError =\r\n | {\r\n /**\r\n * * `number`:\r\n * HTTP status code\r\n */\r\n status: number\r\n data: unknown\r\n }\r\n | {\r\n /**\r\n * * `\"FETCH_ERROR\"`:\r\n * An error that occurred during execution of `fetch` or the `fetchFn` callback option\r\n **/\r\n status: 'FETCH_ERROR'\r\n data?: undefined\r\n error: string\r\n }\r\n | {\r\n /**\r\n * * `\"PARSING_ERROR\"`:\r\n * An error happened during parsing.\r\n * Most likely a non-JSON-response was returned with the default `responseHandler` \"JSON\",\r\n * or an error occurred while executing a custom `responseHandler`.\r\n **/\r\n status: 'PARSING_ERROR'\r\n originalStatus: number\r\n data: string\r\n error: string\r\n }\r\n | {\r\n /**\r\n * * `\"CUSTOM_ERROR\"`:\r\n * A custom error type that you can return from your `queryFn` where another error might not make sense.\r\n **/\r\n status: 'CUSTOM_ERROR'\r\n data?: unknown\r\n error: string\r\n }\r\n\r\nfunction stripUndefined(obj: any) {\r\n if (!isPlainObject(obj)) {\r\n return obj\r\n }\r\n const copy: Record<string, any> = { ...obj }\r\n for (const [k, v] of Object.entries(copy)) {\r\n if (typeof v === 'undefined') delete copy[k]\r\n }\r\n return copy\r\n}\r\n\r\nexport type FetchBaseQueryArgs = {\r\n baseUrl?: string\r\n prepareHeaders?: (\r\n headers: Headers,\r\n api: Pick<\r\n BaseQueryApi,\r\n 'getState' | 'extra' | 'endpoint' | 'type' | 'forced'\r\n >\r\n ) => MaybePromise<Headers>\r\n fetchFn?: (\r\n input: RequestInfo,\r\n init?: RequestInit | undefined\r\n ) => Promise<Response>\r\n paramsSerializer?: (params: Record<string, any>) => string\r\n} & RequestInit\r\n\r\nexport type FetchBaseQueryMeta = { request: Request; response?: Response }\r\n\r\n/**\r\n * This is a very small wrapper around fetch that aims to simplify requests.\r\n *\r\n * @example\r\n * ```ts\r\n * const baseQuery = fetchBaseQuery({\r\n * baseUrl: 'https://api.your-really-great-app.com/v1/',\r\n * prepareHeaders: (headers, { getState }) => {\r\n * const token = (getState() as RootState).auth.token;\r\n * // If we have a token set in state, let's assume that we should be passing it.\r\n * if (token) {\r\n * headers.set('authorization', `Bearer ${token}`);\r\n * }\r\n * return headers;\r\n * },\r\n * })\r\n * ```\r\n *\r\n * @param {string} baseUrl\r\n * The base URL for an API service.\r\n * Typically in the format of https://example.com/\r\n *\r\n * @param {(headers: Headers, api: { getState: () => unknown; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders\r\n * An optional function that can be used to inject headers on requests.\r\n * Provides a Headers object, as well as most of the `BaseQueryApi` (`dispatch` is not available).\r\n * Useful for setting authentication or headers that need to be set conditionally.\r\n *\r\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Headers\r\n *\r\n * @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn\r\n * Accepts a custom `fetch` function if you do not want to use the default on the window.\r\n * Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`\r\n *\r\n * @param {(params: Record<string, unknown>) => string} paramsSerializer\r\n * An optional function that can be used to stringify querystring parameters.\r\n */\r\nexport function fetchBaseQuery({\r\n baseUrl,\r\n prepareHeaders = (x) => x,\r\n fetchFn = defaultFetchFn,\r\n paramsSerializer,\r\n ...baseFetchOptions\r\n}: FetchBaseQueryArgs = {}): BaseQueryFn<\r\n string | FetchArgs,\r\n unknown,\r\n FetchBaseQueryError,\r\n {},\r\n FetchBaseQueryMeta\r\n> {\r\n if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {\r\n console.warn(\r\n 'Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.'\r\n )\r\n }\r\n return async (arg, api) => {\r\n const { signal, getState, extra, endpoint, forced, type } = api\r\n let meta: FetchBaseQueryMeta | undefined\r\n let {\r\n url,\r\n method = 'GET' as const,\r\n headers = new Headers({}),\r\n body = undefined,\r\n params = undefined,\r\n responseHandler = 'json' as const,\r\n validateStatus = defaultValidateStatus,\r\n ...rest\r\n } = typeof arg == 'string' ? { url: arg } : arg\r\n let config: RequestInit = {\r\n ...baseFetchOptions,\r\n method,\r\n signal,\r\n body,\r\n ...rest,\r\n }\r\n\r\n config.headers = await prepareHeaders(\r\n new Headers(stripUndefined(headers)),\r\n { getState, extra, endpoint, forced, type }\r\n )\r\n\r\n // Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc.\r\n const isJsonifiable = (body: any) =>\r\n typeof body === 'object' &&\r\n (isPlainObject(body) ||\r\n Array.isArray(body) ||\r\n typeof body.toJSON === 'function')\r\n\r\n if (!config.headers.has('content-type') && isJsonifiable(body)) {\r\n config.headers.set('content-type', 'application/json')\r\n }\r\n\r\n if (body && isJsonContentType(config.headers)) {\r\n config.body = JSON.stringify(body)\r\n }\r\n\r\n if (params) {\r\n const divider = ~url.indexOf('?') ? '&' : '?'\r\n const query = paramsSerializer\r\n ? paramsSerializer(params)\r\n : new URLSearchParams(stripUndefined(params))\r\n url += divider + query\r\n }\r\n\r\n url = joinUrls(baseUrl, url)\r\n\r\n const request = new Request(url, config)\r\n const requestClone = request.clone()\r\n meta = { request: requestClone }\r\n\r\n let response\r\n try {\r\n response = await fetchFn(request)\r\n } catch (e) {\r\n return { error: { status: 'FETCH_ERROR', error: String(e) }, meta }\r\n }\r\n const responseClone = response.clone()\r\n\r\n meta.response = responseClone\r\n\r\n let resultData: any\r\n let responseText: string = ''\r\n try {\r\n let handleResponseError\r\n await Promise.all([\r\n handleResponse(response, responseHandler).then(\r\n (r) => (resultData = r),\r\n (e) => (handleResponseError = e)\r\n ),\r\n // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182\r\n // we *have* to \"use up\" both streams at the same time or they will stop running in node-fetch scenarios\r\n responseClone.text().then(\r\n (r) => (responseText = r),\r\n () => {}\r\n ),\r\n ])\r\n if (handleResponseError) throw handleResponseError\r\n } catch (e) {\r\n return {\r\n error: {\r\n status: 'PARSING_ERROR',\r\n originalStatus: response.status,\r\n data: responseText,\r\n error: String(e),\r\n },\r\n meta,\r\n }\r\n }\r\n\r\n return validateStatus(response, resultData)\r\n ? {\r\n data: resultData,\r\n meta,\r\n }\r\n : {\r\n error: {\r\n status: response.status,\r\n data: resultData,\r\n },\r\n meta,\r\n }\r\n }\r\n}\r\n","import { isAbsoluteUrl } from './isAbsoluteUrl'\r\n\r\nconst withoutTrailingSlash = (url: string) => url.replace(/\\/$/, '')\r\nconst withoutLeadingSlash = (url: string) => url.replace(/^\\//, '')\r\n\r\nexport function joinUrls(\r\n base: string | undefined,\r\n url: string | undefined\r\n): string {\r\n if (!base) {\r\n return url!\r\n }\r\n if (!url) {\r\n return base\r\n }\r\n\r\n if (isAbsoluteUrl(url)) {\r\n return url\r\n }\r\n\r\n base = withoutTrailingSlash(base)\r\n url = withoutLeadingSlash(url)\r\n\r\n return `${base}/${url}`\r\n}\r\n","/**\r\n * If either :// or // is present consider it to be an absolute url\r\n *\r\n * @param url string\r\n */\r\n\r\nexport function isAbsoluteUrl(url: string) {\r\n return new RegExp(`(^|:)//`).test(url)\r\n}\r\n","export class HandledError {\r\n constructor(\r\n public readonly value: any,\r\n public readonly meta: any = undefined\r\n ) {}\r\n}\r\n","import type { BaseQueryEnhancer } from './baseQueryTypes'\r\nimport { HandledError } from './HandledError'\r\n\r\n/**\r\n * Exponential backoff based on the attempt number.\r\n *\r\n * @remarks\r\n * 1. 600ms * random(0.4, 1.4)\r\n * 2. 1200ms * random(0.4, 1.4)\r\n * 3. 2400ms * random(0.4, 1.4)\r\n * 4. 4800ms * random(0.4, 1.4)\r\n * 5. 9600ms * random(0.4, 1.4)\r\n *\r\n * @param attempt - Current attempt\r\n * @param maxRetries - Maximum number of retries\r\n */\r\nasync function defaultBackoff(attempt: number = 0, maxRetries: number = 5) {\r\n const attempts = Math.min(attempt, maxRetries)\r\n\r\n const timeout = ~~((Math.random() + 0.4) * (300 << attempts)) // Force a positive int in the case we make this an option\r\n await new Promise((resolve) =>\r\n setTimeout((res: any) => resolve(res), timeout)\r\n )\r\n}\r\n\r\nexport interface RetryOptions {\r\n /**\r\n * How many times the query will be retried (default: 5)\r\n */\r\n maxRetries?: number\r\n /**\r\n * Function used to determine delay between retries\r\n */\r\n backoff?: (attempt: number, maxRetries: number) => Promise<void>\r\n}\r\n\r\nfunction fail(e: any): never {\r\n throw Object.assign(new HandledError({ error: e }), {\r\n throwImmediately: true,\r\n })\r\n}\r\n\r\nconst retryWithBackoff: BaseQueryEnhancer<\r\n unknown,\r\n RetryOptions,\r\n RetryOptions | void\r\n> = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {\r\n const options = {\r\n maxRetries: 5,\r\n backoff: defaultBackoff,\r\n ...defaultOptions,\r\n ...extraOptions,\r\n }\r\n let retry = 0\r\n\r\n while (true) {\r\n try {\r\n const result = await baseQuery(args, api, extraOptions)\r\n // baseQueries _should_ return an error property, so we should check for that and throw it to continue retrying\r\n if (result.error) {\r\n throw new HandledError(result)\r\n }\r\n return result\r\n } catch (e) {\r\n retry++\r\n if (e.throwImmediately || retry > options.maxRetries) {\r\n if (e instanceof HandledError) {\r\n return e.value\r\n }\r\n\r\n // We don't know what this is, so we have to rethrow it\r\n throw e\r\n }\r\n await options.backoff(retry, options.maxRetries)\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * A utility that can wrap `baseQuery` in the API definition to provide retries with a basic exponential backoff.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"Retry every request 5 times by default\"\r\n * import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'\r\n * interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n * type PostsResponse = Post[]\r\n *\r\n * // maxRetries: 5 is the default, and can be omitted. Shown for documentation purposes.\r\n * const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), { maxRetries: 5 });\r\n * export const api = createApi({\r\n * baseQuery: staggeredBaseQuery,\r\n * endpoints: (build) => ({\r\n * getPosts: build.query<PostsResponse, void>({\r\n * query: () => ({ url: 'posts' }),\r\n * }),\r\n * getPost: build.query<PostsResponse, string>({\r\n * query: (id) => ({ url: `post/${id}` }),\r\n * extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint\r\n * }),\r\n * }),\r\n * });\r\n *\r\n * export const { useGetPostsQuery, useGetPostQuery } = api;\r\n * ```\r\n */\r\nexport const retry = /* @__PURE__ */ Object.assign(retryWithBackoff, { fail })\r\n","import type {\r\n ThunkDispatch,\r\n ActionCreatorWithoutPayload, // Workaround for API-Extractor\r\n} from '@reduxjs/toolkit'\r\nimport { createAction } from '@reduxjs/toolkit'\r\n\r\nexport const onFocus = /* @__PURE__ */ createAction('__rtkq/focused')\r\nexport const onFocusLost = /* @__PURE__ */ createAction('__rtkq/unfocused')\r\nexport const onOnline = /* @__PURE__ */ createAction('__rtkq/online')\r\nexport const onOffline = /* @__PURE__ */ createAction('__rtkq/offline')\r\n\r\nlet initialized = false\r\n\r\n/**\r\n * A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.\r\n * It requires the dispatch method from your store.\r\n * Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,\r\n * but you have the option of providing a callback for more granular control.\r\n *\r\n * @example\r\n * ```ts\r\n * setupListeners(store.dispatch)\r\n * ```\r\n *\r\n * @param dispatch - The dispatch method from your store\r\n * @param customHandler - An optional callback for more granular control over listener behavior\r\n * @returns Return value of the handler.\r\n * The default handler returns an `unsubscribe` method that can be called to remove the listeners.\r\n */\r\nexport function setupListeners(\r\n dispatch: ThunkDispatch<any, any, any>,\r\n customHandler?: (\r\n dispatch: ThunkDispatch<any, any, any>,\r\n actions: {\r\n onFocus: typeof onFocus\r\n onFocusLost: typeof onFocusLost\r\n onOnline: typeof onOnline\r\n onOffline: typeof onOffline\r\n }\r\n ) => () => void\r\n) {\r\n function defaultHandler() {\r\n const handleFocus = () => dispatch(onFocus())\r\n const handleFocusLost = () => dispatch(onFocusLost())\r\n const handleOnline = () => dispatch(onOnline())\r\n const handleOffline = () => dispatch(onOffline())\r\n const handleVisibilityChange = () => {\r\n if (window.document.visibilityState === 'visible') {\r\n handleFocus()\r\n } else {\r\n handleFocusLost()\r\n }\r\n }\r\n\r\n if (!initialized) {\r\n if (typeof window !== 'undefined' && window.addEventListener) {\r\n // Handle focus events\r\n window.addEventListener(\r\n 'visibilitychange',\r\n handleVisibilityChange,\r\n false\r\n )\r\n window.addEventListener('focus', handleFocus, false)\r\n\r\n // Handle connection events\r\n window.addEventListener('online', handleOnline, false)\r\n window.addEventListener('offline', handleOffline, false)\r\n initialized = true\r\n }\r\n }\r\n const unsubscribe = () => {\r\n window.removeEventListener('focus', handleFocus)\r\n window.removeEventListener('visibilitychange', handleVisibilityChange)\r\n window.removeEventListener('online', handleOnline)\r\n window.removeEventListener('offline', handleOffline)\r\n initialized = false\r\n }\r\n return unsubscribe\r\n }\r\n\r\n return customHandler\r\n ? customHandler(dispatch, { onFocus, onFocusLost, onOffline, onOnline })\r\n : defaultHandler()\r\n}\r\n","import type { AnyAction, ThunkDispatch } from '@reduxjs/toolkit'\r\nimport type { RootState } from './core/apiState'\r\nimport type {\r\n BaseQueryExtraOptions,\r\n BaseQueryFn,\r\n BaseQueryResult,\r\n BaseQueryArg,\r\n BaseQueryApi,\r\n QueryReturnValue,\r\n BaseQueryError,\r\n BaseQueryMeta,\r\n} from './baseQueryTypes'\r\nimport type {\r\n HasRequiredProps,\r\n MaybePromise,\r\n OmitFromUnion,\r\n CastAny,\r\n} from './tsHelpers'\r\nimport type { NEVER } from './fakeBaseQuery'\r\n\r\nconst resultType = /* @__PURE__ */ Symbol()\r\nconst baseQuery = /* @__PURE__ */ Symbol()\r\n\r\ninterface EndpointDefinitionWithQuery<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType\r\n> {\r\n /**\r\n * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"query example\"\r\n *\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\r\n * interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n * type PostsResponse = Post[]\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * endpoints: (build) => ({\r\n * getPosts: build.query<PostsResponse, void>({\r\n * // highlight-start\r\n * query: () => 'posts',\r\n * // highlight-end\r\n * })\r\n * })\r\n * })\r\n * ```\r\n */\r\n query(arg: QueryArg): BaseQueryArg<BaseQuery>\r\n queryFn?: never\r\n /**\r\n * A function to manipulate the data returned by a query or mutation.\r\n */\r\n transformResponse?(\r\n baseQueryReturnValue: BaseQueryResult<BaseQuery>,\r\n meta: BaseQueryMeta<BaseQuery>,\r\n arg: QueryArg\r\n ): ResultType | Promise<ResultType>\r\n /**\r\n * Defaults to `true`.\r\n *\r\n * Most apps should leave this setting on. The only time it can be a performance issue\r\n * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\r\n * you're unable to paginate it.\r\n *\r\n * For details of how this works, please see the below. When it is set to `false`,\r\n * every request will cause subscribed components to rerender, even when the data has not changed.\r\n *\r\n * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\r\n */\r\n structuralSharing?: boolean\r\n}\r\n\r\ninterface EndpointDefinitionWithQueryFn<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType\r\n> {\r\n /**\r\n * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\r\n *\r\n * @example\r\n * ```ts\r\n * // codeblock-meta title=\"Basic queryFn example\"\r\n *\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\r\n * interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n * type PostsResponse = Post[]\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * endpoints: (build) => ({\r\n * getPosts: build.query<PostsResponse, void>({\r\n * query: () => 'posts',\r\n * }),\r\n * flipCoin: build.query<'heads' | 'tails', void>({\r\n * // highlight-start\r\n * queryFn(arg, queryApi, extraOptions, baseQuery) {\r\n * const randomVal = Math.random()\r\n * if (randomVal < 0.45) {\r\n * return { data: 'heads' }\r\n * }\r\n * if (randomVal < 0.9) {\r\n * return { data: 'tails' }\r\n * }\r\n * return { error: { status: 500, statusText: 'Internal Server Error', data: \"Coin landed on it's edge!\" } }\r\n * }\r\n * // highlight-end\r\n * })\r\n * })\r\n * })\r\n * ```\r\n */\r\n queryFn(\r\n arg: QueryArg,\r\n api: BaseQueryApi,\r\n extraOptions: BaseQueryExtraOptions<BaseQuery>,\r\n baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>\r\n ): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>>>\r\n query?: never\r\n transformResponse?: never\r\n /**\r\n * Defaults to `true`.\r\n *\r\n * Most apps should leave this setting on. The only time it can be a performance issue\r\n * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\r\n * you're unable to paginate it.\r\n *\r\n * For details of how this works, please see the below. When it is set to `false`,\r\n * every request will cause subscribed components to rerender, even when the data has not changed.\r\n *\r\n * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\r\n */\r\n structuralSharing?: boolean\r\n}\r\n\r\nexport type BaseEndpointDefinition<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType\r\n> = (\r\n | ([CastAny<BaseQueryResult<BaseQuery>, {}>] extends [NEVER]\r\n ? never\r\n : EndpointDefinitionWithQuery<QueryArg, BaseQuery, ResultType>)\r\n | EndpointDefinitionWithQueryFn<QueryArg, BaseQuery, ResultType>\r\n) & {\r\n /* phantom type */\r\n [resultType]?: ResultType\r\n /* phantom type */\r\n [baseQuery]?: BaseQuery\r\n} & HasRequiredProps<\r\n BaseQueryExtraOptions<BaseQuery>,\r\n { extraOptions: BaseQueryExtraOptions<BaseQuery> },\r\n { extraOptions?: BaseQueryExtraOptions<BaseQuery> }\r\n >\r\n\r\nexport enum DefinitionType {\r\n query = 'query',\r\n mutation = 'mutation',\r\n}\r\n\r\nexport type GetResultDescriptionFn<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n ErrorType,\r\n MetaType\r\n> = (\r\n result: ResultType | undefined,\r\n error: ErrorType | undefined,\r\n arg: QueryArg,\r\n meta: MetaType\r\n) => ReadonlyArray<TagDescription<TagTypes>>\r\n\r\nexport type FullTagDescription<TagType> = {\r\n type: TagType\r\n id?: number | string\r\n}\r\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>\r\nexport type ResultDescription<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n ErrorType,\r\n MetaType\r\n> =\r\n | ReadonlyArray<TagDescription<TagTypes>>\r\n | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>\r\n\r\n/** @deprecated please use `onQueryStarted` instead */\r\nexport interface QueryApi<ReducerPath extends string, Context extends {}> {\r\n /** @deprecated please use `onQueryStarted` instead */\r\n dispatch: ThunkDispatch<any, any, AnyAction>\r\n /** @deprecated please use `onQueryStarted` instead */\r\n getState(): RootState<any, any, ReducerPath>\r\n /** @deprecated please use `onQueryStarted` instead */\r\n extra: unknown\r\n /** @deprecated please use `onQueryStarted` instead */\r\n requestId: string\r\n /** @deprecated please use `onQueryStarted` instead */\r\n context: Context\r\n}\r\n\r\nexport interface QueryExtraOptions<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string = string\r\n> {\r\n type: DefinitionType.query\r\n /**\r\n * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.\r\n * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.\r\n * 1. `['Post']` - equivalent to `2`\r\n * 2. `[{ type: 'Post' }]` - equivalent to `1`\r\n * 3. `[{ type: 'Post', id: 1 }]`\r\n * 4. `(result, error, arg) => ['Post']` - equivalent to `5`\r\n * 5. `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`\r\n * 6. `(result, error, arg) => [{ type: 'Post', id: 1 }]`\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"providesTags example\"\r\n *\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\r\n * interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n * type PostsResponse = Post[]\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * tagTypes: ['Posts'],\r\n * endpoints: (build) => ({\r\n * getPosts: build.query<PostsResponse, void>({\r\n * query: () => 'posts',\r\n * // highlight-start\r\n * providesTags: (result) =>\r\n * result\r\n * ? [\r\n * ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\r\n * { type: 'Posts', id: 'LIST' },\r\n * ]\r\n * : [{ type: 'Posts', id: 'LIST' }],\r\n * // highlight-end\r\n * })\r\n * })\r\n * })\r\n * ```\r\n */\r\n providesTags?: ResultDescription<\r\n TagTypes,\r\n ResultType,\r\n QueryArg,\r\n BaseQueryError<BaseQuery>,\r\n BaseQueryMeta<BaseQuery>\r\n >\r\n /**\r\n * Not to be used. A query should not invalidate tags in the cache.\r\n */\r\n invalidatesTags?: never\r\n}\r\n\r\nexport type QueryDefinition<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n TagTypes extends string,\r\n ResultType,\r\n ReducerPath extends string = string\r\n> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> &\r\n QueryExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>\r\n\r\nexport interface MutationExtraOptions<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string = string\r\n> {\r\n type: DefinitionType.mutation\r\n /**\r\n * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.\r\n * Expects the same shapes as `providesTags`.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"invalidatesTags example\"\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\r\n * interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n * type PostsResponse = Post[]\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * tagTypes: ['Posts'],\r\n * endpoints: (build) => ({\r\n * getPosts: build.query<PostsResponse, void>({\r\n * query: () => 'posts',\r\n * providesTags: (result) =>\r\n * result\r\n * ? [\r\n * ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\r\n * { type: 'Posts', id: 'LIST' },\r\n * ]\r\n * : [{ type: 'Posts', id: 'LIST' }],\r\n * }),\r\n * addPost: build.mutation<Post, Partial<Post>>({\r\n * query(body) {\r\n * return {\r\n * url: `posts`,\r\n * method: 'POST',\r\n * body,\r\n * }\r\n * },\r\n * // highlight-start\r\n * invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\r\n * // highlight-end\r\n * }),\r\n * })\r\n * })\r\n * ```\r\n */\r\n invalidatesTags?: ResultDescription<\r\n TagTypes,\r\n ResultType,\r\n QueryArg,\r\n BaseQueryError<BaseQuery>,\r\n BaseQueryMeta<BaseQuery>\r\n >\r\n /**\r\n * Not to be used. A mutation should not provide tags to the cache.\r\n */\r\n providesTags?: never\r\n}\r\n\r\nexport type MutationDefinition<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n TagTypes extends string,\r\n ResultType,\r\n ReducerPath extends string = string\r\n> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> &\r\n MutationExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>\r\n\r\nexport type EndpointDefinition<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n TagTypes extends string,\r\n ResultType,\r\n ReducerPath extends string = string\r\n> =\r\n | QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>\r\n | MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>\r\n\r\nexport type EndpointDefinitions = Record<\r\n string,\r\n EndpointDefinition<any, any, any, any>\r\n>\r\n\r\nexport function isQueryDefinition(\r\n e: EndpointDefinition<any, any, any, any>\r\n): e is QueryDefinition<any, any, any, any> {\r\n return e.type === DefinitionType.query\r\n}\r\n\r\nexport function isMutationDefinition(\r\n e: EndpointDefinition<any, any, any, any>\r\n): e is MutationDefinition<any, any, any, any> {\r\n return e.type === DefinitionType.mutation\r\n}\r\n\r\nexport type EndpointBuilder<\r\n BaseQuery extends BaseQueryFn,\r\n TagTypes extends string,\r\n ReducerPath extends string\r\n> = {\r\n /**\r\n * An endpoint definition that retrieves data, and may provide tags to the cache.\r\n *\r\n * @example\r\n * ```js\r\n * // codeblock-meta title=\"Example of all query endpoint options\"\r\n * const api = createApi({\r\n * baseQuery,\r\n * endpoints: (build) => ({\r\n * getPost: build.query({\r\n * query: (id) => ({ url: `post/${id}` }),\r\n * // Pick out data and prevent nested properties in a hook or selector\r\n * transformResponse: (response) => response.data,\r\n * // `result` is the server response\r\n * providesTags: (result, error, id) => [{ type: 'Post', id }],\r\n * // trigger side effects or optimistic updates\r\n * onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},\r\n * // handle subscriptions etc\r\n * onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},\r\n * }),\r\n * }),\r\n *});\r\n *```\r\n */\r\n query<ResultType, QueryArg>(\r\n definition: OmitFromUnion<\r\n QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>,\r\n 'type'\r\n >\r\n ): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>\r\n /**\r\n * An endpoint definition that alters data on the server or will possibly invalidate the cache.\r\n *\r\n * @example\r\n * ```js\r\n * // codeblock-meta title=\"Example of all mutation endpoint options\"\r\n * const api = createApi({\r\n * baseQuery,\r\n * endpoints: (build) => ({\r\n * updatePost: build.mutation({\r\n * query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),\r\n * // Pick out data and prevent nested properties in a hook or selector\r\n * transformResponse: (response) => response.data,\r\n * // `result` is the server response\r\n * invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\r\n * // trigger side effects or optimistic updates\r\n * onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},\r\n * // handle subscriptions etc\r\n * onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},\r\n * }),\r\n * }),\r\n * });\r\n * ```\r\n */\r\n mutation<ResultType, QueryArg>(\r\n definition: OmitFromUnion<\r\n MutationDefinition<\r\n QueryArg,\r\n BaseQuery,\r\n TagTypes,\r\n ResultType,\r\n ReducerPath\r\n >,\r\n 'type'\r\n >\r\n ): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>\r\n}\r\n\r\nexport type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T\r\n\r\nexport function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(\r\n description:\r\n | ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType>\r\n | undefined,\r\n result: ResultType | undefined,\r\n error: ErrorType | undefined,\r\n queryArg: QueryArg,\r\n meta: MetaType | undefined,\r\n assertTagTypes: AssertTagTypes\r\n): readonly FullTagDescription<string>[] {\r\n if (isFunction(description)) {\r\n return description(\r\n result as ResultType,\r\n error as undefined,\r\n queryArg,\r\n meta as MetaType\r\n )\r\n .map(expandTagDescription)\r\n .map(assertTagTypes)\r\n }\r\n if (Array.isArray(description)) {\r\n return description.map(expandTagDescription).map(assertTagTypes)\r\n }\r\n return []\r\n}\r\n\r\nfunction isFunction<T>(t: T): t is Extract<T, Function> {\r\n return typeof t === 'function'\r\n}\r\n\r\nexport function expandTagDescription(\r\n description: TagDescription<string>\r\n): FullTagDescription<string> {\r\n return typeof description === 'string' ? { type: description } : description\r\n}\r\n\r\nexport type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any>> =\r\n D extends BaseEndpointDefinition<infer QA, any, any> ? QA : unknown\r\nexport type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any>> =\r\n D extends BaseEndpointDefinition<any, any, infer RT> ? RT : unknown\r\n\r\nexport type ReducerPathFrom<\r\n D extends EndpointDefinition<any, any, any, any, any>\r\n> = D extends EndpointDefinition<any, any, any, any, infer RP> ? RP : unknown\r\n\r\nexport type TagTypesFrom<D extends EndpointDefinition<any, any, any, any>> =\r\n D extends EndpointDefinition<any, any, infer RP, any> ? RP : unknown\r\n\r\nexport type ReplaceTagTypes<\r\n Definitions extends EndpointDefinitions,\r\n NewTagTypes extends string\r\n> = {\r\n [K in keyof Definitions]: Definitions[K] extends QueryDefinition<\r\n infer QueryArg,\r\n infer BaseQuery,\r\n any,\r\n infer ResultType,\r\n infer ReducerPath\r\n >\r\n ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, ResultType, ReducerPath>\r\n : Definitions[K] extends MutationDefinition<\r\n infer QueryArg,\r\n infer BaseQuery,\r\n any,\r\n infer ResultType,\r\n infer ReducerPath\r\n >\r\n ? MutationDefinition<\r\n QueryArg,\r\n BaseQuery,\r\n NewTagTypes,\r\n ResultType,\r\n ReducerPath\r\n >\r\n : never\r\n}\r\n","import { createNextState, createSelector } from '@reduxjs/toolkit'\r\nimport type {\r\n MutationSubState,\r\n QuerySubState,\r\n RootState as _RootState,\r\n RequestStatusFlags,\r\n QueryCacheKey,\r\n} from './apiState'\r\nimport { QueryStatus, getRequestStatusFlags } from './apiState'\r\nimport type {\r\n EndpointDefinitions,\r\n QueryDefinition,\r\n MutationDefinition,\r\n QueryArgFrom,\r\n TagTypesFrom,\r\n ReducerPathFrom,\r\n TagDescription,\r\n} from '../endpointDefinitions'\r\nimport { expandTagDescription } from '../endpointDefinitions'\r\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'\r\nimport { getMutationCacheKey } from './buildSlice'\r\nimport { flatten } from '../utils'\r\n\r\nexport type SkipToken = typeof skipToken\r\n/**\r\n * Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`\r\n * instead of the query argument to get the same effect as if setting\r\n * `skip: true` in the query options.\r\n *\r\n * Useful for scenarios where a query should be skipped when `arg` is `undefined`\r\n * and TypeScript complains about it because `arg` is not allowed to be passed\r\n * in as `undefined`, such as\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"will error if the query argument is not allowed to be undefined\" no-transpile\r\n * useSomeQuery(arg, { skip: !!arg })\r\n * ```\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"using skipToken instead\" no-transpile\r\n * useSomeQuery(arg ?? skipToken)\r\n * ```\r\n *\r\n * If passed directly into a query or mutation selector, that selector will always\r\n * return an uninitialized state.\r\n */\r\nexport const skipToken = /* @__PURE__ */ Symbol.for('RTKQ/skipToken')\r\n/** @deprecated renamed to `skipToken` */\r\nexport const skipSelector = skipToken\r\n\r\ndeclare module './module' {\r\n export interface ApiEndpointQuery<\r\n Definition extends QueryDefinition<any, any, any, any, any>,\r\n Definitions extends EndpointDefinitions\r\n > {\r\n select: QueryResultSelectorFactory<\r\n Definition,\r\n _RootState<\r\n Definitions,\r\n TagTypesFrom<Definition>,\r\n ReducerPathFrom<Definition>\r\n >\r\n >\r\n }\r\n\r\n export interface ApiEndpointMutation<\r\n Definition extends MutationDefinition<any, any, any, any, any>,\r\n Definitions extends EndpointDefinitions\r\n > {\r\n select: MutationResultSelectorFactory<\r\n Definition,\r\n _RootState<\r\n Definitions,\r\n TagTypesFrom<Definition>,\r\n ReducerPathFrom<Definition>\r\n >\r\n >\r\n }\r\n}\r\n\r\ntype QueryResultSelectorFactory<\r\n Definition extends QueryDefinition<any, any, any, any>,\r\n RootState\r\n> = (\r\n queryArg: QueryArgFrom<Definition> | SkipToken\r\n) => (state: RootState) => QueryResultSelectorResult<Definition>\r\n\r\nexport type QueryResultSelectorResult<\r\n Definition extends QueryDefinition<any, any, any, any>\r\n> = QuerySubState<Definition> & RequestStatusFlags\r\n\r\ntype MutationResultSelectorFactory<\r\n Definition extends MutationDefinition<any, any, any, any>,\r\n RootState\r\n> = (\r\n requestId:\r\n | string\r\n | { requestId: string | undefined; fixedCacheKey: string | undefined }\r\n | SkipToken\r\n) => (state: RootState) => MutationResultSelectorResult<Definition>\r\n\r\nexport type MutationResultSelectorResult<\r\n Definition extends MutationDefinition<any, any, any, any>\r\n> = MutationSubState<Definition> & RequestStatusFlags\r\n\r\nconst initialSubState: QuerySubState<any> = {\r\n status: QueryStatus.uninitialized as const,\r\n}\r\n\r\n// abuse immer to freeze default states\r\nconst defaultQuerySubState = /* @__PURE__ */ createNextState(\r\n initialSubState,\r\n () => {}\r\n)\r\nconst defaultMutationSubState = /* @__PURE__ */ createNextState(\r\n initialSubState as MutationSubState<any>,\r\n () => {}\r\n)\r\n\r\nexport function buildSelectors<\r\n Definitions extends EndpointDefinitions,\r\n ReducerPath extends string\r\n>({\r\n serializeQueryArgs,\r\n reducerPath,\r\n}: {\r\n serializeQueryArgs: InternalSerializeQueryArgs\r\n reducerPath: ReducerPath\r\n}) {\r\n type RootState = _RootState<Definitions, string, string>\r\n\r\n return { buildQuerySelector, buildMutationSelector, selectInvalidatedBy }\r\n\r\n function withRequestFlags<T extends { status: QueryStatus }>(\r\n substate: T\r\n ): T & RequestStatusFlags {\r\n return {\r\n ...substate,\r\n ...getRequestStatusFlags(substate.status),\r\n }\r\n }\r\n\r\n function selectInternalState(rootState: RootState) {\r\n const state = rootState[reducerPath]\r\n if (process.env.NODE_ENV !== 'production') {\r\n if (!state) {\r\n if ((selectInternalState as any).triggered) return state\r\n ;(selectInternalState as any).triggered = true\r\n console.error(\r\n `Error: No data found at \\`state.${reducerPath}\\`. Did you forget to add the reducer to the store?`\r\n )\r\n }\r\n }\r\n return state\r\n }\r\n\r\n function buildQuerySelector(\r\n endpointName: string,\r\n endpointDefinition: QueryDefinition<any, any, any, any>\r\n ) {\r\n return ((queryArgs: any) => {\r\n const selectQuerySubState = createSelector(\r\n selectInternalState,\r\n (internalState) =>\r\n (queryArgs === skipToken\r\n ? undefined\r\n : internalState?.queries?.[\r\n serializeQueryArgs({\r\n queryArgs,\r\n endpointDefinition,\r\n endpointName,\r\n })\r\n ]) ?? defaultQuerySubState\r\n )\r\n return createSelector(selectQuerySubState, withRequestFlags)\r\n }) as QueryResultSelectorFactory<any, RootState>\r\n }\r\n\r\n function buildMutationSelector() {\r\n return ((id) => {\r\n let mutationId: string | typeof skipToken\r\n if (typeof id === 'object') {\r\n mutationId = getMutationCacheKey(id) ?? skipToken\r\n } else {\r\n mutationId = id\r\n }\r\n const selectMutationSubstate = createSelector(\r\n selectInternalState,\r\n (internalState) =>\r\n (mutationId === skipToken\r\n ? undefined\r\n : internalState?.mutations?.[mutationId]) ?? defaultMutationSubState\r\n )\r\n return createSelector(selectMutationSubstate, withRequestFlags)\r\n }) as MutationResultSelectorFactory<any, RootState>\r\n }\r\n\r\n function selectInvalidatedBy(\r\n state: RootState,\r\n tags: ReadonlyArray<TagDescription<string>>\r\n ): Array<{\r\n endpointName: string\r\n originalArgs: any\r\n queryCacheKey: QueryCacheKey\r\n }> {\r\n const apiState = state[reducerPath]\r\n const toInvalidate = new Set<QueryCacheKey>()\r\n for (const tag of tags.map(expandTagDescription)) {\r\n const provided = apiState.provided[tag.type]\r\n if (!provided) {\r\n continue\r\n }\r\n\r\n let invalidateSubscriptions =\r\n (tag.id !== undefined\r\n ? // id given: invalidate all queries that provide this type & id\r\n provided[tag.id]\r\n : // no id: invalidate all queries that provide this type\r\n flatten(Object.values(provided))) ?? []\r\n\r\n for (const invalidate of invalidateSubscriptions) {\r\n toInvalidate.add(invalidate)\r\n }\r\n }\r\n\r\n return flatten(\r\n Array.from(toInvalidate.values()).map((queryCacheKey) => {\r\n const querySubState = apiState.queries[queryCacheKey]\r\n return querySubState\r\n ? [\r\n {\r\n queryCacheKey,\r\n endpointName: querySubState.endpointName!,\r\n originalArgs: querySubState.originalArgs,\r\n },\r\n ]\r\n : []\r\n })\r\n )\r\n }\r\n}\r\n","import type { AnyAction, PayloadAction } from '@reduxjs/toolkit'\r\nimport {\r\n combineReducers,\r\n createAction,\r\n createSlice,\r\n isAnyOf,\r\n isFulfilled,\r\n isRejectedWithValue,\r\n} from '@reduxjs/toolkit'\r\nimport type {\r\n CombinedState as CombinedQueryState,\r\n QuerySubstateIdentifier,\r\n QuerySubState,\r\n MutationSubstateIdentifier,\r\n MutationSubState,\r\n MutationState,\r\n QueryState,\r\n InvalidationState,\r\n Subscribers,\r\n QueryCacheKey,\r\n SubscriptionState,\r\n ConfigState,\r\n} from './apiState'\r\nimport { QueryStatus } from './apiState'\r\nimport type { MutationThunk, QueryThunk } from './buildThunks'\r\nimport { calculateProvidedByThunk } from './buildThunks'\r\nimport type {\r\n AssertTagTypes,\r\n EndpointDefinitions,\r\n} from '../endpointDefinitions'\r\nimport type { Patch } from 'immer'\r\nimport { applyPatches } from 'immer'\r\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners'\r\nimport {\r\n isDocumentVisible,\r\n isOnline,\r\n copyWithStructuralSharing,\r\n} from '../utils'\r\nimport type { ApiContext } from '../apiTypes'\r\n\r\nfunction updateQuerySubstateIfExists(\r\n state: QueryState<any>,\r\n queryCacheKey: QueryCacheKey,\r\n update: (substate: QuerySubState<any>) => void\r\n) {\r\n const substate = state[queryCacheKey]\r\n if (substate) {\r\n update(substate)\r\n }\r\n}\r\n\r\nexport function getMutationCacheKey(\r\n id:\r\n | MutationSubstateIdentifier\r\n | { requestId: string; arg: { fixedCacheKey?: string | undefined } }\r\n): string\r\nexport function getMutationCacheKey(id: {\r\n fixedCacheKey?: string\r\n requestId?: string\r\n}): string | undefined\r\n\r\nexport function getMutationCacheKey(\r\n id:\r\n | { fixedCacheKey?: string; requestId?: string }\r\n | MutationSubstateIdentifier\r\n | { requestId: string; arg: { fixedCacheKey?: string | undefined } }\r\n): string | undefined {\r\n return ('arg' in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId\r\n}\r\n\r\nfunction updateMutationSubstateIfExists(\r\n state: MutationState<any>,\r\n id:\r\n | MutationSubstateIdentifier\r\n | { requestId: string; arg: { fixedCacheKey?: string | undefined } },\r\n update: (substate: MutationSubState<any>) => void\r\n) {\r\n const substate = state[getMutationCacheKey(id)]\r\n if (substate) {\r\n update(substate)\r\n }\r\n}\r\n\r\nconst initialState = {} as any\r\n\r\nexport function buildSlice({\r\n reducerPath,\r\n queryThunk,\r\n mutationThunk,\r\n context: {\r\n endpointDefinitions: definitions,\r\n apiUid,\r\n extractRehydrationInfo,\r\n hasRehydrationInfo,\r\n },\r\n assertTagType,\r\n config,\r\n}: {\r\n reducerPath: string\r\n queryThunk: QueryThunk\r\n mutationThunk: MutationThunk\r\n context: ApiContext<EndpointDefinitions>\r\n assertTagType: AssertTagTypes\r\n config: Omit<\r\n ConfigState<string>,\r\n 'online' | 'focused' | 'middlewareRegistered'\r\n >\r\n}) {\r\n const resetApiState = createAction(`${reducerPath}/resetApiState`)\r\n const querySlice = createSlice({\r\n name: `${reducerPath}/queries`,\r\n initialState: initialState as QueryState<any>,\r\n reducers: {\r\n removeQueryResult(\r\n draft,\r\n { payload: { queryCacheKey } }: PayloadAction<QuerySubstateIdentifier>\r\n ) {\r\n delete draft[queryCacheKey]\r\n },\r\n queryResultPatched(\r\n draft,\r\n {\r\n payload: { queryCacheKey, patches },\r\n }: PayloadAction<\r\n QuerySubstateIdentifier & { patches: readonly Patch[] }\r\n >\r\n ) {\r\n updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {\r\n substate.data = applyPatches(substate.data as any, patches.concat())\r\n })\r\n },\r\n },\r\n extraReducers(builder) {\r\n builder\r\n .addCase(queryThunk.pending, (draft, { meta, meta: { arg } }) => {\r\n if (arg.subscribe) {\r\n // only initialize substate if we want to subscribe to it\r\n draft[arg.queryCacheKey] ??= {\r\n status: QueryStatus.uninitialized,\r\n endpointName: arg.endpointName,\r\n }\r\n }\r\n\r\n updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {\r\n substate.status = QueryStatus.pending\r\n substate.requestId = meta.requestId\r\n if (arg.originalArgs !== undefined) {\r\n substate.originalArgs = arg.originalArgs\r\n }\r\n substate.startedTimeStamp = meta.startedTimeStamp\r\n })\r\n })\r\n .addCase(queryThunk.fulfilled, (draft, { meta, payload }) => {\r\n updateQuerySubstateIfExists(\r\n draft,\r\n meta.arg.queryCacheKey,\r\n (substate) => {\r\n if (substate.requestId !== meta.requestId) return\r\n substate.status = QueryStatus.fulfilled\r\n substate.data =\r\n definitions[meta.arg.endpointName].structuralSharing ?? true\r\n ? copyWithStructuralSharing(substate.data, payload)\r\n : payload\r\n delete substate.error\r\n substate.fulfilledTimeStamp = meta.fulfilledTimeStamp\r\n }\r\n )\r\n })\r\n .addCase(\r\n queryThunk.rejected,\r\n (draft, { meta: { condition, arg, requestId }, error, payload }) => {\r\n updateQuerySubstateIfExists(\r\n draft,\r\n arg.queryCacheKey,\r\n (substate) => {\r\n if (condition) {\r\n // request was aborted due to condition (another query already running)\r\n } else {\r\n // request failed\r\n if (substate.requestId !== requestId) return\r\n substate.status = QueryStatus.rejected\r\n substate.error = (payload ?? error) as any\r\n }\r\n }\r\n )\r\n }\r\n )\r\n .addMatcher(hasRehydrationInfo, (draft, action) => {\r\n const { queries } = extractRehydrationInfo(action)!\r\n for (const [key, entry] of Object.entries(queries)) {\r\n if (\r\n // do not rehydrate entries that were currently in flight.\r\n entry?.status === QueryStatus.fulfilled ||\r\n entry?.status === QueryStatus.rejected\r\n ) {\r\n draft[key] = entry\r\n }\r\n }\r\n })\r\n },\r\n })\r\n const mutationSlice = createSlice({\r\n name: `${reducerPath}/mutations`,\r\n initialState: initialState as MutationState<any>,\r\n reducers: {\r\n removeMutationResult(\r\n draft,\r\n { payload }: PayloadAction<MutationSubstateIdentifier>\r\n ) {\r\n const cacheKey = getMutationCacheKey(payload)\r\n if (cacheKey in draft) {\r\n delete draft[cacheKey]\r\n }\r\n },\r\n },\r\n extraReducers(builder) {\r\n builder\r\n .addCase(\r\n mutationThunk.pending,\r\n (draft, { meta, meta: { requestId, arg, startedTimeStamp } }) => {\r\n if (!arg.track) return\r\n\r\n draft[getMutationCacheKey(meta)] = {\r\n requestId,\r\n status: QueryStatus.pending,\r\n endpointName: arg.endpointName,\r\n startedTimeStamp,\r\n }\r\n }\r\n )\r\n .addCase(mutationThunk.fulfilled, (draft, { payload, meta }) => {\r\n if (!meta.arg.track) return\r\n\r\n updateMutationSubstateIfExists(draft, meta, (substate) => {\r\n if (substate.requestId !== meta.requestId) return\r\n substate.status = QueryStatus.fulfilled\r\n substate.data = payload\r\n substate.fulfilledTimeStamp = meta.fulfilledTimeStamp\r\n })\r\n })\r\n .addCase(mutationThunk.rejected, (draft, { payload, error, meta }) => {\r\n if (!meta.arg.track) return\r\n\r\n updateMutationSubstateIfExists(draft, meta, (substate) => {\r\n if (substate.requestId !== meta.requestId) return\r\n\r\n substate.status = QueryStatus.rejected\r\n substate.error = (payload ?? error) as any\r\n })\r\n })\r\n .addMatcher(hasRehydrationInfo, (draft, action) => {\r\n const { mutations } = extractRehydrationInfo(action)!\r\n for (const [key, entry] of Object.entries(mutations)) {\r\n if (\r\n // do not rehydrate entries that were currently in flight.\r\n (entry?.status === QueryStatus.fulfilled ||\r\n entry?.status === QueryStatus.rejected) &&\r\n // only rehydrate endpoints that were persisted using a `fixedCacheKey`\r\n key !== entry?.requestId\r\n ) {\r\n draft[key] = entry\r\n }\r\n }\r\n })\r\n },\r\n })\r\n\r\n const invalidationSlice = createSlice({\r\n name: `${reducerPath}/invalidation`,\r\n initialState: initialState as InvalidationState<string>,\r\n reducers: {},\r\n extraReducers(builder) {\r\n builder\r\n .addCase(\r\n querySlice.actions.removeQueryResult,\r\n (draft, { payload: { queryCacheKey } }) => {\r\n for (const tagTypeSubscriptions of Object.values(draft)) {\r\n for (const idSubscriptions of Object.values(\r\n tagTypeSubscriptions\r\n )) {\r\n const foundAt = idSubscriptions.indexOf(queryCacheKey)\r\n if (foundAt !== -1) {\r\n idSubscriptions.splice(foundAt, 1)\r\n }\r\n }\r\n }\r\n }\r\n )\r\n .addMatcher(hasRehydrationInfo, (draft, action) => {\r\n const { provided } = extractRehydrationInfo(action)!\r\n for (const [type, incomingTags] of Object.entries(provided)) {\r\n for (const [id, cacheKeys] of Object.entries(incomingTags)) {\r\n const subscribedQueries = ((draft[type] ??= {})[\r\n id || '__internal_without_id'\r\n ] ??= [])\r\n for (const queryCacheKey of cacheKeys) {\r\n const alreadySubscribed =\r\n subscribedQueries.includes(queryCacheKey)\r\n if (!alreadySubscribed) {\r\n subscribedQueries.push(queryCacheKey)\r\n }\r\n }\r\n }\r\n }\r\n })\r\n .addMatcher(\r\n isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)),\r\n (draft, action) => {\r\n const providedTags = calculateProvidedByThunk(\r\n action,\r\n 'providesTags',\r\n definitions,\r\n assertTagType\r\n )\r\n const { queryCacheKey } = action.meta.arg\r\n\r\n for (const { type, id } of providedTags) {\r\n const subscribedQueries = ((draft[type] ??= {})[\r\n id || '__internal_without_id'\r\n ] ??= [])\r\n const alreadySubscribed =\r\n subscribedQueries.includes(queryCacheKey)\r\n if (!alreadySubscribed) {\r\n subscribedQueries.push(queryCacheKey)\r\n }\r\n }\r\n }\r\n )\r\n },\r\n })\r\n\r\n const subscriptionSlice = createSlice({\r\n name: `${reducerPath}/subscriptions`,\r\n initialState: initialState as SubscriptionState,\r\n reducers: {\r\n updateSubscriptionOptions(\r\n draft,\r\n {\r\n payload: { queryCacheKey, requestId, options },\r\n }: PayloadAction<\r\n {\r\n endpointName: string\r\n requestId: string\r\n options: Subscribers[number]\r\n } & QuerySubstateIdentifier\r\n >\r\n ) {\r\n if (draft?.[queryCacheKey]?.[requestId]) {\r\n draft[queryCacheKey]![requestId] = options\r\n }\r\n },\r\n unsubscribeQueryResult(\r\n draft,\r\n {\r\n payload: { queryCacheKey, requestId },\r\n }: PayloadAction<{ requestId: string } & QuerySubstateIdentifier>\r\n ) {\r\n if (draft[queryCacheKey]) {\r\n delete draft[queryCacheKey]![requestId]\r\n }\r\n },\r\n },\r\n extraReducers: (builder) => {\r\n builder\r\n .addCase(\r\n querySlice.actions.removeQueryResult,\r\n (draft, { payload: { queryCacheKey } }) => {\r\n delete draft[queryCacheKey]\r\n }\r\n )\r\n .addCase(queryThunk.pending, (draft, { meta: { arg, requestId } }) => {\r\n if (arg.subscribe) {\r\n const substate = (draft[arg.queryCacheKey] ??= {})\r\n substate[requestId] =\r\n arg.subscriptionOptions ?? substate[requestId] ?? {}\r\n }\r\n })\r\n .addCase(\r\n queryThunk.rejected,\r\n (draft, { meta: { condition, arg, requestId }, error, payload }) => {\r\n // request was aborted due to condition (another query already running)\r\n if (condition && arg.subscribe) {\r\n const substate = (draft[arg.queryCacheKey] ??= {})\r\n substate[requestId] =\r\n arg.subscriptionOptions ?? substate[requestId] ?? {}\r\n }\r\n }\r\n )\r\n // update the state to be a new object to be picked up as a \"state change\"\r\n // by redux-persist's `autoMergeLevel2`\r\n .addMatcher(hasRehydrationInfo, (draft) => ({ ...draft }))\r\n },\r\n })\r\n\r\n const configSlice = createSlice({\r\n name: `${reducerPath}/config`,\r\n initialState: {\r\n online: isOnline(),\r\n focused: isDocumentVisible(),\r\n middlewareRegistered: false,\r\n ...config,\r\n } as ConfigState<string>,\r\n reducers: {\r\n middlewareRegistered(state, { payload }: PayloadAction<string>) {\r\n state.middlewareRegistered =\r\n state.middlewareRegistered === 'conflict' || apiUid !== payload\r\n ? 'conflict'\r\n : true\r\n },\r\n },\r\n extraReducers: (builder) => {\r\n builder\r\n .addCase(onOnline, (state) => {\r\n state.online = true\r\n })\r\n .addCase(onOffline, (state) => {\r\n state.online = false\r\n })\r\n .addCase(onFocus, (state) => {\r\n state.focused = true\r\n })\r\n .addCase(onFocusLost, (state) => {\r\n state.focused = false\r\n })\r\n // update the state to be a new object to be picked up as a \"state change\"\r\n // by redux-persist's `autoMergeLevel2`\r\n .addMatcher(hasRehydrationInfo, (draft) => ({ ...draft }))\r\n },\r\n })\r\n\r\n const combinedReducer = combineReducers<\r\n CombinedQueryState<any, string, string>\r\n >({\r\n queries: querySlice.reducer,\r\n mutations: mutationSlice.reducer,\r\n provided: invalidationSlice.reducer,\r\n subscriptions: subscriptionSlice.reducer,\r\n config: configSlice.reducer,\r\n })\r\n\r\n const reducer: typeof combinedReducer = (state, action) =>\r\n combinedReducer(resetApiState.match(action) ? undefined : state, action)\r\n\r\n const actions = {\r\n ...configSlice.actions,\r\n ...querySlice.actions,\r\n ...subscriptionSlice.actions,\r\n ...mutationSlice.actions,\r\n /** @deprecated has been renamed to `removeMutationResult` */\r\n unsubscribeMutationResult: mutationSlice.actions.removeMutationResult,\r\n resetApiState,\r\n }\r\n\r\n return { reducer, actions }\r\n}\r\nexport type SliceActions = ReturnType<typeof buildSlice>['actions']\r\n","import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'\r\nimport type { Api, ApiContext } from '../apiTypes'\r\nimport type {\r\n BaseQueryFn,\r\n BaseQueryError,\r\n QueryReturnValue,\r\n} from '../baseQueryTypes'\r\nimport type { RootState, QueryKeys, QuerySubstateIdentifier } from './apiState'\r\nimport { QueryStatus } from './apiState'\r\nimport type { StartQueryActionCreatorOptions } from './buildInitiate'\r\nimport type {\r\n AssertTagTypes,\r\n EndpointDefinition,\r\n EndpointDefinitions,\r\n MutationDefinition,\r\n QueryArgFrom,\r\n QueryDefinition,\r\n ResultTypeFrom,\r\n} from '../endpointDefinitions'\r\nimport { calculateProvidedBy } from '../endpointDefinitions'\r\nimport type { AsyncThunkPayloadCreator, Draft } from '@reduxjs/toolkit'\r\nimport {\r\n isAllOf,\r\n isFulfilled,\r\n isPending,\r\n isRejected,\r\n isRejectedWithValue,\r\n} from '@reduxjs/toolkit'\r\nimport type { Patch } from 'immer'\r\nimport { isDraftable, produceWithPatches } from 'immer'\r\nimport type {\r\n AnyAction,\r\n ThunkAction,\r\n ThunkDispatch,\r\n AsyncThunk,\r\n} from '@reduxjs/toolkit'\r\nimport { createAsyncThunk } from '@reduxjs/toolkit'\r\n\r\nimport { HandledError } from '../HandledError'\r\n\r\nimport type { ApiEndpointQuery, PrefetchOptions } from './module'\r\nimport type { UnwrapPromise } from '../tsHelpers'\r\n\r\ndeclare module './module' {\r\n export interface ApiEndpointQuery<\r\n Definition extends QueryDefinition<any, any, any, any, any>,\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definitions extends EndpointDefinitions\r\n > extends Matchers<QueryThunk, Definition> {}\r\n\r\n export interface ApiEndpointMutation<\r\n Definition extends MutationDefinition<any, any, any, any, any>,\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definitions extends EndpointDefinitions\r\n > extends Matchers<MutationThunk, Definition> {}\r\n}\r\n\r\ntype EndpointThunk<\r\n Thunk extends QueryThunk | MutationThunk,\r\n Definition extends EndpointDefinition<any, any, any, any>\r\n> = Definition extends EndpointDefinition<\r\n infer QueryArg,\r\n infer BaseQueryFn,\r\n any,\r\n infer ResultType\r\n>\r\n ? Thunk extends AsyncThunk<unknown, infer ATArg, infer ATConfig>\r\n ? AsyncThunk<\r\n ResultType,\r\n ATArg & { originalArgs: QueryArg },\r\n ATConfig & { rejectValue: BaseQueryError<BaseQueryFn> }\r\n >\r\n : never\r\n : never\r\n\r\nexport type PendingAction<\r\n Thunk extends QueryThunk | MutationThunk,\r\n Definition extends EndpointDefinition<any, any, any, any>\r\n> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>\r\n\r\nexport type FulfilledAction<\r\n Thunk extends QueryThunk | MutationThunk,\r\n Definition extends EndpointDefinition<any, any, any, any>\r\n> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>\r\n\r\nexport type RejectedAction<\r\n Thunk extends QueryThunk | MutationThunk,\r\n Definition extends EndpointDefinition<any, any, any, any>\r\n> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>\r\n\r\nexport type Matcher<M> = (value: any) => value is M\r\n\r\nexport interface Matchers<\r\n Thunk extends QueryThunk | MutationThunk,\r\n Definition extends EndpointDefinition<any, any, any, any>\r\n> {\r\n matchPending: Matcher<PendingAction<Thunk, Definition>>\r\n matchFulfilled: Matcher<FulfilledAction<Thunk, Definition>>\r\n matchRejected: Matcher<RejectedAction<Thunk, Definition>>\r\n}\r\n\r\nexport interface QueryThunkArg\r\n extends QuerySubstateIdentifier,\r\n StartQueryActionCreatorOptions {\r\n type: 'query'\r\n originalArgs: unknown\r\n endpointName: string\r\n}\r\n\r\nexport interface MutationThunkArg {\r\n type: 'mutation'\r\n originalArgs: unknown\r\n endpointName: string\r\n track?: boolean\r\n fixedCacheKey?: string\r\n}\r\n\r\nexport type ThunkResult = unknown\r\n\r\nexport type ThunkApiMetaConfig = {\r\n pendingMeta: { startedTimeStamp: number }\r\n fulfilledMeta: {\r\n fulfilledTimeStamp: number\r\n baseQueryMeta: unknown\r\n }\r\n rejectedMeta: {\r\n baseQueryMeta: unknown\r\n }\r\n}\r\nexport type QueryThunk = AsyncThunk<\r\n ThunkResult,\r\n QueryThunkArg,\r\n ThunkApiMetaConfig\r\n>\r\nexport type MutationThunk = AsyncThunk<\r\n ThunkResult,\r\n MutationThunkArg,\r\n ThunkApiMetaConfig\r\n>\r\n\r\nfunction defaultTransformResponse(baseQueryReturnValue: unknown) {\r\n return baseQueryReturnValue\r\n}\r\n\r\nexport type MaybeDrafted<T> = T | Draft<T>\r\nexport type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>\r\n\r\nexport type PatchQueryDataThunk<\r\n Definitions extends EndpointDefinitions,\r\n PartialState\r\n> = <EndpointName extends QueryKeys<Definitions>>(\r\n endpointName: EndpointName,\r\n args: QueryArgFrom<Definitions[EndpointName]>,\r\n patches: readonly Patch[]\r\n) => ThunkAction<void, PartialState, any, AnyAction>\r\n\r\nexport type UpdateQueryDataThunk<\r\n Definitions extends EndpointDefinitions,\r\n PartialState\r\n> = <EndpointName extends QueryKeys<Definitions>>(\r\n endpointName: EndpointName,\r\n args: QueryArgFrom<Definitions[EndpointName]>,\r\n updateRecipe: Recipe<ResultTypeFrom<Definitions[EndpointName]>>\r\n) => ThunkAction<PatchCollection, PartialState, any, AnyAction>\r\n\r\n/**\r\n * An object returned from dispatching a `api.util.updateQueryData` call.\r\n */\r\nexport type PatchCollection = {\r\n /**\r\n * An `immer` Patch describing the cache update.\r\n */\r\n patches: Patch[]\r\n /**\r\n * An `immer` Patch to revert the cache update.\r\n */\r\n inversePatches: Patch[]\r\n /**\r\n * A function that will undo the cache update.\r\n */\r\n undo: () => void\r\n}\r\n\r\nexport function buildThunks<\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string,\r\n Definitions extends EndpointDefinitions\r\n>({\r\n reducerPath,\r\n baseQuery,\r\n context: { endpointDefinitions },\r\n serializeQueryArgs,\r\n api,\r\n}: {\r\n baseQuery: BaseQuery\r\n reducerPath: ReducerPath\r\n context: ApiContext<Definitions>\r\n serializeQueryArgs: InternalSerializeQueryArgs\r\n api: Api<BaseQuery, Definitions, ReducerPath, any>\r\n}) {\r\n type State = RootState<any, string, ReducerPath>\r\n\r\n const patchQueryData: PatchQueryDataThunk<EndpointDefinitions, State> =\r\n (endpointName, args, patches) => (dispatch) => {\r\n const endpointDefinition = endpointDefinitions[endpointName]\r\n dispatch(\r\n api.internalActions.queryResultPatched({\r\n queryCacheKey: serializeQueryArgs({\r\n queryArgs: args,\r\n endpointDefinition,\r\n endpointName,\r\n }),\r\n patches,\r\n })\r\n )\r\n }\r\n\r\n const updateQueryData: UpdateQueryDataThunk<EndpointDefinitions, State> =\r\n (endpointName, args, updateRecipe) => (dispatch, getState) => {\r\n const currentState = (\r\n api.endpoints[endpointName] as ApiEndpointQuery<any, any>\r\n ).select(args)(getState())\r\n let ret: PatchCollection = {\r\n patches: [],\r\n inversePatches: [],\r\n undo: () =>\r\n dispatch(\r\n api.util.patchQueryData(endpointName, args, ret.inversePatches)\r\n ),\r\n }\r\n if (currentState.status === QueryStatus.uninitialized) {\r\n return ret\r\n }\r\n if ('data' in currentState) {\r\n if (isDraftable(currentState.data)) {\r\n const [, patches, inversePatches] = produceWithPatches(\r\n currentState.data,\r\n updateRecipe\r\n )\r\n ret.patches.push(...patches)\r\n ret.inversePatches.push(...inversePatches)\r\n } else {\r\n const value = updateRecipe(currentState.data)\r\n ret.patches.push({ op: 'replace', path: [], value })\r\n ret.inversePatches.push({\r\n op: 'replace',\r\n path: [],\r\n value: currentState.data,\r\n })\r\n }\r\n }\r\n\r\n dispatch(api.util.patchQueryData(endpointName, args, ret.patches))\r\n\r\n return ret\r\n }\r\n\r\n const executeEndpoint: AsyncThunkPayloadCreator<\r\n ThunkResult,\r\n QueryThunkArg | MutationThunkArg,\r\n ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }\r\n > = async (\r\n arg,\r\n { signal, rejectWithValue, fulfillWithValue, dispatch, getState, extra }\r\n ) => {\r\n const endpointDefinition = endpointDefinitions[arg.endpointName]\r\n\r\n try {\r\n let transformResponse: (\r\n baseQueryReturnValue: any,\r\n meta: any,\r\n arg: any\r\n ) => any = defaultTransformResponse\r\n let result: QueryReturnValue\r\n const baseQueryApi = {\r\n signal,\r\n dispatch,\r\n getState,\r\n extra,\r\n endpoint: arg.endpointName,\r\n type: arg.type,\r\n forced:\r\n arg.type === 'query' ? isForcedQuery(arg, getState()) : undefined,\r\n }\r\n if (endpointDefinition.query) {\r\n result = await baseQuery(\r\n endpointDefinition.query(arg.originalArgs),\r\n baseQueryApi,\r\n endpointDefinition.extraOptions as any\r\n )\r\n\r\n if (endpointDefinition.transformResponse) {\r\n transformResponse = endpointDefinition.transformResponse\r\n }\r\n } else {\r\n result = await endpointDefinition.queryFn(\r\n arg.originalArgs,\r\n baseQueryApi,\r\n endpointDefinition.extraOptions as any,\r\n (arg) =>\r\n baseQuery(arg, baseQueryApi, endpointDefinition.extraOptions as any)\r\n )\r\n }\r\n if (\r\n typeof process !== 'undefined' &&\r\n process.env.NODE_ENV === 'development'\r\n ) {\r\n const what = endpointDefinition.query ? '`baseQuery`' : '`queryFn`'\r\n let err: undefined | string\r\n if (!result) {\r\n err = `${what} did not return anything.`\r\n } else if (typeof result !== 'object') {\r\n err = `${what} did not return an object.`\r\n } else if (result.error && result.data) {\r\n err = `${what} returned an object containing both \\`error\\` and \\`result\\`.`\r\n } else if (result.error === undefined && result.data === undefined) {\r\n err = `${what} returned an object containing neither a valid \\`error\\` and \\`result\\`. At least one of them should not be \\`undefined\\``\r\n } else {\r\n for (const key of Object.keys(result)) {\r\n if (key !== 'error' && key !== 'data' && key !== 'meta') {\r\n err = `The object returned by ${what} has the unknown property ${key}.`\r\n break\r\n }\r\n }\r\n }\r\n if (err) {\r\n console.error(\r\n `Error encountered handling the endpoint ${arg.endpointName}.\r\n ${err}\r\n It needs to return an object with either the shape \\`{ data: <value> }\\` or \\`{ error: <value> }\\` that may contain an optional \\`meta\\` property.\r\n Object returned was:`,\r\n result\r\n )\r\n }\r\n }\r\n\r\n if (result.error) throw new HandledError(result.error, result.meta)\r\n\r\n return fulfillWithValue(\r\n await transformResponse(result.data, result.meta, arg.originalArgs),\r\n {\r\n fulfilledTimeStamp: Date.now(),\r\n baseQueryMeta: result.meta,\r\n }\r\n )\r\n } catch (error) {\r\n if (error instanceof HandledError) {\r\n return rejectWithValue(error.value, { baseQueryMeta: error.meta })\r\n }\r\n if (\r\n typeof process !== 'undefined' &&\r\n process.env.NODE_ENV === 'development'\r\n ) {\r\n console.error(\r\n `An unhandled error occured processing a request for the endpoint \"${arg.endpointName}\".\r\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`,\r\n error\r\n )\r\n } else {\r\n console.error(error)\r\n }\r\n throw error\r\n }\r\n }\r\n\r\n function isForcedQuery(\r\n arg: QueryThunkArg,\r\n state: RootState<any, string, ReducerPath>\r\n ) {\r\n const requestState = state[reducerPath]?.queries?.[arg.queryCacheKey]\r\n const baseFetchOnMountOrArgChange =\r\n state[reducerPath]?.config.refetchOnMountOrArgChange\r\n\r\n const fulfilledVal = requestState?.fulfilledTimeStamp\r\n const refetchVal =\r\n arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange)\r\n\r\n if (refetchVal) {\r\n // Return if its true or compare the dates because it must be a number\r\n return (\r\n refetchVal === true ||\r\n (Number(new Date()) - Number(fulfilledVal)) / 1000 >= refetchVal\r\n )\r\n }\r\n return false\r\n }\r\n\r\n const queryThunk = createAsyncThunk<\r\n ThunkResult,\r\n QueryThunkArg,\r\n ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }\r\n >(`${reducerPath}/executeQuery`, executeEndpoint, {\r\n getPendingMeta() {\r\n return { startedTimeStamp: Date.now() }\r\n },\r\n condition(arg, { getState }) {\r\n const state = getState()\r\n const requestState = state[reducerPath]?.queries?.[arg.queryCacheKey]\r\n const fulfilledVal = requestState?.fulfilledTimeStamp\r\n\r\n // Don't retry a request that's currently in-flight\r\n if (requestState?.status === 'pending') return false\r\n\r\n // if this is forced, continue\r\n if (isForcedQuery(arg, state)) return true\r\n\r\n // Pull from the cache unless we explicitly force refetch or qualify based on time\r\n if (fulfilledVal)\r\n // Value is cached and we didn't specify to refresh, skip it.\r\n return false\r\n\r\n return true\r\n },\r\n dispatchConditionRejection: true,\r\n })\r\n\r\n const mutationThunk = createAsyncThunk<\r\n ThunkResult,\r\n MutationThunkArg,\r\n ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }\r\n >(`${reducerPath}/executeMutation`, executeEndpoint, {\r\n getPendingMeta() {\r\n return { startedTimeStamp: Date.now() }\r\n },\r\n })\r\n\r\n const hasTheForce = (options: any): options is { force: boolean } =>\r\n 'force' in options\r\n const hasMaxAge = (\r\n options: any\r\n ): options is { ifOlderThan: false | number } => 'ifOlderThan' in options\r\n\r\n const prefetch =\r\n <EndpointName extends QueryKeys<Definitions>>(\r\n endpointName: EndpointName,\r\n arg: any,\r\n options: PrefetchOptions\r\n ): ThunkAction<void, any, any, AnyAction> =>\r\n (dispatch: ThunkDispatch<any, any, any>, getState: () => any) => {\r\n const force = hasTheForce(options) && options.force\r\n const maxAge = hasMaxAge(options) && options.ifOlderThan\r\n\r\n const queryAction = (force: boolean = true) =>\r\n (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).initiate(\r\n arg,\r\n { forceRefetch: force }\r\n )\r\n const latestStateValue = (\r\n api.endpoints[endpointName] as ApiEndpointQuery<any, any>\r\n ).select(arg)(getState())\r\n\r\n if (force) {\r\n dispatch(queryAction())\r\n } else if (maxAge) {\r\n const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp\r\n if (!lastFulfilledTs) {\r\n dispatch(queryAction())\r\n return\r\n }\r\n const shouldRetrigger =\r\n (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1000 >=\r\n maxAge\r\n if (shouldRetrigger) {\r\n dispatch(queryAction())\r\n }\r\n } else {\r\n // If prefetching with no options, just let it try\r\n dispatch(queryAction(false))\r\n }\r\n }\r\n\r\n function matchesEndpoint(endpointName: string) {\r\n return (action: any): action is AnyAction =>\r\n action?.meta?.arg?.endpointName === endpointName\r\n }\r\n\r\n function buildMatchThunkActions<\r\n Thunk extends\r\n | AsyncThunk<any, QueryThunkArg, ThunkApiMetaConfig>\r\n | AsyncThunk<any, MutationThunkArg, ThunkApiMetaConfig>\r\n >(thunk: Thunk, endpointName: string) {\r\n return {\r\n matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),\r\n matchFulfilled: isAllOf(\r\n isFulfilled(thunk),\r\n matchesEndpoint(endpointName)\r\n ),\r\n matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName)),\r\n } as Matchers<Thunk, any>\r\n }\r\n\r\n return {\r\n queryThunk,\r\n mutationThunk,\r\n prefetch,\r\n updateQueryData,\r\n patchQueryData,\r\n buildMatchThunkActions,\r\n }\r\n}\r\n\r\nexport function calculateProvidedByThunk(\r\n action: UnwrapPromise<\r\n ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<MutationThunk>>\r\n >,\r\n type: 'providesTags' | 'invalidatesTags',\r\n endpointDefinitions: EndpointDefinitions,\r\n assertTagType: AssertTagTypes\r\n) {\r\n return calculateProvidedBy(\r\n endpointDefinitions[action.meta.arg.endpointName][type],\r\n isFulfilled(action) ? action.payload : undefined,\r\n isRejectedWithValue(action) ? action.payload : undefined,\r\n action.meta.arg.originalArgs,\r\n 'baseQueryMeta' in action.meta ? action.meta.baseQueryMeta : undefined,\r\n assertTagType\r\n )\r\n}\r\n","import type { QueryCacheKey } from './core/apiState'\r\nimport type { EndpointDefinition } from './endpointDefinitions'\r\nimport { isPlainObject } from '@reduxjs/toolkit'\r\n\r\nexport const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({\r\n endpointName,\r\n queryArgs,\r\n}) => {\r\n // Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })\r\n return `${endpointName}(${JSON.stringify(queryArgs, (key, value) =>\r\n isPlainObject(value)\r\n ? Object.keys(value)\r\n .sort()\r\n .reduce<any>((acc, key) => {\r\n acc[key] = (value as any)[key]\r\n return acc\r\n }, {})\r\n : value\r\n )})`\r\n}\r\n\r\nexport type SerializeQueryArgs<QueryArgs> = (_: {\r\n queryArgs: QueryArgs\r\n endpointDefinition: EndpointDefinition<any, any, any, any>\r\n endpointName: string\r\n}) => string\r\n\r\nexport type InternalSerializeQueryArgs = (_: {\r\n queryArgs: any\r\n endpointDefinition: EndpointDefinition<any, any, any, any>\r\n endpointName: string\r\n}) => QueryCacheKey\r\n","import type { Api, ApiContext, Module, ModuleName } from './apiTypes'\r\nimport type { CombinedState } from './core/apiState'\r\nimport type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes'\r\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs'\r\nimport { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs'\r\nimport type {\r\n EndpointBuilder,\r\n EndpointDefinitions,\r\n} from './endpointDefinitions'\r\nimport { DefinitionType } from './endpointDefinitions'\r\nimport { nanoid } from '@reduxjs/toolkit'\r\nimport type { AnyAction } from '@reduxjs/toolkit'\r\nimport type { NoInfer } from './tsHelpers'\r\nimport { defaultMemoize } from 'reselect'\r\n\r\nexport interface CreateApiOptions<\r\n BaseQuery extends BaseQueryFn,\r\n Definitions extends EndpointDefinitions,\r\n ReducerPath extends string = 'api',\r\n TagTypes extends string = never\r\n> {\r\n /**\r\n * The base query used by each endpoint if no `queryFn` option is specified. RTK Query exports a utility called [fetchBaseQuery](./fetchBaseQuery) as a lightweight wrapper around `fetch` for common use-cases. See [Customizing Queries](../../rtk-query/usage/customizing-queries) if `fetchBaseQuery` does not handle your requirements.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\r\n *\r\n * const api = createApi({\r\n * // highlight-start\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * // highlight-end\r\n * endpoints: (build) => ({\r\n * // ...endpoints\r\n * }),\r\n * })\r\n * ```\r\n */\r\n baseQuery: BaseQuery\r\n /**\r\n * An array of string tag type names. Specifying tag types is optional, but you should define them so that they can be used for caching and invalidation. When defining a tag type, you will be able to [provide](../../rtk-query/usage/automated-refetching#providing-tags) them with `providesTags` and [invalidate](../../rtk-query/usage/automated-refetching#invalidating-tags) them with `invalidatesTags` when configuring [endpoints](#endpoints).\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * // highlight-start\r\n * tagTypes: ['Post', 'User'],\r\n * // highlight-end\r\n * endpoints: (build) => ({\r\n * // ...endpoints\r\n * }),\r\n * })\r\n * ```\r\n */\r\n tagTypes?: readonly TagTypes[]\r\n /**\r\n * The `reducerPath` is a _unique_ key that your service will be mounted to in your store. If you call `createApi` more than once in your application, you will need to provide a unique value each time. Defaults to `'api'`.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"apis.js\"\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';\r\n *\r\n * const apiOne = createApi({\r\n * // highlight-start\r\n * reducerPath: 'apiOne',\r\n * // highlight-end\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * endpoints: (builder) => ({\r\n * // ...endpoints\r\n * }),\r\n * });\r\n *\r\n * const apiTwo = createApi({\r\n * // highlight-start\r\n * reducerPath: 'apiTwo',\r\n * // highlight-end\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * endpoints: (builder) => ({\r\n * // ...endpoints\r\n * }),\r\n * });\r\n * ```\r\n */\r\n reducerPath?: ReducerPath\r\n /**\r\n * Accepts a custom function if you have a need to change the creation of cache keys for any reason.\r\n */\r\n serializeQueryArgs?: SerializeQueryArgs<BaseQueryArg<BaseQuery>>\r\n /**\r\n * Endpoints are just a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are two basic endpoint types: [`query`](../../rtk-query/usage/queries) and [`mutation`](../../rtk-query/usage/mutations).\r\n */\r\n endpoints(\r\n build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>\r\n ): Definitions\r\n /**\r\n * Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"keepUnusedDataFor example\"\r\n *\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\r\n * interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n * type PostsResponse = Post[]\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * endpoints: (build) => ({\r\n * getPosts: build.query<PostsResponse, void>({\r\n * query: () => 'posts',\r\n * // highlight-start\r\n * keepUnusedDataFor: 5\r\n * // highlight-end\r\n * })\r\n * })\r\n * })\r\n * ```\r\n */\r\n keepUnusedDataFor?: number\r\n /**\r\n * Defaults to `false`. This setting allows you to control whether if a cached result is already available RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\r\n * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\r\n * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\r\n * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\r\n *\r\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\r\n */\r\n refetchOnMountOrArgChange?: boolean | number\r\n /**\r\n * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\r\n *\r\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\r\n *\r\n * Note: requires [`setupListeners`](./setupListeners) to have been called.\r\n */\r\n refetchOnFocus?: boolean\r\n /**\r\n * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\r\n *\r\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\r\n *\r\n * Note: requires [`setupListeners`](./setupListeners) to have been called.\r\n */\r\n refetchOnReconnect?: boolean\r\n /**\r\n * A function that is passed every dispatched action. If this returns something other than `undefined`,\r\n * that return value will be used to rehydrate fulfilled & errored queries.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * // codeblock-meta title=\"next-redux-wrapper rehydration example\"\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\r\n * import { HYDRATE } from 'next-redux-wrapper'\r\n *\r\n * export const api = createApi({\r\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\r\n * // highlight-start\r\n * extractRehydrationInfo(action, { reducerPath }) {\r\n * if (action.type === HYDRATE) {\r\n * return action.payload[reducerPath]\r\n * }\r\n * },\r\n * // highlight-end\r\n * endpoints: (build) => ({\r\n * // omitted\r\n * }),\r\n * })\r\n * ```\r\n */\r\n extractRehydrationInfo?: (\r\n action: AnyAction,\r\n {\r\n reducerPath,\r\n }: {\r\n reducerPath: ReducerPath\r\n }\r\n ) =>\r\n | undefined\r\n | CombinedState<\r\n NoInfer<Definitions>,\r\n NoInfer<TagTypes>,\r\n NoInfer<ReducerPath>\r\n >\r\n}\r\n\r\nexport type CreateApi<Modules extends ModuleName> = {\r\n /**\r\n * Creates a service to use in your application. Contains only the basic redux logic (the core module).\r\n *\r\n * @link https://rtk-query-docs.netlify.app/api/createApi\r\n */\r\n <\r\n BaseQuery extends BaseQueryFn,\r\n Definitions extends EndpointDefinitions,\r\n ReducerPath extends string = 'api',\r\n TagTypes extends string = never\r\n >(\r\n options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>\r\n ): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>\r\n}\r\n\r\n/**\r\n * Builds a `createApi` method based on the provided `modules`.\r\n *\r\n * @link https://rtk-query-docs.netlify.app/concepts/customizing-create-api\r\n *\r\n * @example\r\n * ```ts\r\n * const MyContext = React.createContext<ReactReduxContextValue>(null as any);\r\n * const customCreateApi = buildCreateApi(\r\n * coreModule(),\r\n * reactHooksModule({ useDispatch: createDispatchHook(MyContext) })\r\n * );\r\n * ```\r\n *\r\n * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints\r\n * @returns A `createApi` method using the provided `modules`.\r\n */\r\nexport function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(\r\n ...modules: Modules\r\n): CreateApi<Modules[number]['name']> {\r\n return function baseCreateApi(options) {\r\n const extractRehydrationInfo = defaultMemoize((action: AnyAction) =>\r\n options.extractRehydrationInfo?.(action, {\r\n reducerPath: (options.reducerPath ?? 'api') as any,\r\n })\r\n )\r\n\r\n const optionsWithDefaults = {\r\n reducerPath: 'api',\r\n serializeQueryArgs: defaultSerializeQueryArgs,\r\n keepUnusedDataFor: 60,\r\n refetchOnMountOrArgChange: false,\r\n refetchOnFocus: false,\r\n refetchOnReconnect: false,\r\n ...options,\r\n extractRehydrationInfo,\r\n tagTypes: [...(options.tagTypes || [])],\r\n }\r\n\r\n const context: ApiContext<EndpointDefinitions> = {\r\n endpointDefinitions: {},\r\n batch(fn) {\r\n // placeholder \"batch\" method to be overridden by plugins, for example with React.unstable_batchedUpdate\r\n fn()\r\n },\r\n apiUid: nanoid(),\r\n extractRehydrationInfo,\r\n hasRehydrationInfo: defaultMemoize(\r\n (action) => extractRehydrationInfo(action) != null\r\n ),\r\n }\r\n\r\n const api = {\r\n injectEndpoints,\r\n enhanceEndpoints({ addTagTypes, endpoints }) {\r\n if (addTagTypes) {\r\n for (const eT of addTagTypes) {\r\n if (!optionsWithDefaults.tagTypes.includes(eT as any)) {\r\n optionsWithDefaults.tagTypes.push(eT as any)\r\n }\r\n }\r\n }\r\n if (endpoints) {\r\n for (const [endpointName, partialDefinition] of Object.entries(\r\n endpoints\r\n )) {\r\n if (typeof partialDefinition === 'function') {\r\n partialDefinition(context.endpointDefinitions[endpointName])\r\n }\r\n Object.assign(\r\n context.endpointDefinitions[endpointName] || {},\r\n partialDefinition\r\n )\r\n }\r\n }\r\n return api\r\n },\r\n } as Api<BaseQueryFn, {}, string, string, Modules[number]['name']>\r\n\r\n const initializedModules = modules.map((m) =>\r\n m.init(api as any, optionsWithDefaults, context)\r\n )\r\n\r\n function injectEndpoints(\r\n inject: Parameters<typeof api.injectEndpoints>[0]\r\n ) {\r\n const evaluatedEndpoints = inject.endpoints({\r\n query: (x) => ({ ...x, type: DefinitionType.query } as any),\r\n mutation: (x) => ({ ...x, type: DefinitionType.mutation } as any),\r\n })\r\n\r\n for (const [endpointName, definition] of Object.entries(\r\n evaluatedEndpoints\r\n )) {\r\n if (\r\n !inject.overrideExisting &&\r\n endpointName in context.endpointDefinitions\r\n ) {\r\n if (\r\n typeof process !== 'undefined' &&\r\n process.env.NODE_ENV === 'development'\r\n ) {\r\n console.error(\r\n `called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``\r\n )\r\n }\r\n\r\n continue\r\n }\r\n context.endpointDefinitions[endpointName] = definition\r\n for (const m of initializedModules) {\r\n m.injectEndpoint(endpointName, definition)\r\n }\r\n }\r\n\r\n return api as any\r\n }\r\n\r\n return api.injectEndpoints({ endpoints: options.endpoints as any })\r\n }\r\n}\r\n","import type { BaseQueryFn } from './baseQueryTypes'\r\n\r\nconst _NEVER = /* @__PURE__ */ Symbol()\r\nexport type NEVER = typeof _NEVER\r\n\r\n/**\r\n * Creates a \"fake\" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.\r\n * This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.\r\n */\r\nexport function fakeBaseQuery<ErrorType>(): BaseQueryFn<\r\n void,\r\n NEVER,\r\n ErrorType,\r\n {}\r\n> {\r\n return function () {\r\n throw new Error(\r\n 'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.'\r\n )\r\n }\r\n}\r\n","import { compose } from 'redux'\r\n\r\nimport type { AnyAction, Middleware, ThunkDispatch } from '@reduxjs/toolkit'\r\nimport { createAction } from '@reduxjs/toolkit'\r\n\r\nimport type {\r\n EndpointDefinitions,\r\n FullTagDescription,\r\n} from '../../endpointDefinitions'\r\nimport type { QueryStatus, QuerySubState, RootState } from '../apiState'\r\nimport type { QueryThunkArg } from '../buildThunks'\r\nimport { build as buildCacheCollection } from './cacheCollection'\r\nimport { build as buildInvalidationByTags } from './invalidationByTags'\r\nimport { build as buildPolling } from './polling'\r\nimport type { BuildMiddlewareInput } from './types'\r\nimport { build as buildWindowEventHandling } from './windowEventHandling'\r\nimport { build as buildCacheLifecycle } from './cacheLifecycle'\r\nimport { build as buildQueryLifecycle } from './queryLifecycle'\r\nimport { build as buildDevMiddleware } from './devMiddleware'\r\n\r\nexport function buildMiddleware<\r\n Definitions extends EndpointDefinitions,\r\n ReducerPath extends string,\r\n TagTypes extends string\r\n>(input: BuildMiddlewareInput<Definitions, ReducerPath, TagTypes>) {\r\n const { reducerPath, queryThunk } = input\r\n const actions = {\r\n invalidateTags: createAction<\r\n Array<TagTypes | FullTagDescription<TagTypes>>\r\n >(`${reducerPath}/invalidateTags`),\r\n }\r\n\r\n const middlewares = [\r\n buildDevMiddleware,\r\n buildCacheCollection,\r\n buildInvalidationByTags,\r\n buildPolling,\r\n buildWindowEventHandling,\r\n buildCacheLifecycle,\r\n buildQueryLifecycle,\r\n ].map((build) =>\r\n build({\r\n ...(input as any as BuildMiddlewareInput<\r\n EndpointDefinitions,\r\n string,\r\n string\r\n >),\r\n refetchQuery,\r\n })\r\n )\r\n const middleware: Middleware<\r\n {},\r\n RootState<Definitions, string, ReducerPath>,\r\n ThunkDispatch<any, any, AnyAction>\r\n > = (mwApi) => (next) => {\r\n const applied = compose<typeof next>(\r\n ...middlewares.map((middleware) => middleware(mwApi))\r\n )(next)\r\n return (action) => {\r\n if (mwApi.getState()[reducerPath]) {\r\n return applied(action)\r\n }\r\n return next(action)\r\n }\r\n }\r\n\r\n return { middleware, actions }\r\n\r\n function refetchQuery(\r\n querySubState: Exclude<\r\n QuerySubState<any>,\r\n { status: QueryStatus.uninitialized }\r\n >,\r\n queryCacheKey: string,\r\n override: Partial<QueryThunkArg> = {}\r\n ) {\r\n return queryThunk({\r\n type: 'query',\r\n endpointName: querySubState.endpointName,\r\n originalArgs: querySubState.originalArgs,\r\n subscribe: false,\r\n forceRefetch: true,\r\n queryCacheKey: queryCacheKey as any,\r\n ...override,\r\n })\r\n }\r\n}\r\n","import type { BaseQueryFn } from '../../baseQueryTypes'\r\nimport type { QueryDefinition } from '../../endpointDefinitions'\r\nimport type { ConfigState, QueryCacheKey } from '../apiState'\r\nimport { QuerySubstateIdentifier } from '../apiState'\r\nimport type {\r\n QueryStateMeta,\r\n SubMiddlewareApi,\r\n SubMiddlewareBuilder,\r\n TimeoutId,\r\n} from './types'\r\n\r\nexport type ReferenceCacheCollection = never\r\n\r\ndeclare module '../../endpointDefinitions' {\r\n interface QueryExtraOptions<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string = string\r\n > {\r\n /**\r\n * Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(This value is in seconds.)_\r\n *\r\n * This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.\r\n */\r\n keepUnusedDataFor?: number\r\n }\r\n}\r\n\r\nexport const build: SubMiddlewareBuilder = ({ reducerPath, api, context }) => {\r\n const { removeQueryResult, unsubscribeQueryResult } = api.internalActions\r\n\r\n return (mwApi) => {\r\n const currentRemovalTimeouts: QueryStateMeta<TimeoutId> = {}\r\n\r\n return (next) =>\r\n (action): any => {\r\n const result = next(action)\r\n\r\n if (unsubscribeQueryResult.match(action)) {\r\n const state = mwApi.getState()[reducerPath]\r\n const { queryCacheKey } = action.payload\r\n\r\n handleUnsubscribe(\r\n queryCacheKey,\r\n state.queries[queryCacheKey]?.endpointName,\r\n mwApi,\r\n state.config\r\n )\r\n }\r\n\r\n if (api.util.resetApiState.match(action)) {\r\n for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {\r\n if (timeout) clearTimeout(timeout)\r\n delete currentRemovalTimeouts[key]\r\n }\r\n }\r\n\r\n if (context.hasRehydrationInfo(action)) {\r\n const state = mwApi.getState()[reducerPath]\r\n const { queries } = context.extractRehydrationInfo(action)!\r\n for (const [queryCacheKey, queryState] of Object.entries(queries)) {\r\n // Gotcha:\r\n // If rehydrating before the endpoint has been injected,the global `keepUnusedDataFor`\r\n // will be used instead of the endpoint-specific one.\r\n handleUnsubscribe(\r\n queryCacheKey as QueryCacheKey,\r\n queryState?.endpointName,\r\n mwApi,\r\n state.config\r\n )\r\n }\r\n }\r\n\r\n return result\r\n }\r\n\r\n function handleUnsubscribe(\r\n queryCacheKey: QueryCacheKey,\r\n endpointName: string | undefined,\r\n api: SubMiddlewareApi,\r\n config: ConfigState<string>\r\n ) {\r\n const endpointDefinition = context.endpointDefinitions[\r\n endpointName!\r\n ] as QueryDefinition<any, any, any, any>\r\n const keepUnusedDataFor =\r\n endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor\r\n\r\n const currentTimeout = currentRemovalTimeouts[queryCacheKey]\r\n if (currentTimeout) {\r\n clearTimeout(currentTimeout)\r\n }\r\n currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {\r\n const subscriptions =\r\n api.getState()[reducerPath].subscriptions[queryCacheKey]\r\n if (!subscriptions || Object.keys(subscriptions).length === 0) {\r\n api.dispatch(removeQueryResult({ queryCacheKey }))\r\n }\r\n delete currentRemovalTimeouts![queryCacheKey]\r\n }, keepUnusedDataFor * 1000)\r\n }\r\n }\r\n}\r\n","import { isAnyOf, isFulfilled, isRejectedWithValue } from '@reduxjs/toolkit'\r\n\r\nimport type { FullTagDescription } from '../../endpointDefinitions'\r\nimport { calculateProvidedBy } from '../../endpointDefinitions'\r\nimport type { QueryCacheKey } from '../apiState'\r\nimport { QueryStatus } from '../apiState'\r\nimport { calculateProvidedByThunk } from '../buildThunks'\r\nimport type { SubMiddlewareApi, SubMiddlewareBuilder } from './types'\r\n\r\nexport const build: SubMiddlewareBuilder = ({\r\n reducerPath,\r\n context,\r\n context: { endpointDefinitions },\r\n mutationThunk,\r\n api,\r\n assertTagType,\r\n refetchQuery,\r\n}) => {\r\n const { removeQueryResult } = api.internalActions\r\n\r\n return (mwApi) =>\r\n (next) =>\r\n (action): any => {\r\n const result = next(action)\r\n\r\n if (\r\n isAnyOf(\r\n isFulfilled(mutationThunk),\r\n isRejectedWithValue(mutationThunk)\r\n )(action)\r\n ) {\r\n invalidateTags(\r\n calculateProvidedByThunk(\r\n action,\r\n 'invalidatesTags',\r\n endpointDefinitions,\r\n assertTagType\r\n ),\r\n mwApi\r\n )\r\n }\r\n\r\n if (api.util.invalidateTags.match(action)) {\r\n invalidateTags(\r\n calculateProvidedBy(\r\n action.payload,\r\n undefined,\r\n undefined,\r\n undefined,\r\n undefined,\r\n assertTagType\r\n ),\r\n mwApi\r\n )\r\n }\r\n\r\n return result\r\n }\r\n\r\n function invalidateTags(\r\n tags: readonly FullTagDescription<string>[],\r\n mwApi: SubMiddlewareApi\r\n ) {\r\n const rootState = mwApi.getState()\r\n const state = rootState[reducerPath]\r\n\r\n const toInvalidate = api.util.selectInvalidatedBy(rootState, tags)\r\n\r\n context.batch(() => {\r\n const valuesArray = Array.from(toInvalidate.values())\r\n for (const { queryCacheKey } of valuesArray) {\r\n const querySubState = state.queries[queryCacheKey]\r\n const subscriptionSubState = state.subscriptions[queryCacheKey]\r\n if (querySubState && subscriptionSubState) {\r\n if (Object.keys(subscriptionSubState).length === 0) {\r\n mwApi.dispatch(\r\n removeQueryResult({\r\n queryCacheKey: queryCacheKey as QueryCacheKey,\r\n })\r\n )\r\n } else if (querySubState.status !== QueryStatus.uninitialized) {\r\n mwApi.dispatch(refetchQuery(querySubState, queryCacheKey))\r\n } else {\r\n }\r\n }\r\n }\r\n })\r\n }\r\n}\r\n","import type { QuerySubstateIdentifier, Subscribers } from '../apiState'\r\nimport { QueryStatus } from '../apiState'\r\nimport type {\r\n QueryStateMeta,\r\n SubMiddlewareApi,\r\n SubMiddlewareBuilder,\r\n TimeoutId,\r\n} from './types'\r\n\r\nexport const build: SubMiddlewareBuilder = ({\r\n reducerPath,\r\n queryThunk,\r\n api,\r\n refetchQuery,\r\n}) => {\r\n return (mwApi) => {\r\n const currentPolls: QueryStateMeta<{\r\n nextPollTimestamp: number\r\n timeout?: TimeoutId\r\n pollingInterval: number\r\n }> = {}\r\n\r\n return (next) =>\r\n (action): any => {\r\n const result = next(action)\r\n\r\n if (\r\n api.internalActions.updateSubscriptionOptions.match(action) ||\r\n api.internalActions.unsubscribeQueryResult.match(action)\r\n ) {\r\n updatePollingInterval(action.payload, mwApi)\r\n }\r\n\r\n if (\r\n queryThunk.pending.match(action) ||\r\n (queryThunk.rejected.match(action) && action.meta.condition)\r\n ) {\r\n updatePollingInterval(action.meta.arg, mwApi)\r\n }\r\n\r\n if (\r\n queryThunk.fulfilled.match(action) ||\r\n (queryThunk.rejected.match(action) && !action.meta.condition)\r\n ) {\r\n startNextPoll(action.meta.arg, mwApi)\r\n }\r\n\r\n if (api.util.resetApiState.match(action)) {\r\n clearPolls()\r\n }\r\n\r\n return result\r\n }\r\n\r\n function startNextPoll(\r\n { queryCacheKey }: QuerySubstateIdentifier,\r\n api: SubMiddlewareApi\r\n ) {\r\n const state = api.getState()[reducerPath]\r\n const querySubState = state.queries[queryCacheKey]\r\n const subscriptions = state.subscriptions[queryCacheKey]\r\n\r\n if (!querySubState || querySubState.status === QueryStatus.uninitialized)\r\n return\r\n\r\n const lowestPollingInterval = findLowestPollingInterval(subscriptions)\r\n if (!Number.isFinite(lowestPollingInterval)) return\r\n\r\n const currentPoll = currentPolls[queryCacheKey]\r\n\r\n if (currentPoll?.timeout) {\r\n clearTimeout(currentPoll.timeout)\r\n currentPoll.timeout = undefined\r\n }\r\n\r\n const nextPollTimestamp = Date.now() + lowestPollingInterval\r\n\r\n const currentInterval: typeof currentPolls[number] = (currentPolls[\r\n queryCacheKey\r\n ] = {\r\n nextPollTimestamp,\r\n pollingInterval: lowestPollingInterval,\r\n timeout: setTimeout(() => {\r\n currentInterval!.timeout = undefined\r\n api.dispatch(refetchQuery(querySubState, queryCacheKey))\r\n }, lowestPollingInterval),\r\n })\r\n }\r\n\r\n function updatePollingInterval(\r\n { queryCacheKey }: QuerySubstateIdentifier,\r\n api: SubMiddlewareApi\r\n ) {\r\n const state = api.getState()[reducerPath]\r\n const querySubState = state.queries[queryCacheKey]\r\n const subscriptions = state.subscriptions[queryCacheKey]\r\n\r\n if (\r\n !querySubState ||\r\n querySubState.status === QueryStatus.uninitialized\r\n ) {\r\n return\r\n }\r\n\r\n const lowestPollingInterval = findLowestPollingInterval(subscriptions)\r\n\r\n if (!Number.isFinite(lowestPollingInterval)) {\r\n cleanupPollForKey(queryCacheKey)\r\n return\r\n }\r\n\r\n const currentPoll = currentPolls[queryCacheKey]\r\n const nextPollTimestamp = Date.now() + lowestPollingInterval\r\n\r\n if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {\r\n startNextPoll({ queryCacheKey }, api)\r\n }\r\n }\r\n\r\n function cleanupPollForKey(key: string) {\r\n const existingPoll = currentPolls[key]\r\n if (existingPoll?.timeout) {\r\n clearTimeout(existingPoll.timeout)\r\n }\r\n delete currentPolls[key]\r\n }\r\n\r\n function clearPolls() {\r\n for (const key of Object.keys(currentPolls)) {\r\n cleanupPollForKey(key)\r\n }\r\n }\r\n }\r\n\r\n function findLowestPollingInterval(subscribers: Subscribers = {}) {\r\n let lowestPollingInterval = Number.POSITIVE_INFINITY\r\n for (const subscription of Object.values(subscribers)) {\r\n if (!!subscription.pollingInterval)\r\n lowestPollingInterval = Math.min(\r\n subscription.pollingInterval,\r\n lowestPollingInterval\r\n )\r\n }\r\n return lowestPollingInterval\r\n }\r\n}\r\n","import { QueryStatus } from '../apiState'\r\nimport type { QueryCacheKey } from '../apiState'\r\nimport { onFocus, onOnline } from '../setupListeners'\r\nimport type { SubMiddlewareApi, SubMiddlewareBuilder } from './types'\r\n\r\nexport const build: SubMiddlewareBuilder = ({\r\n reducerPath,\r\n context,\r\n api,\r\n refetchQuery,\r\n}) => {\r\n const { removeQueryResult } = api.internalActions\r\n\r\n return (mwApi) =>\r\n (next) =>\r\n (action): any => {\r\n const result = next(action)\r\n\r\n if (onFocus.match(action)) {\r\n refetchValidQueries(mwApi, 'refetchOnFocus')\r\n }\r\n if (onOnline.match(action)) {\r\n refetchValidQueries(mwApi, 'refetchOnReconnect')\r\n }\r\n\r\n return result\r\n }\r\n\r\n function refetchValidQueries(\r\n api: SubMiddlewareApi,\r\n type: 'refetchOnFocus' | 'refetchOnReconnect'\r\n ) {\r\n const state = api.getState()[reducerPath]\r\n const queries = state.queries\r\n const subscriptions = state.subscriptions\r\n\r\n context.batch(() => {\r\n for (const queryCacheKey of Object.keys(subscriptions)) {\r\n const querySubState = queries[queryCacheKey]\r\n const subscriptionSubState = subscriptions[queryCacheKey]\r\n\r\n if (!subscriptionSubState || !querySubState) continue\r\n\r\n const shouldRefetch =\r\n Object.values(subscriptionSubState).some(\r\n (sub) => sub[type] === true\r\n ) ||\r\n (Object.values(subscriptionSubState).every(\r\n (sub) => sub[type] === undefined\r\n ) &&\r\n state.config[type])\r\n\r\n if (shouldRefetch) {\r\n if (Object.keys(subscriptionSubState).length === 0) {\r\n api.dispatch(\r\n removeQueryResult({\r\n queryCacheKey: queryCacheKey as QueryCacheKey,\r\n })\r\n )\r\n } else if (querySubState.status !== QueryStatus.uninitialized) {\r\n api.dispatch(refetchQuery(querySubState, queryCacheKey))\r\n }\r\n }\r\n }\r\n })\r\n }\r\n}\r\n","import { isAsyncThunkAction, isFulfilled } from '@reduxjs/toolkit'\r\nimport type { AnyAction } from 'redux'\r\nimport type { ThunkDispatch } from 'redux-thunk'\r\nimport type { BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes'\r\nimport { DefinitionType } from '../../endpointDefinitions'\r\nimport type { RootState } from '../apiState'\r\nimport type {\r\n MutationResultSelectorResult,\r\n QueryResultSelectorResult,\r\n} from '../buildSelectors'\r\nimport { getMutationCacheKey } from '../buildSlice'\r\nimport type { PatchCollection, Recipe } from '../buildThunks'\r\nimport type {\r\n PromiseWithKnownReason,\r\n SubMiddlewareApi,\r\n SubMiddlewareBuilder,\r\n} from './types'\r\n\r\nexport type ReferenceCacheLifecycle = never\r\n\r\ndeclare module '../../endpointDefinitions' {\r\n export interface QueryBaseLifecycleApi<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType,\r\n ReducerPath extends string = string\r\n > extends LifecycleApi<ReducerPath> {\r\n /**\r\n * Gets the current value of this cache entry.\r\n */\r\n getCacheEntry(): QueryResultSelectorResult<\r\n { type: DefinitionType.query } & BaseEndpointDefinition<\r\n QueryArg,\r\n BaseQuery,\r\n ResultType\r\n >\r\n >\r\n /**\r\n * Updates the current cache entry value.\r\n * For documentation see `api.util.updateQueryData`.\r\n */\r\n updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection\r\n }\r\n\r\n export interface MutationBaseLifecycleApi<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType,\r\n ReducerPath extends string = string\r\n > extends LifecycleApi<ReducerPath> {\r\n /**\r\n * Gets the current value of this cache entry.\r\n */\r\n getCacheEntry(): MutationResultSelectorResult<\r\n { type: DefinitionType.mutation } & BaseEndpointDefinition<\r\n QueryArg,\r\n BaseQuery,\r\n ResultType\r\n >\r\n >\r\n }\r\n\r\n export interface LifecycleApi<ReducerPath extends string = string> {\r\n /**\r\n * The dispatch method for the store\r\n */\r\n dispatch: ThunkDispatch<any, any, AnyAction>\r\n /**\r\n * A method to get the current state\r\n */\r\n getState(): RootState<any, any, ReducerPath>\r\n /**\r\n * `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.\r\n */\r\n extra: unknown\r\n /**\r\n * A unique ID generated for the mutation\r\n */\r\n requestId: string\r\n }\r\n\r\n export interface CacheLifecyclePromises<\r\n ResultType = unknown,\r\n MetaType = unknown\r\n > {\r\n /**\r\n * Promise that will resolve with the first value for this cache key.\r\n * This allows you to `await` until an actual value is in cache.\r\n *\r\n * If the cache entry is removed from the cache before any value has ever\r\n * been resolved, this Promise will reject with\r\n * `new Error('Promise never resolved before cacheEntryRemoved.')`\r\n * to prevent memory leaks.\r\n * You can just re-throw that error (or not handle it at all) -\r\n * it will be caught outside of `cacheEntryAdded`.\r\n *\r\n * If you don't interact with this promise, it will not throw.\r\n */\r\n cacheDataLoaded: PromiseWithKnownReason<\r\n {\r\n /**\r\n * The (transformed) query result.\r\n */\r\n data: ResultType\r\n /**\r\n * The `meta` returned by the `baseQuery`\r\n */\r\n meta: MetaType\r\n },\r\n typeof neverResolvedError\r\n >\r\n /**\r\n * Promise that allows you to wait for the point in time when the cache entry\r\n * has been removed from the cache, by not being used/subscribed to any more\r\n * in the application for too long or by dispatching `api.util.resetApiState`.\r\n */\r\n cacheEntryRemoved: Promise<void>\r\n }\r\n\r\n export interface QueryCacheLifecycleApi<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType,\r\n ReducerPath extends string = string\r\n > extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,\r\n CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}\r\n\r\n export interface MutationCacheLifecycleApi<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType,\r\n ReducerPath extends string = string\r\n > extends MutationBaseLifecycleApi<\r\n QueryArg,\r\n BaseQuery,\r\n ResultType,\r\n ReducerPath\r\n >,\r\n CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}\r\n\r\n interface QueryExtraOptions<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string = string\r\n > {\r\n onCacheEntryAdded?(\r\n arg: QueryArg,\r\n api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>\r\n ): Promise<void> | void\r\n }\r\n\r\n interface MutationExtraOptions<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string = string\r\n > {\r\n onCacheEntryAdded?(\r\n arg: QueryArg,\r\n api: MutationCacheLifecycleApi<\r\n QueryArg,\r\n BaseQuery,\r\n ResultType,\r\n ReducerPath\r\n >\r\n ): Promise<void> | void\r\n }\r\n}\r\n\r\nconst neverResolvedError = new Error(\r\n 'Promise never resolved before cacheEntryRemoved.'\r\n) as Error & {\r\n message: 'Promise never resolved before cacheEntryRemoved.'\r\n}\r\n\r\nexport const build: SubMiddlewareBuilder = ({\r\n api,\r\n reducerPath,\r\n context,\r\n queryThunk,\r\n mutationThunk,\r\n}) => {\r\n const isQueryThunk = isAsyncThunkAction(queryThunk)\r\n const isMutationThunk = isAsyncThunkAction(mutationThunk)\r\n const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk)\r\n\r\n return (mwApi) => {\r\n type CacheLifecycle = {\r\n valueResolved?(value: { data: unknown; meta: unknown }): unknown\r\n cacheEntryRemoved(): void\r\n }\r\n const lifecycleMap: Record<string, CacheLifecycle> = {}\r\n\r\n return (next) =>\r\n (action): any => {\r\n const stateBefore = mwApi.getState()\r\n\r\n const result = next(action)\r\n\r\n const cacheKey = getCacheKey(action)\r\n\r\n if (queryThunk.pending.match(action)) {\r\n const oldState = stateBefore[reducerPath].queries[cacheKey]\r\n const state = mwApi.getState()[reducerPath].queries[cacheKey]\r\n if (!oldState && state) {\r\n handleNewKey(\r\n action.meta.arg.endpointName,\r\n action.meta.arg.originalArgs,\r\n cacheKey,\r\n mwApi,\r\n action.meta.requestId\r\n )\r\n }\r\n } else if (mutationThunk.pending.match(action)) {\r\n const state = mwApi.getState()[reducerPath].mutations[cacheKey]\r\n if (state) {\r\n handleNewKey(\r\n action.meta.arg.endpointName,\r\n action.meta.arg.originalArgs,\r\n cacheKey,\r\n mwApi,\r\n action.meta.requestId\r\n )\r\n }\r\n } else if (isFullfilledThunk(action)) {\r\n const lifecycle = lifecycleMap[cacheKey]\r\n if (lifecycle?.valueResolved) {\r\n lifecycle.valueResolved({\r\n data: action.payload,\r\n meta: action.meta.baseQueryMeta,\r\n })\r\n delete lifecycle.valueResolved\r\n }\r\n } else if (\r\n api.internalActions.removeQueryResult.match(action) ||\r\n api.internalActions.removeMutationResult.match(action)\r\n ) {\r\n const lifecycle = lifecycleMap[cacheKey]\r\n if (lifecycle) {\r\n delete lifecycleMap[cacheKey]\r\n lifecycle.cacheEntryRemoved()\r\n }\r\n } else if (api.util.resetApiState.match(action)) {\r\n for (const [cacheKey, lifecycle] of Object.entries(lifecycleMap)) {\r\n delete lifecycleMap[cacheKey]\r\n lifecycle.cacheEntryRemoved()\r\n }\r\n }\r\n\r\n return result\r\n }\r\n\r\n function getCacheKey(action: any) {\r\n if (isQueryThunk(action)) return action.meta.arg.queryCacheKey\r\n if (isMutationThunk(action)) return action.meta.requestId\r\n if (api.internalActions.removeQueryResult.match(action))\r\n return action.payload.queryCacheKey\r\n if (api.internalActions.removeMutationResult.match(action))\r\n return getMutationCacheKey(action.payload)\r\n return ''\r\n }\r\n\r\n function handleNewKey(\r\n endpointName: string,\r\n originalArgs: any,\r\n queryCacheKey: string,\r\n mwApi: SubMiddlewareApi,\r\n requestId: string\r\n ) {\r\n const endpointDefinition = context.endpointDefinitions[endpointName]\r\n const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded\r\n if (!onCacheEntryAdded) return\r\n\r\n let lifecycle = {} as CacheLifecycle\r\n\r\n const cacheEntryRemoved = new Promise<void>((resolve) => {\r\n lifecycle.cacheEntryRemoved = resolve\r\n })\r\n const cacheDataLoaded: PromiseWithKnownReason<\r\n { data: unknown; meta: unknown },\r\n typeof neverResolvedError\r\n > = Promise.race([\r\n new Promise<{ data: unknown; meta: unknown }>((resolve) => {\r\n lifecycle.valueResolved = resolve\r\n }),\r\n cacheEntryRemoved.then(() => {\r\n throw neverResolvedError\r\n }),\r\n ])\r\n // prevent uncaught promise rejections from happening.\r\n // if the original promise is used in any way, that will create a new promise that will throw again\r\n cacheDataLoaded.catch(() => {})\r\n lifecycleMap[queryCacheKey] = lifecycle\r\n const selector = (api.endpoints[endpointName] as any).select(\r\n endpointDefinition.type === DefinitionType.query\r\n ? originalArgs\r\n : queryCacheKey\r\n )\r\n\r\n const extra = mwApi.dispatch((_, __, extra) => extra)\r\n const lifecycleApi = {\r\n ...mwApi,\r\n getCacheEntry: () => selector(mwApi.getState()),\r\n requestId,\r\n extra,\r\n updateCachedData: (endpointDefinition.type === DefinitionType.query\r\n ? (updateRecipe: Recipe<any>) =>\r\n mwApi.dispatch(\r\n api.util.updateQueryData(\r\n endpointName as never,\r\n originalArgs,\r\n updateRecipe\r\n )\r\n )\r\n : undefined) as any,\r\n\r\n cacheDataLoaded,\r\n cacheEntryRemoved,\r\n }\r\n\r\n const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi)\r\n // if a `neverResolvedError` was thrown, but not handled in the running handler, do not let it leak out further\r\n Promise.resolve(runningHandler).catch((e) => {\r\n if (e === neverResolvedError) return\r\n throw e\r\n })\r\n }\r\n }\r\n}\r\n","import { isPending, isRejected, isFulfilled } from '@reduxjs/toolkit'\r\nimport type {\r\n BaseQueryError,\r\n BaseQueryFn,\r\n BaseQueryMeta,\r\n} from '../../baseQueryTypes'\r\nimport { DefinitionType } from '../../endpointDefinitions'\r\nimport type { QueryFulfilledRejectionReason } from '../../endpointDefinitions'\r\nimport type { Recipe } from '../buildThunks'\r\nimport type {\r\n SubMiddlewareBuilder,\r\n PromiseWithKnownReason,\r\n PromiseConstructorWithKnownReason,\r\n} from './types'\r\n\r\nexport type ReferenceQueryLifecycle = never\r\n\r\ndeclare module '../../endpointDefinitions' {\r\n export interface QueryLifecyclePromises<\r\n ResultType,\r\n BaseQuery extends BaseQueryFn\r\n > {\r\n /**\r\n * Promise that will resolve with the (transformed) query result.\r\n *\r\n * If the query fails, this promise will reject with the error.\r\n *\r\n * This allows you to `await` for the query to finish.\r\n *\r\n * If you don't interact with this promise, it will not throw.\r\n */\r\n queryFulfilled: PromiseWithKnownReason<\r\n {\r\n /**\r\n * The (transformed) query result.\r\n */\r\n data: ResultType\r\n /**\r\n * The `meta` returned by the `baseQuery`\r\n */\r\n meta: BaseQueryMeta<BaseQuery>\r\n },\r\n QueryFulfilledRejectionReason<BaseQuery>\r\n >\r\n }\r\n\r\n type QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> =\r\n | {\r\n error: BaseQueryError<BaseQuery>\r\n /**\r\n * If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.\r\n */\r\n isUnhandledError: false\r\n /**\r\n * The `meta` returned by the `baseQuery`\r\n */\r\n meta: BaseQueryMeta<BaseQuery>\r\n }\r\n | {\r\n error: unknown\r\n meta?: undefined\r\n /**\r\n * If this is `true`, that means that this error is the result of `baseQueryFn`, `queryFn` or `transformResponse` throwing an error instead of handling it properly.\r\n * There can not be made any assumption about the shape of `error`.\r\n */\r\n isUnhandledError: true\r\n }\r\n\r\n interface QueryExtraOptions<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string = string\r\n > {\r\n /**\r\n * A function that is called when the individual query is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).\r\n *\r\n * Can be used to perform side-effects throughout the lifecycle of the query.\r\n *\r\n * @example\r\n * ```ts\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\r\n * import { messageCreated } from './notificationsSlice\r\n * export interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({\r\n * baseUrl: '/',\r\n * }),\r\n * endpoints: (build) => ({\r\n * getPost: build.query<Post, number>({\r\n * query: (id) => `post/${id}`,\r\n * async onQueryStarted(id, { dispatch, queryFulfilled }) {\r\n * // `onStart` side-effect\r\n * dispatch(messageCreated('Fetching posts...'))\r\n * try {\r\n * const { data } = await queryFulfilled\r\n * // `onSuccess` side-effect\r\n * dispatch(messageCreated('Posts received!'))\r\n * } catch (err) {\r\n * // `onError` side-effect\r\n * dispatch(messageCreated('Error fetching posts!'))\r\n * }\r\n * }\r\n * }),\r\n * }),\r\n * })\r\n * ```\r\n */\r\n onQueryStarted?(\r\n arg: QueryArg,\r\n api: QueryLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>\r\n ): Promise<void> | void\r\n }\r\n\r\n interface MutationExtraOptions<\r\n TagTypes extends string,\r\n ResultType,\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ReducerPath extends string = string\r\n > {\r\n /**\r\n * A function that is called when the individual mutation is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).\r\n *\r\n * Can be used for `optimistic updates`.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\r\n * export interface Post {\r\n * id: number\r\n * name: string\r\n * }\r\n *\r\n * const api = createApi({\r\n * baseQuery: fetchBaseQuery({\r\n * baseUrl: '/',\r\n * }),\r\n * tagTypes: ['Post'],\r\n * endpoints: (build) => ({\r\n * getPost: build.query<Post, number>({\r\n * query: (id) => `post/${id}`,\r\n * providesTags: ['Post'],\r\n * }),\r\n * updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({\r\n * query: ({ id, ...patch }) => ({\r\n * url: `post/${id}`,\r\n * method: 'PATCH',\r\n * body: patch,\r\n * }),\r\n * invalidatesTags: ['Post'],\r\n * async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\r\n * const patchResult = dispatch(\r\n * api.util.updateQueryData('getPost', id, (draft) => {\r\n * Object.assign(draft, patch)\r\n * })\r\n * )\r\n * try {\r\n * await queryFulfilled\r\n * } catch {\r\n * patchResult.undo()\r\n * }\r\n * },\r\n * }),\r\n * }),\r\n * })\r\n * ```\r\n */\r\n onQueryStarted?(\r\n arg: QueryArg,\r\n api: MutationLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>\r\n ): Promise<void> | void\r\n }\r\n\r\n export interface QueryLifecycleApi<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType,\r\n ReducerPath extends string = string\r\n > extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,\r\n QueryLifecyclePromises<ResultType, BaseQuery> {}\r\n\r\n export interface MutationLifecycleApi<\r\n QueryArg,\r\n BaseQuery extends BaseQueryFn,\r\n ResultType,\r\n ReducerPath extends string = string\r\n > extends MutationBaseLifecycleApi<\r\n QueryArg,\r\n BaseQuery,\r\n ResultType,\r\n ReducerPath\r\n >,\r\n QueryLifecyclePromises<ResultType, BaseQuery> {}\r\n}\r\n\r\nexport const build: SubMiddlewareBuilder = ({\r\n api,\r\n context,\r\n queryThunk,\r\n mutationThunk,\r\n}) => {\r\n const isPendingThunk = isPending(queryThunk, mutationThunk)\r\n const isRejectedThunk = isRejected(queryThunk, mutationThunk)\r\n const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk)\r\n\r\n return (mwApi) => {\r\n type CacheLifecycle = {\r\n resolve(value: { data: unknown; meta: unknown }): unknown\r\n reject(value: QueryFulfilledRejectionReason<any>): unknown\r\n }\r\n const lifecycleMap: Record<string, CacheLifecycle> = {}\r\n\r\n return (next) =>\r\n (action): any => {\r\n const result = next(action)\r\n\r\n if (isPendingThunk(action)) {\r\n const {\r\n requestId,\r\n arg: { endpointName, originalArgs },\r\n } = action.meta\r\n const endpointDefinition = context.endpointDefinitions[endpointName]\r\n const onQueryStarted = endpointDefinition?.onQueryStarted\r\n if (onQueryStarted) {\r\n const lifecycle = {} as CacheLifecycle\r\n const queryFulfilled =\r\n new (Promise as PromiseConstructorWithKnownReason)<\r\n { data: unknown; meta: unknown },\r\n QueryFulfilledRejectionReason<any>\r\n >((resolve, reject) => {\r\n lifecycle.resolve = resolve\r\n lifecycle.reject = reject\r\n })\r\n // prevent uncaught promise rejections from happening.\r\n // if the original promise is used in any way, that will create a new promise that will throw again\r\n queryFulfilled.catch(() => {})\r\n lifecycleMap[requestId] = lifecycle\r\n const selector = (api.endpoints[endpointName] as any).select(\r\n endpointDefinition.type === DefinitionType.query\r\n ? originalArgs\r\n : requestId\r\n )\r\n\r\n const extra = mwApi.dispatch((_, __, extra) => extra)\r\n const lifecycleApi = {\r\n ...mwApi,\r\n getCacheEntry: () => selector(mwApi.getState()),\r\n requestId,\r\n extra,\r\n updateCachedData: (endpointDefinition.type ===\r\n DefinitionType.query\r\n ? (updateRecipe: Recipe<any>) =>\r\n mwApi.dispatch(\r\n api.util.updateQueryData(\r\n endpointName as never,\r\n originalArgs,\r\n updateRecipe\r\n )\r\n )\r\n : undefined) as any,\r\n queryFulfilled,\r\n }\r\n onQueryStarted(originalArgs, lifecycleApi)\r\n }\r\n } else if (isFullfilledThunk(action)) {\r\n const { requestId, baseQueryMeta } = action.meta\r\n lifecycleMap[requestId]?.resolve({\r\n data: action.payload,\r\n meta: baseQueryMeta,\r\n })\r\n delete lifecycleMap[requestId]\r\n } else if (isRejectedThunk(action)) {\r\n const { requestId, rejectedWithValue, baseQueryMeta } = action.meta\r\n lifecycleMap[requestId]?.reject({\r\n error: action.payload ?? action.error,\r\n isUnhandledError: !rejectedWithValue,\r\n meta: baseQueryMeta as any,\r\n })\r\n delete lifecycleMap[requestId]\r\n }\r\n\r\n return result\r\n }\r\n }\r\n}\r\n","import type { SubMiddlewareBuilder } from './types'\r\n\r\nexport const build: SubMiddlewareBuilder = ({\r\n api,\r\n context: { apiUid },\r\n reducerPath,\r\n}) => {\r\n return (mwApi) => {\r\n let initialized = false\r\n return (next) => (action) => {\r\n if (!initialized) {\r\n initialized = true\r\n // dispatch before any other action\r\n mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid))\r\n }\r\n\r\n const result = next(action)\r\n\r\n if (api.util.resetApiState.match(action)) {\r\n // dispatch after api reset\r\n mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid))\r\n }\r\n\r\n if (\r\n typeof process !== 'undefined' &&\r\n process.env.NODE_ENV === 'development'\r\n ) {\r\n if (\r\n api.internalActions.middlewareRegistered.match(action) &&\r\n action.payload === apiUid &&\r\n mwApi.getState()[reducerPath]?.config?.middlewareRegistered ===\r\n 'conflict'\r\n ) {\r\n console.warn(`There is a mismatch between slice and middleware for the reducerPath \"${reducerPath}\".\r\nYou can only have one api per reducer path, this will lead to crashes in various situations!${\r\n reducerPath === 'api'\r\n ? `\r\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!`\r\n : ''\r\n }`)\r\n }\r\n }\r\n\r\n return result\r\n }\r\n }\r\n}\r\n","export type Id<T> = { [K in keyof T]: T[K] } & {}\r\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> &\r\n Required<Pick<T, K>>\r\nexport type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never\r\nexport function assertCast<T>(v: any): asserts v is T {}\r\n\r\nexport function safeAssign<T extends object>(\r\n target: T,\r\n ...args: Array<Partial<NoInfer<T>>>\r\n) {\r\n Object.assign(target, ...args)\r\n}\r\n\r\n/**\r\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\r\n */\r\nexport type UnionToIntersection<U> = (\r\n U extends any ? (k: U) => void : never\r\n) extends (k: infer I) => void\r\n ? I\r\n : never\r\n\r\nexport type NonOptionalKeys<T> = {\r\n [K in keyof T]-?: undefined extends T[K] ? never : K\r\n}[keyof T]\r\n\r\nexport type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never\r\n ? False\r\n : True\r\n\r\nexport type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>\r\n\r\nexport type NoInfer<T> = [T][T extends any ? 0 : never]\r\n\r\nexport type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T\r\n\r\nexport type MaybePromise<T> = T | PromiseLike<T>\r\n\r\nexport type OmitFromUnion<T, K extends keyof T> = T extends any\r\n ? Omit<T, K>\r\n : never\r\n\r\nexport type IsAny<T, True, False = never> = true | false extends (\r\n T extends never ? true : false\r\n)\r\n ? True\r\n : False\r\n\r\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>\r\n","/**\r\n * Note: this file should import all other files for type discovery and declaration merging\r\n */\r\nimport type { PatchQueryDataThunk, UpdateQueryDataThunk } from './buildThunks'\r\nimport { buildThunks } from './buildThunks'\r\nimport type {\r\n ActionCreatorWithPayload,\r\n AnyAction,\r\n Middleware,\r\n Reducer,\r\n ThunkAction,\r\n ThunkDispatch,\r\n} from '@reduxjs/toolkit'\r\nimport type {\r\n EndpointDefinitions,\r\n QueryArgFrom,\r\n QueryDefinition,\r\n MutationDefinition,\r\n AssertTagTypes,\r\n TagDescription,\r\n} from '../endpointDefinitions'\r\nimport { isQueryDefinition, isMutationDefinition } from '../endpointDefinitions'\r\nimport type {\r\n CombinedState,\r\n QueryKeys,\r\n MutationKeys,\r\n RootState,\r\n} from './apiState'\r\nimport type { Api, Module } from '../apiTypes'\r\nimport { onFocus, onFocusLost, onOnline, onOffline } from './setupListeners'\r\nimport { buildSlice } from './buildSlice'\r\nimport { buildMiddleware } from './buildMiddleware'\r\nimport { buildSelectors } from './buildSelectors'\r\nimport type {\r\n MutationActionCreatorResult,\r\n QueryActionCreatorResult,\r\n} from './buildInitiate'\r\nimport { buildInitiate } from './buildInitiate'\r\nimport { assertCast, safeAssign } from '../tsHelpers'\r\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'\r\nimport type { SliceActions } from './buildSlice'\r\nimport type { BaseQueryFn } from '../baseQueryTypes'\r\n\r\nimport type { ReferenceCacheLifecycle } from './buildMiddleware/cacheLifecycle'\r\nimport type { ReferenceQueryLifecycle } from './buildMiddleware/queryLifecycle'\r\nimport type { ReferenceCacheCollection } from './buildMiddleware/cacheCollection'\r\nimport { enablePatches } from 'immer'\r\n\r\n/**\r\n * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_\r\n * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value\r\n *\r\n * @overloadSummary\r\n * `force`\r\n * - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.\r\n */\r\nexport type PrefetchOptions =\r\n | {\r\n ifOlderThan?: false | number\r\n }\r\n | { force?: boolean }\r\n\r\nexport const coreModuleName = /* @__PURE__ */ Symbol()\r\nexport type CoreModule =\r\n | typeof coreModuleName\r\n | ReferenceCacheLifecycle\r\n | ReferenceQueryLifecycle\r\n | ReferenceCacheCollection\r\n\r\ndeclare module '../apiTypes' {\r\n export interface ApiModules<\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n BaseQuery extends BaseQueryFn,\r\n Definitions extends EndpointDefinitions,\r\n ReducerPath extends string,\r\n TagTypes extends string\r\n > {\r\n [coreModuleName]: {\r\n /**\r\n * This api's reducer should be mounted at `store[api.reducerPath]`.\r\n *\r\n * @example\r\n * ```ts\r\n * configureStore({\r\n * reducer: {\r\n * [api.reducerPath]: api.reducer,\r\n * },\r\n * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\r\n * })\r\n * ```\r\n */\r\n reducerPath: ReducerPath\r\n /**\r\n * Internal actions not part of the public API. Note: These are subject to change at any given time.\r\n */\r\n internalActions: InternalActions\r\n /**\r\n * A standard redux reducer that enables core functionality. Make sure it's included in your store.\r\n *\r\n * @example\r\n * ```ts\r\n * configureStore({\r\n * reducer: {\r\n * [api.reducerPath]: api.reducer,\r\n * },\r\n * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\r\n * })\r\n * ```\r\n */\r\n reducer: Reducer<\r\n CombinedState<Definitions, TagTypes, ReducerPath>,\r\n AnyAction\r\n >\r\n /**\r\n * This is a standard redux middleware and is responsible for things like polling, garbage collection and a handful of other things. Make sure it's included in your store.\r\n *\r\n * @example\r\n * ```ts\r\n * configureStore({\r\n * reducer: {\r\n * [api.reducerPath]: api.reducer,\r\n * },\r\n * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\r\n * })\r\n * ```\r\n */\r\n middleware: Middleware<\r\n {},\r\n RootState<Definitions, string, ReducerPath>,\r\n ThunkDispatch<any, any, AnyAction>\r\n >\r\n /**\r\n * A collection of utility thunks for various situations.\r\n */\r\n util: {\r\n /**\r\n * Returns all promises for running queries and mutations.\r\n * Useful for SSR scenarios to await everything triggered in any way,\r\n * including via hook calls, or manually dispatching `initiate` actions.\r\n */\r\n getRunningOperationPromises: () => Array<Promise<unknown>>\r\n /**\r\n * If a promise is running for a given endpoint name + argument combination,\r\n * returns that promise. Otherwise, returns `undefined`.\r\n * Can be used to await a specific query/mutation triggered in any way,\r\n * including via hook calls, or manually dispatching `initiate` actions.\r\n */\r\n getRunningOperationPromise<EndpointName extends QueryKeys<Definitions>>(\r\n endpointName: EndpointName,\r\n args: QueryArgFrom<Definitions[EndpointName]>\r\n ):\r\n | QueryActionCreatorResult<\r\n Definitions[EndpointName] & { type: 'query' }\r\n >\r\n | undefined\r\n getRunningOperationPromise<\r\n EndpointName extends MutationKeys<Definitions>\r\n >(\r\n endpointName: EndpointName,\r\n fixedCacheKeyOrRequestId: string\r\n ):\r\n | MutationActionCreatorResult<\r\n Definitions[EndpointName] & { type: 'mutation' }\r\n >\r\n | undefined\r\n\r\n /**\r\n * A Redux thunk that can be used to manually trigger pre-fetching of data.\r\n *\r\n * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), any relevant query arguments, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.\r\n *\r\n * React Hooks users will most likely never need to use this directly, as the `usePrefetch` hook will dispatch this thunk internally as needed when you call the prefetching function supplied by the hook.\r\n *\r\n * @example\r\n *\r\n * ```ts no-transpile\r\n * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))\r\n * ```\r\n */\r\n prefetch<EndpointName extends QueryKeys<Definitions>>(\r\n endpointName: EndpointName,\r\n arg: QueryArgFrom<Definitions[EndpointName]>,\r\n options: PrefetchOptions\r\n ): ThunkAction<void, any, any, AnyAction>\r\n /**\r\n * A Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes.\r\n *\r\n * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), any relevant query arguments, and a callback function. The callback receives an Immer-wrapped `draft` of the current state, and may modify the draft to match the expected results after the mutation completes successfully.\r\n *\r\n * The thunk returns an object containing `{patches: Patch[], inversePatches: Patch[], undo: () => void}`. The `patches` and `inversePatches` are generated using Immer's [`produceWithPatches` method](https://immerjs.github.io/immer/patches).\r\n *\r\n * This is typically used as the first step in implementing optimistic updates. The generated `inversePatches` can be used to revert the updates by calling `dispatch(patchQueryData(endpointName, args, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * const patchCollection = dispatch(\r\n * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\r\n * draftPosts.push({ id: 1, name: 'Teddy' })\r\n * })\r\n * )\r\n * ```\r\n */\r\n updateQueryData: UpdateQueryDataThunk<\r\n Definitions,\r\n RootState<Definitions, string, ReducerPath>\r\n >\r\n /** @deprecated renamed to `updateQueryData` */\r\n updateQueryResult: UpdateQueryDataThunk<\r\n Definitions,\r\n RootState<Definitions, string, ReducerPath>\r\n >\r\n /**\r\n * A Redux thunk that applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.\r\n *\r\n * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), any relevant query arguments, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.\r\n *\r\n * This is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching `patchQueryData` with the `inversePatches` that were generated by `updateQueryData` earlier.\r\n *\r\n * In cases where it is desired to simply revert the previous changes, it may be preferable to call the `undo` method returned from dispatching `updateQueryData` instead.\r\n *\r\n * @example\r\n * ```ts\r\n * const patchCollection = dispatch(\r\n * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\r\n * draftPosts.push({ id: 1, name: 'Teddy' })\r\n * })\r\n * )\r\n *\r\n * // later\r\n * dispatch(\r\n * api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)\r\n * )\r\n *\r\n * // or\r\n * patchCollection.undo()\r\n * ```\r\n */\r\n patchQueryData: PatchQueryDataThunk<\r\n Definitions,\r\n RootState<Definitions, string, ReducerPath>\r\n >\r\n /** @deprecated renamed to `patchQueryData` */\r\n patchQueryResult: PatchQueryDataThunk<\r\n Definitions,\r\n RootState<Definitions, string, ReducerPath>\r\n >\r\n /**\r\n * A Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * dispatch(api.util.resetApiState())\r\n * ```\r\n */\r\n resetApiState: SliceActions['resetApiState']\r\n /**\r\n * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).\r\n *\r\n * The action creator accepts one argument: the cache tags to be invalidated. It returns an action with those tags as a payload, and the corresponding `invalidateTags` action type for the api.\r\n *\r\n * Dispatching the result of this action creator will [invalidate](../../usage/automated-refetching.mdx#invalidating-cache-data) the given tags, causing queries to automatically re-fetch if they are subscribed to cache data that [provides](../../usage/automated-refetching.mdx#providing-cache-data) the corresponding tags.\r\n *\r\n * The array of tags provided to the action creator should be in one of the following formats, where `TagType` is equal to a string provided to the [`tagTypes`](../createApi.mdx#tagtypes) property of the api:\r\n *\r\n * - `[TagType]`\r\n * - `[{ type: TagType }]`\r\n * - `[{ type: TagType, id: number | string }]`\r\n *\r\n * @example\r\n *\r\n * ```ts\r\n * dispatch(api.util.invalidateTags(['Post']))\r\n * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))\r\n * dispatch(\r\n * api.util.invalidateTags([\r\n * { type: 'Post', id: 1 },\r\n * { type: 'Post', id: 'LIST' },\r\n * ])\r\n * )\r\n * ```\r\n */\r\n invalidateTags: ActionCreatorWithPayload<\r\n Array<TagDescription<TagTypes>>,\r\n string\r\n >\r\n\r\n selectInvalidatedBy: (\r\n state: RootState<Definitions, string, ReducerPath>,\r\n tags: ReadonlyArray<TagDescription<TagTypes>>\r\n ) => Array<{\r\n endpointName: string\r\n originalArgs: any\r\n queryCacheKey: string\r\n }>\r\n }\r\n /**\r\n * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.\r\n */\r\n endpoints: {\r\n [K in keyof Definitions]: Definitions[K] extends QueryDefinition<\r\n any,\r\n any,\r\n any,\r\n any,\r\n any\r\n >\r\n ? ApiEndpointQuery<Definitions[K], Definitions>\r\n : Definitions[K] extends MutationDefinition<any, any, any, any, any>\r\n ? ApiEndpointMutation<Definitions[K], Definitions>\r\n : never\r\n }\r\n }\r\n }\r\n}\r\n\r\nexport interface ApiEndpointQuery<\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definition extends QueryDefinition<any, any, any, any, any>,\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definitions extends EndpointDefinitions\r\n> {}\r\n\r\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\r\nexport interface ApiEndpointMutation<\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definition extends MutationDefinition<any, any, any, any, any>,\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definitions extends EndpointDefinitions\r\n> {}\r\n\r\nexport type ListenerActions = {\r\n /**\r\n * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior\r\n * @link https://rtk-query-docs.netlify.app/api/setupListeners\r\n */\r\n onOnline: typeof onOnline\r\n onOffline: typeof onOffline\r\n /**\r\n * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior\r\n * @link https://rtk-query-docs.netlify.app/api/setupListeners\r\n */\r\n onFocus: typeof onFocus\r\n onFocusLost: typeof onFocusLost\r\n}\r\n\r\nexport type InternalActions = SliceActions & ListenerActions\r\n\r\n/**\r\n * Creates a module containing the basic redux logic for use with `buildCreateApi`.\r\n *\r\n * @example\r\n * ```ts\r\n * const createBaseApi = buildCreateApi(coreModule());\r\n * ```\r\n */\r\nexport const coreModule = (): Module<CoreModule> => ({\r\n name: coreModuleName,\r\n init(\r\n api,\r\n {\r\n baseQuery,\r\n tagTypes,\r\n reducerPath,\r\n serializeQueryArgs,\r\n keepUnusedDataFor,\r\n refetchOnMountOrArgChange,\r\n refetchOnFocus,\r\n refetchOnReconnect,\r\n },\r\n context\r\n ) {\r\n enablePatches()\r\n\r\n assertCast<InternalSerializeQueryArgs>(serializeQueryArgs)\r\n\r\n const assertTagType: AssertTagTypes = (tag) => {\r\n if (\r\n typeof process !== 'undefined' &&\r\n process.env.NODE_ENV === 'development'\r\n ) {\r\n if (!tagTypes.includes(tag.type as any)) {\r\n console.error(\r\n `Tag type '${tag.type}' was used, but not specified in \\`tagTypes\\`!`\r\n )\r\n }\r\n }\r\n return tag\r\n }\r\n\r\n Object.assign(api, {\r\n reducerPath,\r\n endpoints: {},\r\n internalActions: {\r\n onOnline,\r\n onOffline,\r\n onFocus,\r\n onFocusLost,\r\n },\r\n util: {},\r\n })\r\n\r\n const {\r\n queryThunk,\r\n mutationThunk,\r\n patchQueryData,\r\n updateQueryData,\r\n prefetch,\r\n buildMatchThunkActions,\r\n } = buildThunks({\r\n baseQuery,\r\n reducerPath,\r\n context,\r\n api,\r\n serializeQueryArgs,\r\n })\r\n\r\n const { reducer, actions: sliceActions } = buildSlice({\r\n context,\r\n queryThunk,\r\n mutationThunk,\r\n reducerPath,\r\n assertTagType,\r\n config: {\r\n refetchOnFocus,\r\n refetchOnReconnect,\r\n refetchOnMountOrArgChange,\r\n keepUnusedDataFor,\r\n reducerPath,\r\n },\r\n })\r\n\r\n safeAssign(api.util, {\r\n patchQueryData,\r\n updateQueryData,\r\n prefetch,\r\n resetApiState: sliceActions.resetApiState,\r\n })\r\n safeAssign(api.internalActions, sliceActions)\r\n\r\n // remove in final release\r\n Object.defineProperty(api.util, 'updateQueryResult', {\r\n get() {\r\n if (\r\n typeof process !== 'undefined' &&\r\n process.env.NODE_ENV === 'development'\r\n ) {\r\n console.warn(\r\n '`api.util.updateQueryResult` has been renamed to `api.util.updateQueryData`, please change your code accordingly'\r\n )\r\n }\r\n return api.util.updateQueryData\r\n },\r\n })\r\n // remove in final release\r\n Object.defineProperty(api.util, 'patchQueryResult', {\r\n get() {\r\n if (\r\n typeof process !== 'undefined' &&\r\n process.env.NODE_ENV === 'development'\r\n ) {\r\n console.warn(\r\n '`api.util.patchQueryResult` has been renamed to `api.util.patchQueryData`, please change your code accordingly'\r\n )\r\n }\r\n return api.util.patchQueryData\r\n },\r\n })\r\n\r\n const { middleware, actions: middlewareActions } = buildMiddleware({\r\n reducerPath,\r\n context,\r\n queryThunk,\r\n mutationThunk,\r\n api,\r\n assertTagType,\r\n })\r\n safeAssign(api.util, middlewareActions)\r\n\r\n safeAssign(api, { reducer: reducer as any, middleware })\r\n\r\n const { buildQuerySelector, buildMutationSelector, selectInvalidatedBy } =\r\n buildSelectors({\r\n serializeQueryArgs: serializeQueryArgs as any,\r\n reducerPath,\r\n })\r\n\r\n safeAssign(api.util, { selectInvalidatedBy })\r\n\r\n const {\r\n buildInitiateQuery,\r\n buildInitiateMutation,\r\n getRunningOperationPromises,\r\n getRunningOperationPromise,\r\n } = buildInitiate({\r\n queryThunk,\r\n mutationThunk,\r\n api,\r\n serializeQueryArgs: serializeQueryArgs as any,\r\n context,\r\n })\r\n\r\n safeAssign(api.util, {\r\n getRunningOperationPromises,\r\n getRunningOperationPromise,\r\n })\r\n\r\n return {\r\n name: coreModuleName,\r\n injectEndpoint(endpointName, definition) {\r\n const anyApi = api as any as Api<\r\n any,\r\n Record<string, any>,\r\n string,\r\n string,\r\n CoreModule\r\n >\r\n anyApi.endpoints[endpointName] ??= {} as any\r\n if (isQueryDefinition(definition)) {\r\n safeAssign(\r\n anyApi.endpoints[endpointName],\r\n {\r\n select: buildQuerySelector(endpointName, definition),\r\n initiate: buildInitiateQuery(endpointName, definition),\r\n },\r\n buildMatchThunkActions(queryThunk, endpointName)\r\n )\r\n } else if (isMutationDefinition(definition)) {\r\n safeAssign(\r\n anyApi.endpoints[endpointName],\r\n {\r\n select: buildMutationSelector(),\r\n initiate: buildInitiateMutation(endpointName),\r\n },\r\n buildMatchThunkActions(mutationThunk, endpointName)\r\n )\r\n }\r\n },\r\n }\r\n },\r\n})\r\n","/**\r\n * Assumes a browser is online if `undefined`, otherwise makes a best effort\r\n * @link https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine\r\n */\r\nexport function isOnline() {\r\n // We set the default config value in the store, so we'd need to check for this in a SSR env\r\n return typeof navigator === 'undefined'\r\n ? true\r\n : navigator.onLine === undefined\r\n ? true\r\n : navigator.onLine\r\n}\r\n","/**\r\n * Assumes true for a non-browser env, otherwise makes a best effort\r\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState\r\n */\r\nexport function isDocumentVisible(): boolean {\r\n // `document` may not exist in non-browser envs (like RN)\r\n if (typeof document === 'undefined') {\r\n return true\r\n }\r\n // Match true for visible, prerender, undefined\r\n return document.visibilityState !== 'hidden'\r\n}\r\n","import type {\r\n EndpointDefinitions,\r\n QueryDefinition,\r\n MutationDefinition,\r\n QueryArgFrom,\r\n ResultTypeFrom,\r\n} from '../endpointDefinitions'\r\nimport { DefinitionType } from '../endpointDefinitions'\r\nimport type { QueryThunk, MutationThunk } from './buildThunks'\r\nimport type { AnyAction, ThunkAction, SerializedError } from '@reduxjs/toolkit'\r\nimport type { SubscriptionOptions, RootState } from './apiState'\r\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'\r\nimport type { Api, ApiContext } from '../apiTypes'\r\nimport type { ApiEndpointQuery } from './module'\r\nimport type { BaseQueryError } from '../baseQueryTypes'\r\nimport type { QueryResultSelectorResult } from './buildSelectors'\r\n\r\ndeclare module './module' {\r\n export interface ApiEndpointQuery<\r\n Definition extends QueryDefinition<any, any, any, any, any>,\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definitions extends EndpointDefinitions\r\n > {\r\n initiate: StartQueryActionCreator<Definition>\r\n }\r\n\r\n export interface ApiEndpointMutation<\r\n Definition extends MutationDefinition<any, any, any, any, any>,\r\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\r\n Definitions extends EndpointDefinitions\r\n > {\r\n initiate: StartMutationActionCreator<Definition>\r\n }\r\n}\r\n\r\nexport interface StartQueryActionCreatorOptions {\r\n subscribe?: boolean\r\n forceRefetch?: boolean | number\r\n subscriptionOptions?: SubscriptionOptions\r\n}\r\n\r\ntype StartQueryActionCreator<\r\n D extends QueryDefinition<any, any, any, any, any>\r\n> = (\r\n arg: QueryArgFrom<D>,\r\n options?: StartQueryActionCreatorOptions\r\n) => ThunkAction<QueryActionCreatorResult<D>, any, any, AnyAction>\r\n\r\nexport type QueryActionCreatorResult<\r\n D extends QueryDefinition<any, any, any, any>\r\n> = Promise<QueryResultSelectorResult<D>> & {\r\n arg: QueryArgFrom<D>\r\n requestId: string\r\n subscriptionOptions: SubscriptionOptions | undefined\r\n abort(): void\r\n unwrap(): Promise<ResultTypeFrom<D>>\r\n unsubscribe(): void\r\n refetch(): void\r\n updateSubscriptionOptions(options: SubscriptionOptions): void\r\n queryCacheKey: string\r\n}\r\n\r\ntype StartMutationActionCreator<\r\n D extends MutationDefinition<any, any, any, any>\r\n> = (\r\n arg: QueryArgFrom<D>,\r\n options?: {\r\n /**\r\n * If this mutation should be tracked in the store.\r\n * If you just want to manually trigger this mutation using `dispatch` and don't care about the\r\n * result, state & potential errors being held in store, you can set this to false.\r\n * (defaults to `true`)\r\n */\r\n track?: boolean\r\n fixedCacheKey?: string\r\n }\r\n) => ThunkAction<MutationActionCreatorResult<D>, any, any, AnyAction>\r\n\r\nexport type MutationActionCreatorResult<\r\n D extends MutationDefinition<any, any, any, any>\r\n> = Promise<\r\n | { data: ResultTypeFrom<D> }\r\n | {\r\n error:\r\n | Exclude<\r\n BaseQueryError<\r\n D extends MutationDefinition<any, infer BaseQuery, any, any>\r\n ? BaseQuery\r\n : never\r\n >,\r\n undefined\r\n >\r\n | SerializedError\r\n }\r\n> & {\r\n /** @internal */\r\n arg: {\r\n /**\r\n * The name of the given endpoint for the mutation\r\n */\r\n endpointName: string\r\n /**\r\n * The original arguments supplied to the mutation call\r\n */\r\n originalArgs: QueryArgFrom<D>\r\n /**\r\n * Whether the mutation is being tracked in the store.\r\n */\r\n track?: boolean\r\n fixedCacheKey?: string\r\n }\r\n /**\r\n * A unique string generated for the request sequence\r\n */\r\n requestId: string\r\n\r\n /**\r\n * A method to cancel the mutation promise. Note that this is not intended to prevent the mutation\r\n * that was fired off from reaching the server, but only to assist in handling the response.\r\n *\r\n * Calling `abort()` prior to the promise resolving will force it to reach the error state with\r\n * the serialized error:\r\n * `{ name: 'AbortError', message: 'Aborted' }`\r\n *\r\n * @example\r\n * ```ts\r\n * const [updateUser] = useUpdateUserMutation();\r\n *\r\n * useEffect(() => {\r\n * const promise = updateUser(id);\r\n * promise\r\n * .unwrap()\r\n * .catch((err) => {\r\n * if (err.name === 'AbortError') return;\r\n * // else handle the unexpected error\r\n * })\r\n *\r\n * return () => {\r\n * promise.abort();\r\n * }\r\n * }, [id, updateUser])\r\n * ```\r\n */\r\n abort(): void\r\n /**\r\n * Unwraps a mutation call to provide the raw response/error.\r\n *\r\n * @remarks\r\n * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\r\n *\r\n * @example\r\n * ```ts\r\n * // codeblock-meta title=\"Using .unwrap\"\r\n * addPost({ id: 1, name: 'Example' })\r\n * .unwrap()\r\n * .then((payload) => console.log('fulfilled', payload))\r\n * .catch((error) => console.error('rejected', error));\r\n * ```\r\n *\r\n * @example\r\n * ```ts\r\n * // codeblock-meta title=\"Using .unwrap with async await\"\r\n * try {\r\n * const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\r\n * console.log('fulfilled', payload)\r\n * } catch (error) {\r\n * console.error('rejected', error);\r\n * }\r\n * ```\r\n */\r\n unwrap(): Promise<ResultTypeFrom<D>>\r\n /**\r\n * A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.\r\n The value returned by the hook will reset to `isUninitialized` afterwards.\r\n */\r\n reset(): void\r\n /** @deprecated has been renamed to `reset` */\r\n unsubscribe(): void\r\n}\r\n\r\nexport function buildInitiate({\r\n serializeQueryArgs,\r\n queryThunk,\r\n mutationThunk,\r\n api,\r\n context,\r\n}: {\r\n serializeQueryArgs: InternalSerializeQueryArgs\r\n queryThunk: QueryThunk\r\n mutationThunk: MutationThunk\r\n api: Api<any, EndpointDefinitions, any, any>\r\n context: ApiContext<EndpointDefinitions>\r\n}) {\r\n const runningQueries: Record<\r\n string,\r\n QueryActionCreatorResult<any> | undefined\r\n > = {}\r\n const runningMutations: Record<\r\n string,\r\n MutationActionCreatorResult<any> | undefined\r\n > = {}\r\n\r\n const {\r\n unsubscribeQueryResult,\r\n removeMutationResult,\r\n updateSubscriptionOptions,\r\n } = api.internalActions\r\n return {\r\n buildInitiateQuery,\r\n buildInitiateMutation,\r\n getRunningOperationPromises,\r\n getRunningOperationPromise,\r\n }\r\n\r\n function getRunningOperationPromise(\r\n endpointName: string,\r\n argOrRequestId: any\r\n ): any {\r\n const endpointDefinition = context.endpointDefinitions[endpointName]\r\n if (endpointDefinition.type === DefinitionType.query) {\r\n const queryCacheKey = serializeQueryArgs({\r\n queryArgs: argOrRequestId,\r\n endpointDefinition,\r\n endpointName,\r\n })\r\n return runningQueries[queryCacheKey]\r\n } else {\r\n return runningMutations[argOrRequestId]\r\n }\r\n }\r\n\r\n function getRunningOperationPromises() {\r\n return [\r\n ...Object.values(runningQueries),\r\n ...Object.values(runningMutations),\r\n ].filter(<T>(t: T | undefined): t is T => !!t)\r\n }\r\n\r\n function middlewareWarning(getState: () => RootState<{}, string, string>) {\r\n if (process.env.NODE_ENV !== 'production') {\r\n if ((middlewareWarning as any).triggered) return\r\n const registered =\r\n getState()[api.reducerPath]?.config?.middlewareRegistered\r\n if (registered !== undefined) {\r\n ;(middlewareWarning as any).triggered = true\r\n }\r\n if (registered === false) {\r\n console.warn(\r\n `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\r\nFeatures like automatic cache collection, automatic refetching etc. will not be available.`\r\n )\r\n }\r\n }\r\n }\r\n\r\n function buildInitiateQuery(\r\n endpointName: string,\r\n endpointDefinition: QueryDefinition<any, any, any, any>\r\n ) {\r\n const queryAction: StartQueryActionCreator<any> =\r\n (arg, { subscribe = true, forceRefetch, subscriptionOptions } = {}) =>\r\n (dispatch, getState) => {\r\n const queryCacheKey = serializeQueryArgs({\r\n queryArgs: arg,\r\n endpointDefinition,\r\n endpointName,\r\n })\r\n const thunk = queryThunk({\r\n type: 'query',\r\n subscribe,\r\n forceRefetch,\r\n subscriptionOptions,\r\n endpointName,\r\n originalArgs: arg,\r\n queryCacheKey,\r\n })\r\n const thunkResult = dispatch(thunk)\r\n middlewareWarning(getState)\r\n\r\n const { requestId, abort } = thunkResult\r\n\r\n const statePromise: QueryActionCreatorResult<any> = Object.assign(\r\n Promise.all([runningQueries[queryCacheKey], thunkResult]).then(() =>\r\n (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(\r\n arg\r\n )(getState())\r\n ),\r\n {\r\n arg,\r\n requestId,\r\n subscriptionOptions,\r\n queryCacheKey,\r\n abort,\r\n async unwrap() {\r\n const result = await statePromise\r\n\r\n if (result.isError) {\r\n throw result.error\r\n }\r\n\r\n return result.data\r\n },\r\n refetch() {\r\n dispatch(\r\n queryAction(arg, { subscribe: false, forceRefetch: true })\r\n )\r\n },\r\n unsubscribe() {\r\n if (subscribe)\r\n dispatch(\r\n unsubscribeQueryResult({\r\n queryCacheKey,\r\n requestId,\r\n })\r\n )\r\n },\r\n updateSubscriptionOptions(options: SubscriptionOptions) {\r\n statePromise.subscriptionOptions = options\r\n dispatch(\r\n updateSubscriptionOptions({\r\n endpointName,\r\n requestId,\r\n queryCacheKey,\r\n options,\r\n })\r\n )\r\n },\r\n }\r\n )\r\n\r\n if (!runningQueries[queryCacheKey]) {\r\n runningQueries[queryCacheKey] = statePromise\r\n statePromise.then(() => {\r\n delete runningQueries[queryCacheKey]\r\n })\r\n }\r\n\r\n return statePromise\r\n }\r\n return queryAction\r\n }\r\n\r\n function buildInitiateMutation(\r\n endpointName: string\r\n ): StartMutationActionCreator<any> {\r\n return (arg, { track = true, fixedCacheKey } = {}) =>\r\n (dispatch, getState) => {\r\n const thunk = mutationThunk({\r\n type: 'mutation',\r\n endpointName,\r\n originalArgs: arg,\r\n track,\r\n fixedCacheKey,\r\n })\r\n const thunkResult = dispatch(thunk)\r\n middlewareWarning(getState)\r\n const { requestId, abort, unwrap } = thunkResult\r\n const returnValuePromise = thunkResult\r\n .unwrap()\r\n .then((data) => ({ data }))\r\n .catch((error) => ({ error }))\r\n\r\n const reset = () => {\r\n dispatch(removeMutationResult({ requestId, fixedCacheKey }))\r\n }\r\n\r\n const ret = Object.assign(returnValuePromise, {\r\n arg: thunkResult.arg,\r\n requestId,\r\n abort,\r\n unwrap,\r\n unsubscribe: reset,\r\n reset,\r\n })\r\n\r\n runningMutations[requestId] = ret\r\n ret.then(() => {\r\n delete runningMutations[requestId]\r\n })\r\n if (fixedCacheKey) {\r\n runningMutations[fixedCacheKey] = ret\r\n ret.then(() => {\r\n if (runningMutations[fixedCacheKey] === ret)\r\n delete runningMutations[fixedCacheKey]\r\n })\r\n }\r\n\r\n return ret\r\n }\r\n }\r\n}\r\n","import { buildCreateApi, CreateApi } from '../createApi'\r\nimport { coreModule, coreModuleName } from './module'\r\n\r\nconst createApi = /* @__PURE__ */ buildCreateApi(coreModule())\r\n\r\nexport { createApi, coreModule }\r\n"]}