knowledgebase_law/node_modules/@reduxjs/toolkit/dist/query/rtk-query.browser.mjs.map
2025-04-11 11:47:09 -04:00

1 line
306 KiB
Plaintext

{"version":3,"sources":["../../src/query/core/apiState.ts","../../src/query/core/rtkImports.ts","../../src/query/utils/copyWithStructuralSharing.ts","../../src/query/utils/countObjectKeys.ts","../../src/query/utils/flatten.ts","../../src/query/utils/isAbsoluteUrl.ts","../../src/query/utils/isDocumentVisible.ts","../../src/query/utils/isNotNullish.ts","../../src/query/utils/isOnline.ts","../../src/query/utils/joinUrls.ts","../../src/query/utils/getOrInsert.ts","../../src/query/fetchBaseQuery.ts","../../src/query/HandledError.ts","../../src/query/retry.ts","../../src/query/core/setupListeners.ts","../../src/query/endpointDefinitions.ts","../../src/query/core/buildThunks.ts","../../src/query/core/buildInitiate.ts","../../src/tsHelpers.ts","../../src/query/core/buildSlice.ts","../../src/query/core/buildSelectors.ts","../../src/query/createApi.ts","../../src/query/defaultSerializeQueryArgs.ts","../../src/query/fakeBaseQuery.ts","../../src/query/core/module.ts","../../src/query/tsHelpers.ts","../../src/query/core/buildMiddleware/batchActions.ts","../../src/query/core/buildMiddleware/cacheCollection.ts","../../src/query/core/buildMiddleware/cacheLifecycle.ts","../../src/query/core/buildMiddleware/devMiddleware.ts","../../src/query/core/buildMiddleware/invalidationByTags.ts","../../src/query/core/buildMiddleware/polling.ts","../../src/query/core/buildMiddleware/queryLifecycle.ts","../../src/query/core/buildMiddleware/windowEventHandling.ts","../../src/query/core/buildMiddleware/index.ts","../../src/query/core/index.ts"],"sourcesContent":["import type { SerializedError } from '@reduxjs/toolkit';\nimport type { BaseQueryError } from '../baseQueryTypes';\nimport type { BaseEndpointDefinition, EndpointDefinitions, InfiniteQueryDefinition, MutationDefinition, PageParamFrom, QueryArgFrom, QueryDefinition, ResultTypeFrom } from '../endpointDefinitions';\nimport type { Id, WithRequiredProp } from '../tsHelpers';\nexport type QueryCacheKey = string & {\n _type: 'queryCacheKey';\n};\nexport type QuerySubstateIdentifier = {\n queryCacheKey: QueryCacheKey;\n};\nexport type MutationSubstateIdentifier = {\n requestId: string;\n fixedCacheKey?: string;\n} | {\n requestId?: string;\n fixedCacheKey: string;\n};\nexport type RefetchConfigOptions = {\n refetchOnMountOrArgChange: boolean | number;\n refetchOnReconnect: boolean;\n refetchOnFocus: boolean;\n};\nexport type PageParamFunction<DataType, PageParam> = (firstPage: DataType, allPages: Array<DataType>, firstPageParam: PageParam, allPageParams: Array<PageParam>) => PageParam | undefined | null;\nexport type InfiniteQueryConfigOptions<DataType, PageParam> = {\n /**\n * The initial page parameter to use for the first page fetch.\n */\n initialPageParam: PageParam;\n /**\n * This function is required to automatically get the next cursor for infinite queries.\n * The result will also be used to determine the value of `hasNextPage`.\n */\n getNextPageParam: PageParamFunction<DataType, PageParam>;\n /**\n * This function can be set to automatically get the previous cursor for infinite queries.\n * The result will also be used to determine the value of `hasPreviousPage`.\n */\n getPreviousPageParam?: PageParamFunction<DataType, PageParam>;\n /**\n * If specified, only keep this many pages in cache at once.\n * If additional pages are fetched, older pages in the other\n * direction will be dropped from the cache.\n */\n maxPages?: number;\n};\nexport interface InfiniteData<DataType, PageParam> {\n pages: Array<DataType>;\n pageParams: Array<PageParam>;\n}\n\n/**\n * Strings describing the query state at any given time.\n */\nexport enum QueryStatus {\n uninitialized = 'uninitialized',\n pending = 'pending',\n fulfilled = 'fulfilled',\n rejected = 'rejected',\n}\nexport type RequestStatusFlags = {\n status: QueryStatus.uninitialized;\n isUninitialized: true;\n isLoading: false;\n isSuccess: false;\n isError: false;\n} | {\n status: QueryStatus.pending;\n isUninitialized: false;\n isLoading: true;\n isSuccess: false;\n isError: false;\n} | {\n status: QueryStatus.fulfilled;\n isUninitialized: false;\n isLoading: false;\n isSuccess: true;\n isError: false;\n} | {\n status: QueryStatus.rejected;\n isUninitialized: false;\n isLoading: false;\n isSuccess: false;\n isError: true;\n};\nexport function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags {\n return {\n status,\n isUninitialized: status === QueryStatus.uninitialized,\n isLoading: status === QueryStatus.pending,\n isSuccess: status === QueryStatus.fulfilled,\n isError: status === QueryStatus.rejected\n } as any;\n}\n\n/**\n * @public\n */\nexport type SubscriptionOptions = {\n /**\n * How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).\n */\n pollingInterval?: number;\n /**\n * Defaults to 'false'. This setting allows you to control whether RTK Query will continue polling if the window is not focused.\n *\n * If pollingInterval is not set or set to 0, this **will not be evaluated** until pollingInterval is greater than 0.\n *\n * Note: requires [`setupListeners`](./setupListeners) to have been called.\n */\n skipPollingIfUnfocused?: boolean;\n /**\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.\n *\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n *\n * Note: requires [`setupListeners`](./setupListeners) to have been called.\n */\n refetchOnReconnect?: boolean;\n /**\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.\n *\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n *\n * Note: requires [`setupListeners`](./setupListeners) to have been called.\n */\n refetchOnFocus?: boolean;\n};\nexport type Subscribers = {\n [requestId: string]: SubscriptionOptions;\n};\nexport type QueryKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any> ? K : never }[keyof Definitions];\nexport type InfiniteQueryKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? K : never }[keyof Definitions];\nexport type MutationKeys<Definitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends MutationDefinition<any, any, any, any> ? K : never }[keyof Definitions];\ntype BaseQuerySubState<D extends BaseEndpointDefinition<any, any, any>, DataType = ResultTypeFrom<D>> = {\n /**\n * The argument originally passed into the hook or `initiate` action call\n */\n originalArgs: QueryArgFrom<D>;\n /**\n * A unique ID associated with the request\n */\n requestId: string;\n /**\n * The received data from the query\n */\n data?: DataType;\n /**\n * The received error if applicable\n */\n error?: SerializedError | (D extends QueryDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);\n /**\n * The name of the endpoint associated with the query\n */\n endpointName: string;\n /**\n * Time that the latest query started\n */\n startedTimeStamp: number;\n /**\n * Time that the latest query was fulfilled\n */\n fulfilledTimeStamp?: number;\n};\nexport type QuerySubState<D extends BaseEndpointDefinition<any, any, any>, DataType = ResultTypeFrom<D>> = Id<({\n status: QueryStatus.fulfilled;\n} & WithRequiredProp<BaseQuerySubState<D, DataType>, 'data' | 'fulfilledTimeStamp'> & {\n error: undefined;\n}) | ({\n status: QueryStatus.pending;\n} & BaseQuerySubState<D, DataType>) | ({\n status: QueryStatus.rejected;\n} & WithRequiredProp<BaseQuerySubState<D, DataType>, 'error'>) | {\n status: QueryStatus.uninitialized;\n originalArgs?: undefined;\n data?: undefined;\n error?: undefined;\n requestId?: undefined;\n endpointName?: string;\n startedTimeStamp?: undefined;\n fulfilledTimeStamp?: undefined;\n}>;\nexport type InfiniteQueryDirection = 'forward' | 'backward';\nexport type InfiniteQuerySubState<D extends BaseEndpointDefinition<any, any, any>> = D extends InfiniteQueryDefinition<any, any, any, any, any> ? QuerySubState<D, InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>> & {\n direction?: InfiniteQueryDirection;\n} : never;\ntype BaseMutationSubState<D extends BaseEndpointDefinition<any, any, any>> = {\n requestId: string;\n data?: ResultTypeFrom<D>;\n error?: SerializedError | (D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);\n endpointName: string;\n startedTimeStamp: number;\n fulfilledTimeStamp?: number;\n};\nexport type MutationSubState<D extends BaseEndpointDefinition<any, any, any>> = (({\n status: QueryStatus.fulfilled;\n} & WithRequiredProp<BaseMutationSubState<D>, 'data' | 'fulfilledTimeStamp'>) & {\n error: undefined;\n}) | (({\n status: QueryStatus.pending;\n} & BaseMutationSubState<D>) & {\n data?: undefined;\n}) | ({\n status: QueryStatus.rejected;\n} & WithRequiredProp<BaseMutationSubState<D>, 'error'>) | {\n requestId?: undefined;\n status: QueryStatus.uninitialized;\n data?: undefined;\n error?: undefined;\n endpointName?: string;\n startedTimeStamp?: undefined;\n fulfilledTimeStamp?: undefined;\n};\nexport type CombinedState<D extends EndpointDefinitions, E extends string, ReducerPath extends string> = {\n queries: QueryState<D>;\n mutations: MutationState<D>;\n provided: InvalidationState<E>;\n subscriptions: SubscriptionState;\n config: ConfigState<ReducerPath>;\n};\nexport type InvalidationState<TagTypes extends string> = { [_ in TagTypes]: {\n [id: string]: Array<QueryCacheKey>;\n [id: number]: Array<QueryCacheKey>;\n} };\nexport type QueryState<D extends EndpointDefinitions> = {\n [queryCacheKey: string]: QuerySubState<D[string]> | InfiniteQuerySubState<D[string]> | undefined;\n};\nexport type SubscriptionState = {\n [queryCacheKey: string]: Subscribers | undefined;\n};\nexport type ConfigState<ReducerPath> = RefetchConfigOptions & {\n reducerPath: ReducerPath;\n online: boolean;\n focused: boolean;\n middlewareRegistered: boolean | 'conflict';\n} & ModifiableConfigState;\nexport type ModifiableConfigState = {\n keepUnusedDataFor: number;\n invalidationBehavior: 'delayed' | 'immediately';\n} & RefetchConfigOptions;\nexport type MutationState<D extends EndpointDefinitions> = {\n [requestId: string]: MutationSubState<D[string]> | undefined;\n};\nexport type RootState<Definitions extends EndpointDefinitions, TagTypes extends string, ReducerPath extends string> = { [P in ReducerPath]: CombinedState<Definitions, TagTypes, P> };","// This file exists to consolidate all of the imports from the `@reduxjs/toolkit` package.\n// ESBuild does not de-duplicate imports, so this file is used to ensure that each method\n// imported is only listed once, and there's only one mention of the `@reduxjs/toolkit` package.\n\nexport { createAction, createSlice, createSelector, createAsyncThunk, combineReducers, createNextState, isAnyOf, isAllOf, isAction, isPending, isRejected, isFulfilled, isRejectedWithValue, isAsyncThunkAction, prepareAutoBatched, SHOULD_AUTOBATCH, isPlainObject, nanoid } from '@reduxjs/toolkit';","import { isPlainObject as _iPO } from '../core/rtkImports';\n\n// remove type guard\nconst isPlainObject: (_: any) => boolean = _iPO;\nexport function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T;\nexport function copyWithStructuralSharing(oldObj: any, newObj: any): any {\n if (oldObj === newObj || !(isPlainObject(oldObj) && isPlainObject(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {\n return newObj;\n }\n const newKeys = Object.keys(newObj);\n const oldKeys = Object.keys(oldObj);\n let isSameObject = newKeys.length === oldKeys.length;\n const mergeObj: any = Array.isArray(newObj) ? [] : {};\n for (const key of newKeys) {\n mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);\n if (isSameObject) isSameObject = oldObj[key] === mergeObj[key];\n }\n return isSameObject ? oldObj : mergeObj;\n}","// Fast method for counting an object's keys\n// without resorting to `Object.keys(obj).length\n// Will this make a big difference in perf? Probably not\n// But we can save a few allocations.\n\nexport function countObjectKeys(obj: Record<any, any>) {\n let count = 0;\n for (const _key in obj) {\n count++;\n }\n return count;\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 */\nexport const flatten = (arr: readonly any[]) => [].concat(...arr);","/**\r\n * If either :// or // is present consider it to be an absolute url\r\n *\r\n * @param url string\r\n */\n\nexport function isAbsoluteUrl(url: string) {\n return new RegExp(`(^|:)//`).test(url);\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 */\nexport function isDocumentVisible(): boolean {\n // `document` may not exist in non-browser envs (like RN)\n if (typeof document === 'undefined') {\n return true;\n }\n // Match true for visible, prerender, undefined\n return document.visibilityState !== 'hidden';\n}","export function isNotNullish<T>(v: T | null | undefined): v is T {\n return v != null;\n}","/**\n * Assumes a browser is online if `undefined`, otherwise makes a best effort\n * @link https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine\n */\nexport function isOnline() {\n // We set the default config value in the store, so we'd need to check for this in a SSR env\n return typeof navigator === 'undefined' ? true : navigator.onLine === undefined ? true : navigator.onLine;\n}","import { isAbsoluteUrl } from './isAbsoluteUrl';\nconst withoutTrailingSlash = (url: string) => url.replace(/\\/$/, '');\nconst withoutLeadingSlash = (url: string) => url.replace(/^\\//, '');\nexport function joinUrls(base: string | undefined, url: string | undefined): string {\n if (!base) {\n return url!;\n }\n if (!url) {\n return base;\n }\n if (isAbsoluteUrl(url)) {\n return url;\n }\n const delimiter = base.endsWith('/') || !url.startsWith('?') ? '/' : '';\n base = withoutTrailingSlash(base);\n url = withoutLeadingSlash(url);\n return `${base}${delimiter}${url}`;\n}","export function getOrInsert<K extends object, V>(map: WeakMap<K, V>, key: K, value: V): V;\nexport function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V;\nexport function getOrInsert<K extends object, V>(map: Map<K, V> | WeakMap<K, V>, key: K, value: V): V {\n if (map.has(key)) return map.get(key) as V;\n return map.set(key, value).get(key) as V;\n}","import { joinUrls } from './utils';\nimport { isPlainObject } from './core/rtkImports';\nimport type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes';\nimport type { MaybePromise, Override } from './tsHelpers';\nexport type ResponseHandler = 'content-type' | 'json' | 'text' | ((response: Response) => Promise<any>);\ntype CustomRequestInit = Override<RequestInit, {\n headers?: Headers | string[][] | Record<string, string | undefined> | undefined;\n}>;\nexport interface FetchArgs extends CustomRequestInit {\n url: string;\n params?: Record<string, any>;\n body?: any;\n responseHandler?: ResponseHandler;\n validateStatus?: (response: Response, body: any) => boolean;\n /**\n * A number in milliseconds that represents that maximum time a request can take before timing out.\n */\n timeout?: number;\n}\n\n/**\n * A mini-wrapper that passes arguments straight through to\n * {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.\n * Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.\n */\nconst defaultFetchFn: typeof fetch = (...args) => fetch(...args);\nconst defaultValidateStatus = (response: Response) => response.status >= 200 && response.status <= 299;\nconst defaultIsJsonContentType = (headers: Headers) => /*applicat*//ion\\/(vnd\\.api\\+)?json/.test(headers.get('content-type') || '');\nexport type FetchBaseQueryError = {\n /**\n * * `number`:\n * HTTP status code\n */\n status: number;\n data: unknown;\n} | {\n /**\n * * `\"FETCH_ERROR\"`:\n * An error that occurred during execution of `fetch` or the `fetchFn` callback option\n **/\n status: 'FETCH_ERROR';\n data?: undefined;\n error: string;\n} | {\n /**\n * * `\"PARSING_ERROR\"`:\n * An error happened during parsing.\n * Most likely a non-JSON-response was returned with the default `responseHandler` \"JSON\",\n * or an error occurred while executing a custom `responseHandler`.\n **/\n status: 'PARSING_ERROR';\n originalStatus: number;\n data: string;\n error: string;\n} | {\n /**\n * * `\"TIMEOUT_ERROR\"`:\n * Request timed out\n **/\n status: 'TIMEOUT_ERROR';\n data?: undefined;\n error: string;\n} | {\n /**\n * * `\"CUSTOM_ERROR\"`:\n * A custom error type that you can return from your `queryFn` where another error might not make sense.\n **/\n status: 'CUSTOM_ERROR';\n data?: unknown;\n error: string;\n};\nfunction stripUndefined(obj: any) {\n if (!isPlainObject(obj)) {\n return obj;\n }\n const copy: Record<string, any> = {\n ...obj\n };\n for (const [k, v] of Object.entries(copy)) {\n if (v === undefined) delete copy[k];\n }\n return copy;\n}\nexport type FetchBaseQueryArgs = {\n baseUrl?: string;\n prepareHeaders?: (headers: Headers, api: Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type' | 'forced'> & {\n arg: string | FetchArgs;\n extraOptions: unknown;\n }) => MaybePromise<Headers | void>;\n fetchFn?: (input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>;\n paramsSerializer?: (params: Record<string, any>) => string;\n /**\n * By default, we only check for 'application/json' and 'application/vnd.api+json' as the content-types for json. If you need to support another format, you can pass\n * in a predicate function for your given api to get the same automatic stringifying behavior\n * @example\n * ```ts\n * const isJsonContentType = (headers: Headers) => [\"application/vnd.api+json\", \"application/json\", \"application/vnd.hal+json\"].includes(headers.get(\"content-type\")?.trim());\n * ```\n */\n isJsonContentType?: (headers: Headers) => boolean;\n /**\n * Defaults to `application/json`;\n */\n jsonContentType?: string;\n\n /**\n * Custom replacer function used when calling `JSON.stringify()`;\n */\n jsonReplacer?: (this: any, key: string, value: any) => any;\n} & RequestInit & Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>;\nexport type FetchBaseQueryMeta = {\n request: Request;\n response?: Response;\n};\n\n/**\n * This is a very small wrapper around fetch that aims to simplify requests.\n *\n * @example\n * ```ts\n * const baseQuery = fetchBaseQuery({\n * baseUrl: 'https://api.your-really-great-app.com/v1/',\n * prepareHeaders: (headers, { getState }) => {\n * const token = (getState() as RootState).auth.token;\n * // If we have a token set in state, let's assume that we should be passing it.\n * if (token) {\n * headers.set('authorization', `Bearer ${token}`);\n * }\n * return headers;\n * },\n * })\n * ```\n *\n * @param {string} baseUrl\n * The base URL for an API service.\n * Typically in the format of https://example.com/\n *\n * @param {(headers: Headers, api: { getState: () => unknown; arg: string | FetchArgs; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders\n * An optional function that can be used to inject headers on requests.\n * Provides a Headers object, most of the `BaseQueryApi` (`dispatch` is not available), and the arg passed into the query function.\n * Useful for setting authentication or headers that need to be set conditionally.\n *\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Headers\n *\n * @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn\n * Accepts a custom `fetch` function if you do not want to use the default on the window.\n * Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`\n *\n * @param {(params: Record<string, unknown>) => string} paramsSerializer\n * An optional function that can be used to stringify querystring parameters.\n *\n * @param {(headers: Headers) => boolean} isJsonContentType\n * An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`\n *\n * @param {string} jsonContentType Used when automatically setting the content-type header for a request with a jsonifiable body that does not have an explicit content-type header. Defaults to `application/json`.\n *\n * @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.\n *\n * @param {number} timeout\n * A number in milliseconds that represents the maximum time a request can take before timing out.\n */\n\nexport function fetchBaseQuery({\n baseUrl,\n prepareHeaders = x => x,\n fetchFn = defaultFetchFn,\n paramsSerializer,\n isJsonContentType = defaultIsJsonContentType,\n jsonContentType = 'application/json',\n jsonReplacer,\n timeout: defaultTimeout,\n responseHandler: globalResponseHandler,\n validateStatus: globalValidateStatus,\n ...baseFetchOptions\n}: FetchBaseQueryArgs = {}): BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta> {\n if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {\n console.warn('Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.');\n }\n return async (arg, api, extraOptions) => {\n const {\n getState,\n extra,\n endpoint,\n forced,\n type\n } = api;\n let meta: FetchBaseQueryMeta | undefined;\n let {\n url,\n headers = new Headers(baseFetchOptions.headers),\n params = undefined,\n responseHandler = globalResponseHandler ?? 'json' as const,\n validateStatus = globalValidateStatus ?? defaultValidateStatus,\n timeout = defaultTimeout,\n ...rest\n } = typeof arg == 'string' ? {\n url: arg\n } : arg;\n let abortController: AbortController | undefined,\n signal = api.signal;\n if (timeout) {\n abortController = new AbortController();\n api.signal.addEventListener('abort', abortController.abort);\n signal = abortController.signal;\n }\n let config: RequestInit = {\n ...baseFetchOptions,\n signal,\n ...rest\n };\n headers = new Headers(stripUndefined(headers));\n config.headers = (await prepareHeaders(headers, {\n getState,\n arg,\n extra,\n endpoint,\n forced,\n type,\n extraOptions\n })) || headers;\n\n // Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc.\n const isJsonifiable = (body: any) => typeof body === 'object' && (isPlainObject(body) || Array.isArray(body) || typeof body.toJSON === 'function');\n if (!config.headers.has('content-type') && isJsonifiable(config.body)) {\n config.headers.set('content-type', jsonContentType);\n }\n if (isJsonifiable(config.body) && isJsonContentType(config.headers)) {\n config.body = JSON.stringify(config.body, jsonReplacer);\n }\n if (params) {\n const divider = ~url.indexOf('?') ? '&' : '?';\n const query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params));\n url += divider + query;\n }\n url = joinUrls(baseUrl, url);\n const request = new Request(url, config);\n const requestClone = new Request(url, config);\n meta = {\n request: requestClone\n };\n let response,\n timedOut = false,\n timeoutId = abortController && setTimeout(() => {\n timedOut = true;\n abortController!.abort();\n }, timeout);\n try {\n response = await fetchFn(request);\n } catch (e) {\n return {\n error: {\n status: timedOut ? 'TIMEOUT_ERROR' : 'FETCH_ERROR',\n error: String(e)\n },\n meta\n };\n } finally {\n if (timeoutId) clearTimeout(timeoutId);\n abortController?.signal.removeEventListener('abort', abortController.abort);\n }\n const responseClone = response.clone();\n meta.response = responseClone;\n let resultData: any;\n let responseText: string = '';\n try {\n let handleResponseError;\n await Promise.all([handleResponse(response, responseHandler).then(r => resultData = r, e => handleResponseError = e),\n // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182\n // we *have* to \"use up\" both streams at the same time or they will stop running in node-fetch scenarios\n responseClone.text().then(r => responseText = r, () => {})]);\n if (handleResponseError) throw handleResponseError;\n } catch (e) {\n return {\n error: {\n status: 'PARSING_ERROR',\n originalStatus: response.status,\n data: responseText,\n error: String(e)\n },\n meta\n };\n }\n return validateStatus(response, resultData) ? {\n data: resultData,\n meta\n } : {\n error: {\n status: response.status,\n data: resultData\n },\n meta\n };\n };\n async function handleResponse(response: Response, responseHandler: ResponseHandler) {\n if (typeof responseHandler === 'function') {\n return responseHandler(response);\n }\n if (responseHandler === 'content-type') {\n responseHandler = isJsonContentType(response.headers) ? 'json' : 'text';\n }\n if (responseHandler === 'json') {\n const text = await response.text();\n return text.length ? JSON.parse(text) : null;\n }\n return response.text();\n }\n}","export class HandledError {\n constructor(public readonly value: any, public readonly meta: any = undefined) {}\n}","import type { BaseQueryApi, BaseQueryArg, BaseQueryEnhancer, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta } from './baseQueryTypes';\nimport type { FetchBaseQueryError } from './fetchBaseQuery';\nimport { HandledError } from './HandledError';\n\n/**\n * Exponential backoff based on the attempt number.\n *\n * @remarks\n * 1. 600ms * random(0.4, 1.4)\n * 2. 1200ms * random(0.4, 1.4)\n * 3. 2400ms * random(0.4, 1.4)\n * 4. 4800ms * random(0.4, 1.4)\n * 5. 9600ms * random(0.4, 1.4)\n *\n * @param attempt - Current attempt\n * @param maxRetries - Maximum number of retries\n */\nasync function defaultBackoff(attempt: number = 0, maxRetries: number = 5) {\n const attempts = Math.min(attempt, maxRetries);\n const timeout = ~~((Math.random() + 0.4) * (300 << attempts)); // Force a positive int in the case we make this an option\n await new Promise(resolve => setTimeout((res: any) => resolve(res), timeout));\n}\ntype RetryConditionFunction = (error: BaseQueryError<BaseQueryFn>, args: BaseQueryArg<BaseQueryFn>, extraArgs: {\n attempt: number;\n baseQueryApi: BaseQueryApi;\n extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions;\n}) => boolean;\nexport type RetryOptions = {\n /**\n * Function used to determine delay between retries\n */\n backoff?: (attempt: number, maxRetries: number) => Promise<void>;\n} & ({\n /**\n * How many times the query will be retried (default: 5)\n */\n maxRetries?: number;\n retryCondition?: undefined;\n} | {\n /**\n * Callback to determine if a retry should be attempted.\n * Return `true` for another retry and `false` to quit trying prematurely.\n */\n retryCondition?: RetryConditionFunction;\n maxRetries?: undefined;\n});\nfunction fail<BaseQuery extends BaseQueryFn = BaseQueryFn>(error: BaseQueryError<BaseQuery>, meta?: BaseQueryMeta<BaseQuery>): never {\n throw Object.assign(new HandledError({\n error,\n meta\n }), {\n throwImmediately: true\n });\n}\nconst EMPTY_OPTIONS = {};\nconst retryWithBackoff: BaseQueryEnhancer<unknown, RetryOptions, RetryOptions | void> = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {\n // We need to figure out `maxRetries` before we define `defaultRetryCondition.\n // This is probably goofy, but ought to work.\n // Put our defaults in one array, filter out undefineds, grab the last value.\n const possibleMaxRetries: number[] = [5, (defaultOptions as any || EMPTY_OPTIONS).maxRetries, (extraOptions as any || EMPTY_OPTIONS).maxRetries].filter(x => x !== undefined);\n const [maxRetries] = possibleMaxRetries.slice(-1);\n const defaultRetryCondition: RetryConditionFunction = (_, __, {\n attempt\n }) => attempt <= maxRetries;\n const options: {\n maxRetries: number;\n backoff: typeof defaultBackoff;\n retryCondition: typeof defaultRetryCondition;\n } = {\n maxRetries,\n backoff: defaultBackoff,\n retryCondition: defaultRetryCondition,\n ...defaultOptions,\n ...extraOptions\n };\n let retry = 0;\n while (true) {\n try {\n const result = await baseQuery(args, api, extraOptions);\n // baseQueries _should_ return an error property, so we should check for that and throw it to continue retrying\n if (result.error) {\n throw new HandledError(result);\n }\n return result;\n } catch (e: any) {\n retry++;\n if (e.throwImmediately) {\n if (e instanceof HandledError) {\n return e.value;\n }\n\n // We don't know what this is, so we have to rethrow it\n throw e;\n }\n if (e instanceof HandledError && !options.retryCondition(e.value.error as FetchBaseQueryError, args, {\n attempt: retry,\n baseQueryApi: api,\n extraOptions\n })) {\n return e.value;\n }\n await options.backoff(retry, options.maxRetries);\n }\n }\n};\n\n/**\n * A utility that can wrap `baseQuery` in the API definition to provide retries with a basic exponential backoff.\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"Retry every request 5 times by default\"\n * import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'\n * interface Post {\n * id: number\n * name: string\n * }\n * type PostsResponse = Post[]\n *\n * // maxRetries: 5 is the default, and can be omitted. Shown for documentation purposes.\n * const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), { maxRetries: 5 });\n * export const api = createApi({\n * baseQuery: staggeredBaseQuery,\n * endpoints: (build) => ({\n * getPosts: build.query<PostsResponse, void>({\n * query: () => ({ url: 'posts' }),\n * }),\n * getPost: build.query<PostsResponse, string>({\n * query: (id) => ({ url: `post/${id}` }),\n * extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint\n * }),\n * }),\n * });\n *\n * export const { useGetPostsQuery, useGetPostQuery } = api;\n * ```\n */\nexport const retry = /* @__PURE__ */Object.assign(retryWithBackoff, {\n fail\n});","import type { ThunkDispatch, ActionCreatorWithoutPayload // Workaround for API-Extractor\n} from '@reduxjs/toolkit';\nimport { createAction } from './rtkImports';\nexport const onFocus = /* @__PURE__ */createAction('__rtkq/focused');\nexport const onFocusLost = /* @__PURE__ */createAction('__rtkq/unfocused');\nexport const onOnline = /* @__PURE__ */createAction('__rtkq/online');\nexport const onOffline = /* @__PURE__ */createAction('__rtkq/offline');\nlet initialized = false;\n\n/**\n * A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.\n * It requires the dispatch method from your store.\n * Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,\n * but you have the option of providing a callback for more granular control.\n *\n * @example\n * ```ts\n * setupListeners(store.dispatch)\n * ```\n *\n * @param dispatch - The dispatch method from your store\n * @param customHandler - An optional callback for more granular control over listener behavior\n * @returns Return value of the handler.\n * The default handler returns an `unsubscribe` method that can be called to remove the listeners.\n */\nexport function setupListeners(dispatch: ThunkDispatch<any, any, any>, customHandler?: (dispatch: ThunkDispatch<any, any, any>, actions: {\n onFocus: typeof onFocus;\n onFocusLost: typeof onFocusLost;\n onOnline: typeof onOnline;\n onOffline: typeof onOffline;\n}) => () => void) {\n function defaultHandler() {\n const handleFocus = () => dispatch(onFocus());\n const handleFocusLost = () => dispatch(onFocusLost());\n const handleOnline = () => dispatch(onOnline());\n const handleOffline = () => dispatch(onOffline());\n const handleVisibilityChange = () => {\n if (window.document.visibilityState === 'visible') {\n handleFocus();\n } else {\n handleFocusLost();\n }\n };\n if (!initialized) {\n if (typeof window !== 'undefined' && window.addEventListener) {\n // Handle focus events\n window.addEventListener('visibilitychange', handleVisibilityChange, false);\n window.addEventListener('focus', handleFocus, false);\n\n // Handle connection events\n window.addEventListener('online', handleOnline, false);\n window.addEventListener('offline', handleOffline, false);\n initialized = true;\n }\n }\n const unsubscribe = () => {\n window.removeEventListener('focus', handleFocus);\n window.removeEventListener('visibilitychange', handleVisibilityChange);\n window.removeEventListener('online', handleOnline);\n window.removeEventListener('offline', handleOffline);\n initialized = false;\n };\n return unsubscribe;\n }\n return customHandler ? customHandler(dispatch, {\n onFocus,\n onFocusLost,\n onOffline,\n onOnline\n }) : defaultHandler();\n}","import type { Api } from '@reduxjs/toolkit/query';\nimport type { BaseQueryApi, BaseQueryArg, BaseQueryError, BaseQueryExtraOptions, BaseQueryFn, BaseQueryMeta, BaseQueryResult, QueryReturnValue } from './baseQueryTypes';\nimport type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection';\nimport type { CacheLifecycleInfiniteQueryExtraOptions, CacheLifecycleMutationExtraOptions, CacheLifecycleQueryExtraOptions } from './core/buildMiddleware/cacheLifecycle';\nimport type { QueryLifecycleInfiniteQueryExtraOptions, QueryLifecycleMutationExtraOptions, QueryLifecycleQueryExtraOptions } from './core/buildMiddleware/queryLifecycle';\nimport type { InfiniteData, InfiniteQueryConfigOptions, QuerySubState, RootState } from './core/index';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { NEVER } from './fakeBaseQuery';\nimport type { CastAny, HasRequiredProps, MaybePromise, NonUndefined, OmitFromUnion, UnwrapPromise } from './tsHelpers';\nimport { isNotNullish } from './utils';\nconst resultType = /* @__PURE__ */Symbol();\nconst baseQuery = /* @__PURE__ */Symbol();\ntype EndpointDefinitionWithQuery<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {\n /**\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.\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"query example\"\n *\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n * interface Post {\n * id: number\n * name: string\n * }\n * type PostsResponse = Post[]\n *\n * const api = createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * tagTypes: ['Post'],\n * endpoints: (build) => ({\n * getPosts: build.query<PostsResponse, void>({\n * // highlight-start\n * query: () => 'posts',\n * // highlight-end\n * }),\n * addPost: build.mutation<Post, Partial<Post>>({\n * // highlight-start\n * query: (body) => ({\n * url: `posts`,\n * method: 'POST',\n * body,\n * }),\n * // highlight-end\n * invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n * }),\n * })\n * })\n * ```\n */\n query(arg: QueryArg): BaseQueryArg<BaseQuery>;\n queryFn?: never;\n /**\n * A function to manipulate the data returned by a query or mutation.\n */\n transformResponse?(baseQueryReturnValue: BaseQueryResult<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): ResultType | Promise<ResultType>;\n /**\n * A function to manipulate the data returned by a failed query or mutation.\n */\n transformErrorResponse?(baseQueryReturnValue: BaseQueryError<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): unknown;\n /**\n * Defaults to `true`.\n *\n * Most apps should leave this setting on. The only time it can be a performance issue\n * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n * you're unable to paginate it.\n *\n * For details of how this works, please see the below. When it is set to `false`,\n * every request will cause subscribed components to rerender, even when the data has not changed.\n *\n * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n */\n structuralSharing?: boolean;\n};\ntype EndpointDefinitionWithQueryFn<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {\n /**\n * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\n *\n * @example\n * ```ts\n * // codeblock-meta title=\"Basic queryFn example\"\n *\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n * interface Post {\n * id: number\n * name: string\n * }\n * type PostsResponse = Post[]\n *\n * const api = createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * endpoints: (build) => ({\n * getPosts: build.query<PostsResponse, void>({\n * query: () => 'posts',\n * }),\n * flipCoin: build.query<'heads' | 'tails', void>({\n * // highlight-start\n * queryFn(arg, queryApi, extraOptions, baseQuery) {\n * const randomVal = Math.random()\n * if (randomVal < 0.45) {\n * return { data: 'heads' }\n * }\n * if (randomVal < 0.9) {\n * return { data: 'tails' }\n * }\n * return { error: { status: 500, statusText: 'Internal Server Error', data: \"Coin landed on its edge!\" } }\n * }\n * // highlight-end\n * })\n * })\n * })\n * ```\n */\n queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions<BaseQuery>, baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>>;\n query?: never;\n transformResponse?: never;\n transformErrorResponse?: never;\n /**\n * Defaults to `true`.\n *\n * Most apps should leave this setting on. The only time it can be a performance issue\n * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n * you're unable to paginate it.\n *\n * For details of how this works, please see the below. When it is set to `false`,\n * every request will cause subscribed components to rerender, even when the data has not changed.\n *\n * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n */\n structuralSharing?: boolean;\n};\ntype BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = {\n QueryArg: QueryArg;\n BaseQuery: BaseQuery;\n ResultType: ResultType;\n};\nexport type BaseEndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = (([CastAny<BaseQueryResult<BaseQuery>, {}>] extends [NEVER] ? never : EndpointDefinitionWithQuery<QueryArg, BaseQuery, ResultType>) | EndpointDefinitionWithQueryFn<QueryArg, BaseQuery, ResultType>) & {\n /* phantom type */\n [resultType]?: ResultType;\n /* phantom type */\n [baseQuery]?: BaseQuery;\n} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {\n extraOptions: BaseQueryExtraOptions<BaseQuery>;\n}, {\n extraOptions?: BaseQueryExtraOptions<BaseQuery>;\n}>;\nexport enum DefinitionType {\n query = 'query',\n mutation = 'mutation',\n infinitequery = 'infinitequery',\n}\nexport type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => ReadonlyArray<TagDescription<TagTypes> | undefined | null>;\nexport type FullTagDescription<TagType> = {\n type: TagType;\n id?: number | string;\n};\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>;\n\n/**\n * @public\n */\nexport type ResultDescription<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = ReadonlyArray<TagDescription<TagTypes> | undefined | null> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>;\ntype QueryTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType> & {\n /**\n * The endpoint definition type. To be used with some internal generic types.\n * @example\n * ```ts\n * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n * ```\n */\n QueryDefinition: QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n TagTypes: TagTypes;\n ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> extends CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n type: DefinitionType.query;\n\n /**\n * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.\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.\n * 1. `['Post']` - equivalent to `2`\n * 2. `[{ type: 'Post' }]` - equivalent to `1`\n * 3. `[{ type: 'Post', id: 1 }]`\n * 4. `(result, error, arg) => ['Post']` - equivalent to `5`\n * 5. `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`\n * 6. `(result, error, arg) => [{ type: 'Post', id: 1 }]`\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"providesTags example\"\n *\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n * interface Post {\n * id: number\n * name: string\n * }\n * type PostsResponse = Post[]\n *\n * const api = createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * tagTypes: ['Posts'],\n * endpoints: (build) => ({\n * getPosts: build.query<PostsResponse, void>({\n * query: () => 'posts',\n * // highlight-start\n * providesTags: (result) =>\n * result\n * ? [\n * ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n * { type: 'Posts', id: 'LIST' },\n * ]\n * : [{ type: 'Posts', id: 'LIST' }],\n * // highlight-end\n * })\n * })\n * })\n * ```\n */\n providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n /**\n * Not to be used. A query should not invalidate tags in the cache.\n */\n invalidatesTags?: never;\n\n /**\n * Can be provided to return a custom cache key value based on the query arguments.\n *\n * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key. It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n *\n * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean. If it returns a string, that value will be used as the cache key directly. If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`. This simplifies the use case of stripping out args you don't want included in the cache key.\n *\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n *\n * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n * interface Post {\n * id: number\n * name: string\n * }\n *\n * interface MyApiClient {\n * fetchPost: (id: string) => Promise<Post>\n * }\n *\n * createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * endpoints: (build) => ({\n * // Example: an endpoint with an API client passed in as an argument,\n * // but only the item ID should be used as the cache key\n * getPost: build.query<Post, { id: string; client: MyApiClient }>({\n * queryFn: async ({ id, client }) => {\n * const post = await client.fetchPost(id)\n * return { data: post }\n * },\n * // highlight-start\n * serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n * const { id } = queryArgs\n * // This can return a string, an object, a number, or a boolean.\n * // If it returns an object, number or boolean, that value\n * // will be serialized automatically via `defaultSerializeQueryArgs`\n * return { id } // omit `client` from the cache key\n *\n * // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n * // return defaultSerializeQueryArgs({\n * // endpointName,\n * // queryArgs: { id },\n * // endpointDefinition\n * // })\n * // Or create and return a string yourself:\n * // return `getPost(${id})`\n * },\n * // highlight-end\n * }),\n * }),\n *})\n * ```\n */\n serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n /**\n * Can be provided to merge an incoming response value into the current cache data.\n * If supplied, no automatic structural sharing will be applied - it's up to\n * you to update the cache appropriately.\n *\n * Since RTKQ normally replaces cache entries with the new response, you will usually\n * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep\n * an existing cache entry so that it can be updated.\n *\n * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,\n * or return a new value, but _not_ both at once.\n *\n * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,\n * the cache entry will just save the response data directly.\n *\n * Useful if you don't want a new request to completely override the current cache value,\n * maybe because you have manually updated it from another source and don't want those\n * updates to get lost.\n *\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"merge: pagination\"\n *\n * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n * interface Post {\n * id: number\n * name: string\n * }\n *\n * createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * endpoints: (build) => ({\n * listItems: build.query<string[], number>({\n * query: (pageNumber) => `/listItems?page=${pageNumber}`,\n * // Only have one cache entry because the arg always maps to one string\n * serializeQueryArgs: ({ endpointName }) => {\n * return endpointName\n * },\n * // Always merge incoming data to the cache entry\n * merge: (currentCache, newItems) => {\n * currentCache.push(...newItems)\n * },\n * // Refetch when the page arg changes\n * forceRefetch({ currentArg, previousArg }) {\n * return currentArg !== previousArg\n * },\n * }),\n * }),\n *})\n * ```\n */\n merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: {\n arg: QueryArg;\n baseQueryMeta: BaseQueryMeta<BaseQuery>;\n requestId: string;\n fulfilledTimeStamp: number;\n }): ResultType | void;\n\n /**\n * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.\n * This is primarily useful for \"infinite scroll\" / pagination use cases where\n * RTKQ is keeping a single cache entry that is added to over time, in combination\n * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback\n * set to add incoming data to the cache entry each time.\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"forceRefresh: pagination\"\n *\n * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n * interface Post {\n * id: number\n * name: string\n * }\n *\n * createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * endpoints: (build) => ({\n * listItems: build.query<string[], number>({\n * query: (pageNumber) => `/listItems?page=${pageNumber}`,\n * // Only have one cache entry because the arg always maps to one string\n * serializeQueryArgs: ({ endpointName }) => {\n * return endpointName\n * },\n * // Always merge incoming data to the cache entry\n * merge: (currentCache, newItems) => {\n * currentCache.push(...newItems)\n * },\n * // Refetch when the page arg changes\n * forceRefetch({ currentArg, previousArg }) {\n * return currentArg !== previousArg\n * },\n * }),\n * }),\n *})\n * ```\n */\n forceRefetch?(params: {\n currentArg: QueryArg | undefined;\n previousArg: QueryArg | undefined;\n state: RootState<any, any, string>;\n endpointState?: QuerySubState<any>;\n }): boolean;\n\n /**\n * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n */\n Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n}\nexport type QueryDefinition<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> & QueryExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport interface InfiniteQueryTypes<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> extends BaseEndpointTypes<QueryArg, BaseQuery, ResultType> {\n /**\n * The endpoint definition type. To be used with some internal generic types.\n * @example\n * ```ts\n * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n * ```\n */\n InfiniteQueryDefinition: InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\n TagTypes: TagTypes;\n ReducerPath: ReducerPath;\n}\nexport interface InfiniteQueryExtraOptions<TagTypes extends string, ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> extends CacheLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleInfiniteQueryExtraOptions<InfiniteData<ResultType, PageParam>, QueryArg, BaseQuery, ReducerPath>, CacheCollectionQueryExtraOptions {\n type: DefinitionType.infinitequery;\n providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n /**\n * Not to be used. A query should not invalidate tags in the cache.\n */\n invalidatesTags?: never;\n\n /**\n * Required options to configure the infinite query behavior.\n * `initialPageParam` and `getNextPageParam` are required, to\n * ensure the infinite query can properly fetch the next page of data.\n * `initialPageParam` may be specified when using the\n * endpoint, to override the default value.\n * `maxPages` and `getPreviousPageParam` are both optional.\n * \n * @example\n * \n * ```ts\n * // codeblock-meta title=\"infiniteQueryOptions example\"\n * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n * \n * type Pokemon = {\n * id: string\n * name: string\n * }\n * \n * const pokemonApi = createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n * endpoints: (build) => ({\n * getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({\n * infiniteQueryOptions: {\n * initialPageParam: 0,\n * maxPages: 3,\n * getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>\n * lastPageParam + 1,\n * getPreviousPageParam: (\n * firstPage,\n * allPages,\n * firstPageParam,\n * allPageParams,\n * ) => {\n * return firstPageParam > 0 ? firstPageParam - 1 : undefined\n * },\n * },\n * query({pageParam}) {\n * return `https://example.com/listItems?page=${pageParam}`\n * },\n * }),\n * }),\n * })\n \n * ```\n */\n infiniteQueryOptions: InfiniteQueryConfigOptions<ResultType, PageParam>;\n\n /**\n * Can be provided to return a custom cache key value based on the query arguments.\n *\n * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key. It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n *\n * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean. If it returns a string, that value will be used as the cache key directly. If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`. This simplifies the use case of stripping out args you don't want included in the cache key.\n *\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n *\n * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'\n * interface Post {\n * id: number\n * name: string\n * }\n *\n * interface MyApiClient {\n * fetchPost: (id: string) => Promise<Post>\n * }\n *\n * createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * endpoints: (build) => ({\n * // Example: an endpoint with an API client passed in as an argument,\n * // but only the item ID should be used as the cache key\n * getPost: build.query<Post, { id: string; client: MyApiClient }>({\n * queryFn: async ({ id, client }) => {\n * const post = await client.fetchPost(id)\n * return { data: post }\n * },\n * // highlight-start\n * serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n * const { id } = queryArgs\n * // This can return a string, an object, a number, or a boolean.\n * // If it returns an object, number or boolean, that value\n * // will be serialized automatically via `defaultSerializeQueryArgs`\n * return { id } // omit `client` from the cache key\n *\n * // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n * // return defaultSerializeQueryArgs({\n * // endpointName,\n * // queryArgs: { id },\n * // endpointDefinition\n * // })\n * // Or create and return a string yourself:\n * // return `getPost(${id})`\n * },\n * // highlight-end\n * }),\n * }),\n *})\n * ```\n */\n serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;\n\n /**\n * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n */\n Types?: InfiniteQueryTypes<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\n}\nexport type InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> =\n// Infinite query endpoints receive `{queryArg, pageParam}`\nBaseEndpointDefinition<InfiniteQueryCombinedArg<QueryArg, PageParam>, BaseQuery, ResultType> & InfiniteQueryExtraOptions<TagTypes, ResultType, QueryArg, PageParam, BaseQuery, ReducerPath>;\ntype MutationTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType> & {\n /**\n * The endpoint definition type. To be used with some internal generic types.\n * @example\n * ```ts\n * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...\n * ```\n */\n MutationDefinition: MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n TagTypes: TagTypes;\n ReducerPath: ReducerPath;\n};\n\n/**\n * @public\n */\nexport interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> extends CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>, QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath> {\n type: DefinitionType.mutation;\n\n /**\n * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.\n * Expects the same shapes as `providesTags`.\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"invalidatesTags example\"\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n * interface Post {\n * id: number\n * name: string\n * }\n * type PostsResponse = Post[]\n *\n * const api = createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * tagTypes: ['Posts'],\n * endpoints: (build) => ({\n * getPosts: build.query<PostsResponse, void>({\n * query: () => 'posts',\n * providesTags: (result) =>\n * result\n * ? [\n * ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n * { type: 'Posts', id: 'LIST' },\n * ]\n * : [{ type: 'Posts', id: 'LIST' }],\n * }),\n * addPost: build.mutation<Post, Partial<Post>>({\n * query(body) {\n * return {\n * url: `posts`,\n * method: 'POST',\n * body,\n * }\n * },\n * // highlight-start\n * invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n * // highlight-end\n * }),\n * })\n * })\n * ```\n */\n invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;\n /**\n * Not to be used. A mutation should not provide tags to the cache.\n */\n providesTags?: never;\n\n /**\n * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n */\n Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n}\nexport type MutationDefinition<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> & MutationExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport type EndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string, PageParam = any> = QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath> | MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath> | InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\nexport type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any>>;\nexport function isQueryDefinition(e: EndpointDefinition<any, any, any, any>): e is QueryDefinition<any, any, any, any> {\n return e.type === DefinitionType.query;\n}\nexport function isMutationDefinition(e: EndpointDefinition<any, any, any, any>): e is MutationDefinition<any, any, any, any> {\n return e.type === DefinitionType.mutation;\n}\nexport function isInfiniteQueryDefinition(e: EndpointDefinition<any, any, any, any>): e is InfiniteQueryDefinition<any, any, any, any, any> {\n return e.type === DefinitionType.infinitequery;\n}\nexport type EndpointBuilder<BaseQuery extends BaseQueryFn, TagTypes extends string, ReducerPath extends string> = {\n /**\n * An endpoint definition that retrieves data, and may provide tags to the cache.\n *\n * @example\n * ```js\n * // codeblock-meta title=\"Example of all query endpoint options\"\n * const api = createApi({\n * baseQuery,\n * endpoints: (build) => ({\n * getPost: build.query({\n * query: (id) => ({ url: `post/${id}` }),\n * // Pick out data and prevent nested properties in a hook or selector\n * transformResponse: (response) => response.data,\n * // Pick out error and prevent nested properties in a hook or selector\n * transformErrorResponse: (response) => response.error,\n * // `result` is the server response\n * providesTags: (result, error, id) => [{ type: 'Post', id }],\n * // trigger side effects or optimistic updates\n * onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},\n * // handle subscriptions etc\n * onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},\n * }),\n * }),\n *});\n *```\n */\n query<ResultType, QueryArg>(definition: OmitFromUnion<QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>, 'type'>): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n /**\n * An endpoint definition that alters data on the server or will possibly invalidate the cache.\n *\n * @example\n * ```js\n * // codeblock-meta title=\"Example of all mutation endpoint options\"\n * const api = createApi({\n * baseQuery,\n * endpoints: (build) => ({\n * updatePost: build.mutation({\n * query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),\n * // Pick out data and prevent nested properties in a hook or selector\n * transformResponse: (response) => response.data,\n * // Pick out error and prevent nested properties in a hook or selector\n * transformErrorResponse: (response) => response.error,\n * // `result` is the server response\n * invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\n * // trigger side effects or optimistic updates\n * onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},\n * // handle subscriptions etc\n * onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},\n * }),\n * }),\n * });\n * ```\n */\n mutation<ResultType, QueryArg>(definition: OmitFromUnion<MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>, 'type'>): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;\n infiniteQuery<ResultType, QueryArg, PageParam>(definition: OmitFromUnion<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>, 'type'>): InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, ResultType, ReducerPath>;\n};\nexport type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;\nexport function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(description: ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType> | undefined, result: ResultType | undefined, error: ErrorType | undefined, queryArg: QueryArg, meta: MetaType | undefined, assertTagTypes: AssertTagTypes): readonly FullTagDescription<string>[] {\n if (isFunction(description)) {\n return description(result as ResultType, error as undefined, queryArg, meta as MetaType).filter(isNotNullish).map(expandTagDescription).map(assertTagTypes);\n }\n if (Array.isArray(description)) {\n return description.map(expandTagDescription).map(assertTagTypes);\n }\n return [];\n}\nfunction isFunction<T>(t: T): t is Extract<T, Function> {\n return typeof t === 'function';\n}\nexport function expandTagDescription(description: TagDescription<string>): FullTagDescription<string> {\n return typeof description === 'string' ? {\n type: description\n } : description;\n}\nexport type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any> ? QA : never;\n\n// Just extracting `QueryArg` from `BaseEndpointDefinition`\n// doesn't sufficiently match here.\n// We need to explicitly match against `InfiniteQueryDefinition`\nexport type InfiniteQueryArgFrom<D extends BaseEndpointDefinition<any, any, any>> = D extends InfiniteQueryDefinition<infer QA, any, any, any, any> ? QA : never;\nexport type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT> ? RT : unknown;\nexport type ReducerPathFrom<D extends EndpointDefinition<any, any, any, any, any>> = D extends EndpointDefinition<any, any, any, any, infer RP> ? RP : unknown;\nexport type TagTypesFrom<D extends EndpointDefinition<any, any, any, any>> = D extends EndpointDefinition<any, any, infer RP, any> ? RP : unknown;\nexport type PageParamFrom<D extends InfiniteQueryDefinition<any, any, any, any, any>> = D extends InfiniteQueryDefinition<any, infer PP, any, any, any> ? PP : unknown;\nexport type InfiniteQueryCombinedArg<QueryArg, PageParam> = {\n queryArg: QueryArg;\n pageParam: PageParam;\n};\nexport type TagTypesFromApi<T> = T extends Api<any, any, any, infer TagTypes> ? TagTypes : never;\nexport type DefinitionsFromApi<T> = T extends Api<any, infer Definitions, any, any> ? Definitions : never;\nexport type TransformedResponse<NewDefinitions extends EndpointDefinitions, K, ResultType> = K extends keyof NewDefinitions ? NewDefinitions[K]['transformResponse'] extends undefined ? ResultType : UnwrapPromise<ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>> : ResultType;\nexport type OverrideResultType<Definition, NewResultType> = Definition extends QueryDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends MutationDefinition<infer QueryArg, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath> : Definition extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, infer TagTypes, any, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, TagTypes, NewResultType, ReducerPath> : never;\nexport type UpdateDefinitions<Definitions extends EndpointDefinitions, NewTagTypes extends string, NewDefinitions extends EndpointDefinitions> = { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends MutationDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : Definitions[K] extends InfiniteQueryDefinition<infer QueryArg, infer PageParam, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, NewTagTypes, TransformedResponse<NewDefinitions, K, ResultType>, ReducerPath> : never };","import type { AsyncThunk, AsyncThunkPayloadCreator, Draft, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { Patch } from 'immer';\nimport { isDraftable, produceWithPatches } from 'immer';\nimport type { Api, ApiContext } from '../apiTypes';\nimport type { BaseQueryError, BaseQueryFn, QueryReturnValue } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { AssertTagTypes, EndpointDefinition, EndpointDefinitions, InfiniteQueryArgFrom, InfiniteQueryCombinedArg, InfiniteQueryDefinition, MutationDefinition, PageParamFrom, QueryArgFrom, QueryDefinition, ResultTypeFrom } from '../endpointDefinitions';\nimport { calculateProvidedBy, isInfiniteQueryDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { HandledError } from '../HandledError';\nimport type { UnwrapPromise } from '../tsHelpers';\nimport type { RootState, QueryKeys, QuerySubstateIdentifier, InfiniteData, InfiniteQueryConfigOptions, QueryCacheKey, InfiniteQueryDirection, InfiniteQueryKeys } from './apiState';\nimport { QueryStatus } from './apiState';\nimport type { InfiniteQueryActionCreatorResult, QueryActionCreatorResult, StartInfiniteQueryActionCreatorOptions, StartQueryActionCreatorOptions } from './buildInitiate';\nimport { forceQueryFnSymbol, isUpsertQuery } from './buildInitiate';\nimport type { AllSelectors } from './buildSelectors';\nimport type { ApiEndpointQuery, PrefetchOptions } from './module';\nimport { createAsyncThunk, isAllOf, isFulfilled, isPending, isRejected, isRejectedWithValue, SHOULD_AUTOBATCH } from './rtkImports';\nexport type BuildThunksApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = Matchers<QueryThunk, Definition>;\nexport type BuildThunksApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = Matchers<QueryThunk, Definition>;\nexport type BuildThunksApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = Matchers<MutationThunk, Definition>;\ntype EndpointThunk<Thunk extends QueryThunk | MutationThunk, Definition extends EndpointDefinition<any, any, any, any>> = Definition extends EndpointDefinition<infer QueryArg, infer BaseQueryFn, any, infer ResultType> ? Thunk extends AsyncThunk<unknown, infer ATArg, infer ATConfig> ? AsyncThunk<ResultType, ATArg & {\n originalArgs: QueryArg;\n}, ATConfig & {\n rejectValue: BaseQueryError<BaseQueryFn>;\n}> : never : never;\nexport type PendingAction<Thunk extends QueryThunk | MutationThunk, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>;\nexport type FulfilledAction<Thunk extends QueryThunk | MutationThunk, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>;\nexport type RejectedAction<Thunk extends QueryThunk | MutationThunk, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>;\nexport type Matcher<M> = (value: any) => value is M;\nexport interface Matchers<Thunk extends QueryThunk | MutationThunk, Definition extends EndpointDefinition<any, any, any, any>> {\n matchPending: Matcher<PendingAction<Thunk, Definition>>;\n matchFulfilled: Matcher<FulfilledAction<Thunk, Definition>>;\n matchRejected: Matcher<RejectedAction<Thunk, Definition>>;\n}\nexport type QueryThunkArg = QuerySubstateIdentifier & StartQueryActionCreatorOptions & {\n type: 'query';\n originalArgs: unknown;\n endpointName: string;\n};\nexport type InfiniteQueryThunkArg<D extends InfiniteQueryDefinition<any, any, any, any, any>> = QuerySubstateIdentifier & StartInfiniteQueryActionCreatorOptions<D> & {\n type: `query`;\n originalArgs: unknown;\n endpointName: string;\n param: unknown;\n direction?: InfiniteQueryDirection;\n};\ntype MutationThunkArg = {\n type: 'mutation';\n originalArgs: unknown;\n endpointName: string;\n track?: boolean;\n fixedCacheKey?: string;\n};\nexport type ThunkResult = unknown;\nexport type ThunkApiMetaConfig = {\n pendingMeta: {\n startedTimeStamp: number;\n [SHOULD_AUTOBATCH]: true;\n };\n fulfilledMeta: {\n fulfilledTimeStamp: number;\n baseQueryMeta: unknown;\n [SHOULD_AUTOBATCH]: true;\n };\n rejectedMeta: {\n baseQueryMeta: unknown;\n [SHOULD_AUTOBATCH]: true;\n };\n};\nexport type QueryThunk = AsyncThunk<ThunkResult, QueryThunkArg, ThunkApiMetaConfig>;\nexport type InfiniteQueryThunk<D extends InfiniteQueryDefinition<any, any, any, any, any>> = AsyncThunk<ThunkResult, InfiniteQueryThunkArg<D>, ThunkApiMetaConfig>;\nexport type MutationThunk = AsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig>;\nfunction defaultTransformResponse(baseQueryReturnValue: unknown) {\n return baseQueryReturnValue;\n}\nexport type MaybeDrafted<T> = T | Draft<T>;\nexport type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>;\nexport type UpsertRecipe<T> = (data: MaybeDrafted<T> | undefined) => void | MaybeDrafted<T>;\nexport type PatchQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, patches: readonly Patch[], updateProvided?: boolean) => ThunkAction<void, PartialState, any, UnknownAction>;\nexport type AllQueryKeys<Definitions extends EndpointDefinitions> = QueryKeys<Definitions> | InfiniteQueryKeys<Definitions>;\nexport type QueryArgFromAnyQueryDefinition<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryArgFrom<Definitions[EndpointName]> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? QueryArgFrom<Definitions[EndpointName]> : never;\nexport type DataFromAnyQueryDefinition<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteData<ResultTypeFrom<Definitions[EndpointName]>, PageParamFrom<Definitions[EndpointName]>> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? ResultTypeFrom<Definitions[EndpointName]> : unknown;\nexport type UpsertThunkResult<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = Definitions[EndpointName] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryActionCreatorResult<Definitions[EndpointName]> : Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? QueryActionCreatorResult<Definitions[EndpointName]> : QueryActionCreatorResult<never>;\nexport type UpdateQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>, updateRecipe: Recipe<DataFromAnyQueryDefinition<Definitions, EndpointName>>, updateProvided?: boolean) => ThunkAction<PatchCollection, PartialState, any, UnknownAction>;\nexport type UpsertQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>, value: DataFromAnyQueryDefinition<Definitions, EndpointName>) => ThunkAction<UpsertThunkResult<Definitions, EndpointName>, PartialState, any, UnknownAction>;\n\n/**\n * An object returned from dispatching a `api.util.updateQueryData` call.\n */\nexport type PatchCollection = {\n /**\n * An `immer` Patch describing the cache update.\n */\n patches: Patch[];\n /**\n * An `immer` Patch to revert the cache update.\n */\n inversePatches: Patch[];\n /**\n * A function that will undo the cache update.\n */\n undo: () => void;\n};\ntype TransformCallback = (baseQueryReturnValue: unknown, meta: unknown, arg: unknown) => any;\nexport const addShouldAutoBatch = <T extends Record<string, any>,>(arg: T = {} as T): T & {\n [SHOULD_AUTOBATCH]: true;\n} => {\n return {\n ...arg,\n [SHOULD_AUTOBATCH]: true\n };\n};\nexport function buildThunks<BaseQuery extends BaseQueryFn, ReducerPath extends string, Definitions extends EndpointDefinitions>({\n reducerPath,\n baseQuery,\n context: {\n endpointDefinitions\n },\n serializeQueryArgs,\n api,\n assertTagType,\n selectors\n}: {\n baseQuery: BaseQuery;\n reducerPath: ReducerPath;\n context: ApiContext<Definitions>;\n serializeQueryArgs: InternalSerializeQueryArgs;\n api: Api<BaseQuery, Definitions, ReducerPath, any>;\n assertTagType: AssertTagTypes;\n selectors: AllSelectors;\n}) {\n type State = RootState<any, string, ReducerPath>;\n const patchQueryData: PatchQueryDataThunk<EndpointDefinitions, State> = (endpointName, arg, patches, updateProvided) => (dispatch, getState) => {\n const endpointDefinition = endpointDefinitions[endpointName];\n const queryCacheKey = serializeQueryArgs({\n queryArgs: arg,\n endpointDefinition,\n endpointName\n });\n dispatch(api.internalActions.queryResultPatched({\n queryCacheKey,\n patches\n }));\n if (!updateProvided) {\n return;\n }\n const newValue = api.endpoints[endpointName].select(arg)(\n // Work around TS 4.1 mismatch\n getState() as RootState<any, any, any>);\n const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, undefined, arg, {}, assertTagType);\n dispatch(api.internalActions.updateProvidedBy({\n queryCacheKey,\n providedTags\n }));\n };\n function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [item, ...items];\n return max && newItems.length > max ? newItems.slice(0, -1) : newItems;\n }\n function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [...items, item];\n return max && newItems.length > max ? newItems.slice(1) : newItems;\n }\n const updateQueryData: UpdateQueryDataThunk<EndpointDefinitions, State> = (endpointName, arg, updateRecipe, updateProvided = true) => (dispatch, getState) => {\n const endpointDefinition = api.endpoints[endpointName];\n const currentState = endpointDefinition.select(arg)(\n // Work around TS 4.1 mismatch\n getState() as RootState<any, any, any>);\n const ret: PatchCollection = {\n patches: [],\n inversePatches: [],\n undo: () => dispatch(api.util.patchQueryData(endpointName, arg, ret.inversePatches, updateProvided))\n };\n if (currentState.status === QueryStatus.uninitialized) {\n return ret;\n }\n let newValue;\n if ('data' in currentState) {\n if (isDraftable(currentState.data)) {\n const [value, patches, inversePatches] = produceWithPatches(currentState.data, updateRecipe);\n ret.patches.push(...patches);\n ret.inversePatches.push(...inversePatches);\n newValue = value;\n } else {\n newValue = updateRecipe(currentState.data);\n ret.patches.push({\n op: 'replace',\n path: [],\n value: newValue\n });\n ret.inversePatches.push({\n op: 'replace',\n path: [],\n value: currentState.data\n });\n }\n }\n if (ret.patches.length === 0) {\n return ret;\n }\n dispatch(api.util.patchQueryData(endpointName, arg, ret.patches, updateProvided));\n return ret;\n };\n const upsertQueryData: UpsertQueryDataThunk<Definitions, State> = (endpointName, arg, value) => dispatch => {\n type EndpointName = typeof endpointName;\n const res = dispatch((api.endpoints[endpointName] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>).initiate(arg, {\n subscribe: false,\n forceRefetch: true,\n [forceQueryFnSymbol]: () => ({\n data: value\n })\n })) as UpsertThunkResult<Definitions, EndpointName>;\n return res;\n };\n const getTransformCallbackForEndpoint = (endpointDefinition: EndpointDefinition<any, any, any, any>, transformFieldName: 'transformResponse' | 'transformErrorResponse'): TransformCallback => {\n return endpointDefinition.query && endpointDefinition[transformFieldName] ? endpointDefinition[transformFieldName]! as TransformCallback : defaultTransformResponse;\n };\n\n // The generic async payload function for all of our thunks\n const executeEndpoint: AsyncThunkPayloadCreator<ThunkResult, QueryThunkArg | MutationThunkArg | InfiniteQueryThunkArg<any>, ThunkApiMetaConfig & {\n state: RootState<any, string, ReducerPath>;\n }> = async (arg, {\n signal,\n abort,\n rejectWithValue,\n fulfillWithValue,\n dispatch,\n getState,\n extra\n }) => {\n const endpointDefinition = endpointDefinitions[arg.endpointName];\n try {\n let transformResponse: TransformCallback = getTransformCallbackForEndpoint(endpointDefinition, 'transformResponse');\n const baseQueryApi = {\n signal,\n abort,\n dispatch,\n getState,\n extra,\n endpoint: arg.endpointName,\n type: arg.type,\n forced: arg.type === 'query' ? isForcedQuery(arg, getState()) : undefined,\n queryCacheKey: arg.type === 'query' ? arg.queryCacheKey : undefined\n };\n const forceQueryFn = arg.type === 'query' ? arg[forceQueryFnSymbol] : undefined;\n let finalQueryReturnValue: QueryReturnValue;\n\n // Infinite query wrapper, which executes the request and returns\n // the InfiniteData `{pages, pageParams}` structure\n const fetchPage = async (data: InfiniteData<unknown, unknown>, param: unknown, maxPages: number, previous?: boolean): Promise<QueryReturnValue> => {\n // This should handle cases where there is no `getPrevPageParam`,\n // or `getPPP` returned nullish\n if (param == null && data.pages.length) {\n return Promise.resolve({\n data\n });\n }\n const finalQueryArg: InfiniteQueryCombinedArg<any, any> = {\n queryArg: arg.originalArgs,\n pageParam: param\n };\n const pageResponse = await executeRequest(finalQueryArg);\n const addTo = previous ? addToStart : addToEnd;\n return {\n data: {\n pages: addTo(data.pages, pageResponse.data, maxPages),\n pageParams: addTo(data.pageParams, param, maxPages)\n }\n };\n };\n\n // Wrapper for executing either `query` or `queryFn`,\n // and handling any errors\n async function executeRequest(finalQueryArg: unknown): Promise<QueryReturnValue> {\n let result: QueryReturnValue;\n const {\n extraOptions\n } = endpointDefinition;\n if (forceQueryFn) {\n // upsertQueryData relies on this to pass in the user-provided value\n result = forceQueryFn();\n } else if (endpointDefinition.query) {\n result = await baseQuery(endpointDefinition.query(finalQueryArg as any), baseQueryApi, extraOptions as any);\n } else {\n result = await endpointDefinition.queryFn(finalQueryArg as any, baseQueryApi, extraOptions as any, arg => baseQuery(arg, baseQueryApi, extraOptions as any));\n }\n if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n const what = endpointDefinition.query ? '`baseQuery`' : '`queryFn`';\n let err: undefined | string;\n if (!result) {\n err = `${what} did not return anything.`;\n } else if (typeof result !== 'object') {\n err = `${what} did not return an object.`;\n } else if (result.error && result.data) {\n err = `${what} returned an object containing both \\`error\\` and \\`result\\`.`;\n } else if (result.error === undefined && result.data === undefined) {\n err = `${what} returned an object containing neither a valid \\`error\\` and \\`result\\`. At least one of them should not be \\`undefined\\``;\n } else {\n for (const key of Object.keys(result)) {\n if (key !== 'error' && key !== 'data' && key !== 'meta') {\n err = `The object returned by ${what} has the unknown property ${key}.`;\n break;\n }\n }\n }\n if (err) {\n console.error(`Error encountered handling the endpoint ${arg.endpointName}.\n ${err}\n It needs to return an object with either the shape \\`{ data: <value> }\\` or \\`{ error: <value> }\\` that may contain an optional \\`meta\\` property.\n Object returned was:`, result);\n }\n }\n if (result.error) throw new HandledError(result.error, result.meta);\n const transformedResponse = await transformResponse(result.data, result.meta, finalQueryArg);\n return {\n ...result,\n data: transformedResponse\n };\n }\n if (arg.type === 'query' && 'infiniteQueryOptions' in endpointDefinition) {\n // This is an infinite query endpoint\n const {\n infiniteQueryOptions\n } = endpointDefinition;\n\n // Runtime checks should guarantee this is a positive number if provided\n const {\n maxPages = Infinity\n } = infiniteQueryOptions;\n let result: QueryReturnValue;\n\n // Start by looking up the existing InfiniteData value from state,\n // falling back to an empty value if it doesn't exist yet\n const blankData = {\n pages: [],\n pageParams: []\n };\n const cachedData = selectors.selectQueryEntry(getState(), arg.queryCacheKey)?.data as InfiniteData<unknown, unknown> | undefined;\n\n // When the arg changes or the user forces a refetch,\n // we don't include the `direction` flag. This lets us distinguish\n // between actually refetching with a forced query, vs just fetching\n // the next page.\n const isForcedQueryNeedingRefetch =\n // arg.forceRefetch\n isForcedQuery(arg, getState()) && !(arg as InfiniteQueryThunkArg<any>).direction;\n const existingData = (isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData) as InfiniteData<unknown, unknown>;\n\n // If the thunk specified a direction and we do have at least one page,\n // fetch the next or previous page\n if ('direction' in arg && arg.direction && existingData.pages.length) {\n const previous = arg.direction === 'backward';\n const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;\n const param = pageParamFn(infiniteQueryOptions, existingData);\n result = await fetchPage(existingData, param, maxPages, previous);\n } else {\n // Otherwise, fetch the first page and then any remaining pages\n\n const {\n initialPageParam = infiniteQueryOptions.initialPageParam\n } = arg as InfiniteQueryThunkArg<any>;\n\n // If we're doing a refetch, we should start from\n // the first page we have cached.\n // Otherwise, we should start from the initialPageParam\n const cachedPageParams = cachedData?.pageParams ?? [];\n const firstPageParam = cachedPageParams[0] ?? initialPageParam;\n const totalPages = cachedPageParams.length;\n\n // Fetch first page\n result = await fetchPage(existingData, firstPageParam, maxPages);\n if (forceQueryFn) {\n // HACK `upsertQueryData` expects the user to pass in the `{pages, pageParams}` structure,\n // but `fetchPage` treats that as `pages[0]`. We have to manually un-nest it.\n result = {\n data: (result.data as InfiniteData<unknown, unknown>).pages[0]\n } as QueryReturnValue;\n }\n\n // Fetch remaining pages\n for (let i = 1; i < totalPages; i++) {\n const param = getNextPageParam(infiniteQueryOptions, result.data as InfiniteData<unknown, unknown>);\n result = await fetchPage(result.data as InfiniteData<unknown, unknown>, param, maxPages);\n }\n }\n finalQueryReturnValue = result;\n } else {\n // Non-infinite endpoint. Just run the one request.\n finalQueryReturnValue = await executeRequest(arg.originalArgs);\n }\n\n // console.log('Final result: ', transformedData)\n return fulfillWithValue(finalQueryReturnValue.data, addShouldAutoBatch({\n fulfilledTimeStamp: Date.now(),\n baseQueryMeta: finalQueryReturnValue.meta\n }));\n } catch (error) {\n let catchedError = error;\n if (catchedError instanceof HandledError) {\n let transformErrorResponse: TransformCallback = getTransformCallbackForEndpoint(endpointDefinition, 'transformErrorResponse');\n try {\n return rejectWithValue(await transformErrorResponse(catchedError.value, catchedError.meta, arg.originalArgs), addShouldAutoBatch({\n baseQueryMeta: catchedError.meta\n }));\n } catch (e) {\n catchedError = e;\n }\n }\n if (typeof process !== 'undefined' && process.env.NODE_ENV !== 'production') {\n console.error(`An unhandled error occurred processing a request for the endpoint \"${arg.endpointName}\".\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`, catchedError);\n } else {\n console.error(catchedError);\n }\n throw catchedError;\n }\n };\n function isForcedQuery(arg: QueryThunkArg, state: RootState<any, string, ReducerPath>) {\n const requestState = selectors.selectQueryEntry(state, arg.queryCacheKey);\n const baseFetchOnMountOrArgChange = selectors.selectConfig(state).refetchOnMountOrArgChange;\n const fulfilledVal = requestState?.fulfilledTimeStamp;\n const refetchVal = arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange);\n if (refetchVal) {\n // Return if it's true or compare the dates because it must be a number\n return refetchVal === true || (Number(new Date()) - Number(fulfilledVal)) / 1000 >= refetchVal;\n }\n return false;\n }\n const createQueryThunk = <ThunkArgType extends QueryThunkArg | InfiniteQueryThunkArg<any>,>() => {\n const generatedQueryThunk = createAsyncThunk<ThunkResult, ThunkArgType, ThunkApiMetaConfig & {\n state: RootState<any, string, ReducerPath>;\n }>(`${reducerPath}/executeQuery`, executeEndpoint, {\n getPendingMeta({\n arg\n }) {\n const endpointDefinition = endpointDefinitions[arg.endpointName];\n return addShouldAutoBatch({\n startedTimeStamp: Date.now(),\n ...(isInfiniteQueryDefinition(endpointDefinition) ? {\n direction: (arg as InfiniteQueryThunkArg<any>).direction\n } : {})\n });\n },\n condition(queryThunkArg, {\n getState\n }) {\n const state = getState();\n const requestState = selectors.selectQueryEntry(state, queryThunkArg.queryCacheKey);\n const fulfilledVal = requestState?.fulfilledTimeStamp;\n const currentArg = queryThunkArg.originalArgs;\n const previousArg = requestState?.originalArgs;\n const endpointDefinition = endpointDefinitions[queryThunkArg.endpointName];\n const direction = (queryThunkArg as InfiniteQueryThunkArg<any>).direction;\n\n // Order of these checks matters.\n // In order for `upsertQueryData` to successfully run while an existing request is in flight,\n /// we have to check for that first, otherwise `queryThunk` will bail out and not run at all.\n if (isUpsertQuery(queryThunkArg)) {\n return true;\n }\n\n // Don't retry a request that's currently in-flight\n if (requestState?.status === 'pending') {\n return false;\n }\n\n // if this is forced, continue\n if (isForcedQuery(queryThunkArg, state)) {\n return true;\n }\n if (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({\n currentArg,\n previousArg,\n endpointState: requestState,\n state\n })) {\n return true;\n }\n\n // Pull from the cache unless we explicitly force refetch or qualify based on time\n if (fulfilledVal && !direction) {\n // Value is cached and we didn't specify to refresh, skip it.\n return false;\n }\n return true;\n },\n dispatchConditionRejection: true\n });\n return generatedQueryThunk;\n };\n const queryThunk = createQueryThunk<QueryThunkArg>();\n const infiniteQueryThunk = createQueryThunk<InfiniteQueryThunkArg<any>>();\n const mutationThunk = createAsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig & {\n state: RootState<any, string, ReducerPath>;\n }>(`${reducerPath}/executeMutation`, executeEndpoint, {\n getPendingMeta() {\n return addShouldAutoBatch({\n startedTimeStamp: Date.now()\n });\n }\n });\n const hasTheForce = (options: any): options is {\n force: boolean;\n } => 'force' in options;\n const hasMaxAge = (options: any): options is {\n ifOlderThan: false | number;\n } => 'ifOlderThan' in options;\n const prefetch = <EndpointName extends QueryKeys<Definitions>,>(endpointName: EndpointName, arg: any, options: PrefetchOptions): ThunkAction<void, any, any, UnknownAction> => (dispatch: ThunkDispatch<any, any, any>, getState: () => any) => {\n const force = hasTheForce(options) && options.force;\n const maxAge = hasMaxAge(options) && options.ifOlderThan;\n const queryAction = (force: boolean = true) => {\n const options = {\n forceRefetch: force,\n isPrefetch: true\n };\n return (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).initiate(arg, options);\n };\n const latestStateValue = (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(arg)(getState());\n if (force) {\n dispatch(queryAction());\n } else if (maxAge) {\n const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp;\n if (!lastFulfilledTs) {\n dispatch(queryAction());\n return;\n }\n const shouldRetrigger = (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1000 >= maxAge;\n if (shouldRetrigger) {\n dispatch(queryAction());\n }\n } else {\n // If prefetching with no options, just let it try\n dispatch(queryAction(false));\n }\n };\n function matchesEndpoint(endpointName: string) {\n return (action: any): action is UnknownAction => action?.meta?.arg?.endpointName === endpointName;\n }\n function buildMatchThunkActions<Thunk extends AsyncThunk<any, QueryThunkArg, ThunkApiMetaConfig> | AsyncThunk<any, MutationThunkArg, ThunkApiMetaConfig>>(thunk: Thunk, endpointName: string) {\n return {\n matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),\n matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),\n matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))\n } as Matchers<Thunk, any>;\n }\n return {\n queryThunk,\n mutationThunk,\n infiniteQueryThunk,\n prefetch,\n updateQueryData,\n upsertQueryData,\n patchQueryData,\n buildMatchThunkActions\n };\n}\nexport function getNextPageParam(options: InfiniteQueryConfigOptions<unknown, unknown>, {\n pages,\n pageParams\n}: InfiniteData<unknown, unknown>): unknown | undefined {\n const lastIndex = pages.length - 1;\n return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams);\n}\nexport function getPreviousPageParam(options: InfiniteQueryConfigOptions<unknown, unknown>, {\n pages,\n pageParams\n}: InfiniteData<unknown, unknown>): unknown | undefined {\n return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams);\n}\nexport function calculateProvidedByThunk(action: UnwrapPromise<ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<MutationThunk>>>, type: 'providesTags' | 'invalidatesTags', endpointDefinitions: EndpointDefinitions, assertTagType: AssertTagTypes) {\n return calculateProvidedBy(endpointDefinitions[action.meta.arg.endpointName][type], isFulfilled(action) ? action.payload : undefined, isRejectedWithValue(action) ? action.payload : undefined, action.meta.arg.originalArgs, 'baseQueryMeta' in action.meta ? action.meta.baseQueryMeta : undefined, assertTagType);\n}","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { AsyncThunkAction, SafePromise, SerializedError, ThunkAction, UnknownAction } from '@reduxjs/toolkit';\nimport type { Dispatch } from 'redux';\nimport { asSafePromise } from '../../tsHelpers';\nimport type { Api, ApiContext } from '../apiTypes';\nimport type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport { isQueryDefinition, type EndpointDefinition, type EndpointDefinitions, type InfiniteQueryArgFrom, type InfiniteQueryDefinition, type MutationDefinition, type PageParamFrom, type QueryArgFrom, type QueryDefinition, type ResultTypeFrom } from '../endpointDefinitions';\nimport { countObjectKeys, getOrInsert, isNotNullish } from '../utils';\nimport type { InfiniteData, InfiniteQueryConfigOptions, InfiniteQueryDirection, SubscriptionOptions } from './apiState';\nimport type { InfiniteQueryResultSelectorResult, QueryResultSelectorResult } from './buildSelectors';\nimport type { InfiniteQueryThunk, InfiniteQueryThunkArg, MutationThunk, QueryThunk, QueryThunkArg, ThunkApiMetaConfig } from './buildThunks';\nimport type { ApiEndpointQuery } from './module';\nexport type BuildInitiateApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>> = {\n initiate: StartQueryActionCreator<Definition>;\n};\nexport type BuildInitiateApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {\n initiate: StartInfiniteQueryActionCreator<Definition>;\n};\nexport type BuildInitiateApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>> = {\n initiate: StartMutationActionCreator<Definition>;\n};\nexport const forceQueryFnSymbol = Symbol('forceQueryFn');\nexport const isUpsertQuery = (arg: QueryThunkArg) => typeof arg[forceQueryFnSymbol] === 'function';\nexport type StartQueryActionCreatorOptions = {\n subscribe?: boolean;\n forceRefetch?: boolean | number;\n subscriptionOptions?: SubscriptionOptions;\n [forceQueryFnSymbol]?: () => QueryReturnValue;\n};\nexport type StartInfiniteQueryActionCreatorOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>> = StartQueryActionCreatorOptions & {\n direction?: InfiniteQueryDirection;\n param?: unknown;\n} & Partial<Pick<Partial<InfiniteQueryConfigOptions<ResultTypeFrom<D>, PageParamFrom<D>>>, 'initialPageParam'>>;\ntype AnyQueryActionCreator<D extends EndpointDefinition<any, any, any, any>> = (arg: any, options?: StartQueryActionCreatorOptions) => ThunkAction<AnyActionCreatorResult, any, any, UnknownAction>;\ntype StartQueryActionCreator<D extends QueryDefinition<any, any, any, any, any>> = (arg: QueryArgFrom<D>, options?: StartQueryActionCreatorOptions) => ThunkAction<QueryActionCreatorResult<D>, any, any, UnknownAction>;\nexport type StartInfiniteQueryActionCreator<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D>, options?: StartInfiniteQueryActionCreatorOptions<D>) => ThunkAction<InfiniteQueryActionCreatorResult<D>, any, any, UnknownAction>;\ntype QueryActionCreatorFields = {\n requestId: string;\n subscriptionOptions: SubscriptionOptions | undefined;\n abort(): void;\n unsubscribe(): void;\n updateSubscriptionOptions(options: SubscriptionOptions): void;\n queryCacheKey: string;\n};\ntype AnyActionCreatorResult = SafePromise<any> & QueryActionCreatorFields & {\n arg: any;\n unwrap(): Promise<any>;\n refetch(): AnyActionCreatorResult;\n};\nexport type QueryActionCreatorResult<D extends QueryDefinition<any, any, any, any>> = SafePromise<QueryResultSelectorResult<D>> & QueryActionCreatorFields & {\n arg: QueryArgFrom<D>;\n unwrap(): Promise<ResultTypeFrom<D>>;\n refetch(): QueryActionCreatorResult<D>;\n};\nexport type InfiniteQueryActionCreatorResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = SafePromise<InfiniteQueryResultSelectorResult<D>> & QueryActionCreatorFields & {\n arg: InfiniteQueryArgFrom<D>;\n unwrap(): Promise<InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>>;\n refetch(): InfiniteQueryActionCreatorResult<D>;\n};\ntype StartMutationActionCreator<D extends MutationDefinition<any, any, any, any>> = (arg: QueryArgFrom<D>, options?: {\n /**\n * If this mutation should be tracked in the store.\n * If you just want to manually trigger this mutation using `dispatch` and don't care about the\n * result, state & potential errors being held in store, you can set this to false.\n * (defaults to `true`)\n */\n track?: boolean;\n fixedCacheKey?: string;\n}) => ThunkAction<MutationActionCreatorResult<D>, any, any, UnknownAction>;\nexport type MutationActionCreatorResult<D extends MutationDefinition<any, any, any, any>> = SafePromise<{\n data: ResultTypeFrom<D>;\n error?: undefined;\n} | {\n data?: undefined;\n error: Exclude<BaseQueryError<D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQuery : never>, undefined> | SerializedError;\n}> & {\n /** @internal */\n arg: {\n /**\n * The name of the given endpoint for the mutation\n */\n endpointName: string;\n /**\n * The original arguments supplied to the mutation call\n */\n originalArgs: QueryArgFrom<D>;\n /**\n * Whether the mutation is being tracked in the store.\n */\n track?: boolean;\n fixedCacheKey?: string;\n };\n /**\n * A unique string generated for the request sequence\n */\n requestId: string;\n\n /**\n * A method to cancel the mutation promise. Note that this is not intended to prevent the mutation\n * that was fired off from reaching the server, but only to assist in handling the response.\n *\n * Calling `abort()` prior to the promise resolving will force it to reach the error state with\n * the serialized error:\n * `{ name: 'AbortError', message: 'Aborted' }`\n *\n * @example\n * ```ts\n * const [updateUser] = useUpdateUserMutation();\n *\n * useEffect(() => {\n * const promise = updateUser(id);\n * promise\n * .unwrap()\n * .catch((err) => {\n * if (err.name === 'AbortError') return;\n * // else handle the unexpected error\n * })\n *\n * return () => {\n * promise.abort();\n * }\n * }, [id, updateUser])\n * ```\n */\n abort(): void;\n /**\n * Unwraps a mutation call to provide the raw response/error.\n *\n * @remarks\n * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\n *\n * @example\n * ```ts\n * // codeblock-meta title=\"Using .unwrap\"\n * addPost({ id: 1, name: 'Example' })\n * .unwrap()\n * .then((payload) => console.log('fulfilled', payload))\n * .catch((error) => console.error('rejected', error));\n * ```\n *\n * @example\n * ```ts\n * // codeblock-meta title=\"Using .unwrap with async await\"\n * try {\n * const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\n * console.log('fulfilled', payload)\n * } catch (error) {\n * console.error('rejected', error);\n * }\n * ```\n */\n unwrap(): Promise<ResultTypeFrom<D>>;\n /**\n * A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.\n The value returned by the hook will reset to `isUninitialized` afterwards.\n */\n reset(): void;\n};\nexport function buildInitiate({\n serializeQueryArgs,\n queryThunk,\n infiniteQueryThunk,\n mutationThunk,\n api,\n context\n}: {\n serializeQueryArgs: InternalSerializeQueryArgs;\n queryThunk: QueryThunk;\n infiniteQueryThunk: InfiniteQueryThunk<any>;\n mutationThunk: MutationThunk;\n api: Api<any, EndpointDefinitions, any, any>;\n context: ApiContext<EndpointDefinitions>;\n}) {\n const runningQueries: Map<Dispatch, Record<string, QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any> | undefined>> = new Map();\n const runningMutations: Map<Dispatch, Record<string, MutationActionCreatorResult<any> | undefined>> = new Map();\n const {\n unsubscribeQueryResult,\n removeMutationResult,\n updateSubscriptionOptions\n } = api.internalActions;\n return {\n buildInitiateQuery,\n buildInitiateInfiniteQuery,\n buildInitiateMutation,\n getRunningQueryThunk,\n getRunningMutationThunk,\n getRunningQueriesThunk,\n getRunningMutationsThunk\n };\n function getRunningQueryThunk(endpointName: string, queryArgs: any) {\n return (dispatch: Dispatch) => {\n const endpointDefinition = context.endpointDefinitions[endpointName];\n const queryCacheKey = serializeQueryArgs({\n queryArgs,\n endpointDefinition,\n endpointName\n });\n return runningQueries.get(dispatch)?.[queryCacheKey] as QueryActionCreatorResult<never> | InfiniteQueryActionCreatorResult<never> | undefined;\n };\n }\n function getRunningMutationThunk(\n /**\n * this is only here to allow TS to infer the result type by input value\n * we could use it to validate the result, but it's probably not necessary\n */\n _endpointName: string, fixedCacheKeyOrRequestId: string) {\n return (dispatch: Dispatch) => {\n return runningMutations.get(dispatch)?.[fixedCacheKeyOrRequestId] as MutationActionCreatorResult<never> | undefined;\n };\n }\n function getRunningQueriesThunk() {\n return (dispatch: Dispatch) => Object.values(runningQueries.get(dispatch) || {}).filter(isNotNullish);\n }\n function getRunningMutationsThunk() {\n return (dispatch: Dispatch) => Object.values(runningMutations.get(dispatch) || {}).filter(isNotNullish);\n }\n function middlewareWarning(dispatch: Dispatch) {\n if (process.env.NODE_ENV !== 'production') {\n if ((middlewareWarning as any).triggered) return;\n const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());\n (middlewareWarning as any).triggered = true;\n\n // The RTKQ middleware should return the internal state object,\n // but it should _not_ be the action object.\n if (typeof returnedValue !== 'object' || typeof returnedValue?.type === 'string') {\n // Otherwise, must not have been added\n throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(34) : `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\nYou must add the middleware for RTK-Query to function correctly!`);\n }\n }\n }\n function buildInitiateAnyQuery<T extends 'query' | 'infiniteQuery'>(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any> | InfiniteQueryDefinition<any, any, any, any, any>) {\n const queryAction: AnyQueryActionCreator<any> = (arg, {\n subscribe = true,\n forceRefetch,\n subscriptionOptions,\n [forceQueryFnSymbol]: forceQueryFn,\n ...rest\n } = {}) => (dispatch, getState) => {\n const queryCacheKey = serializeQueryArgs({\n queryArgs: arg,\n endpointDefinition,\n endpointName\n });\n let thunk: AsyncThunkAction<unknown, QueryThunkArg, ThunkApiMetaConfig>;\n const commonThunkArgs = {\n ...rest,\n type: 'query' as const,\n subscribe,\n forceRefetch: forceRefetch,\n subscriptionOptions,\n endpointName,\n originalArgs: arg,\n queryCacheKey,\n [forceQueryFnSymbol]: forceQueryFn\n };\n if (isQueryDefinition(endpointDefinition)) {\n thunk = queryThunk(commonThunkArgs);\n } else {\n const {\n direction,\n initialPageParam\n } = rest as Pick<InfiniteQueryThunkArg<any>, 'direction' | 'initialPageParam'>;\n thunk = infiniteQueryThunk({\n ...(commonThunkArgs as InfiniteQueryThunkArg<any>),\n // Supply these even if undefined. This helps with a field existence\n // check over in `buildSlice.ts`\n direction,\n initialPageParam\n });\n }\n const selector = (api.endpoints[endpointName] as ApiEndpointQuery<any, any>).select(arg);\n const thunkResult = dispatch(thunk);\n const stateAfter = selector(getState());\n middlewareWarning(dispatch);\n const {\n requestId,\n abort\n } = thunkResult;\n const skippedSynchronously = stateAfter.requestId !== requestId;\n const runningQuery = runningQueries.get(dispatch)?.[queryCacheKey];\n const selectFromState = () => selector(getState());\n const statePromise: AnyActionCreatorResult = Object.assign((forceQueryFn ?\n // a query has been forced (upsertQueryData)\n // -> we want to resolve it once data has been written with the data that will be written\n thunkResult.then(selectFromState) : skippedSynchronously && !runningQuery ?\n // a query has been skipped due to a condition and we do not have any currently running query\n // -> we want to resolve it immediately with the current data\n Promise.resolve(stateAfter) :\n // query just started or one is already in flight\n // -> wait for the running query, then resolve with data from after that\n Promise.all([runningQuery, thunkResult]).then(selectFromState)) as SafePromise<any>, {\n arg,\n requestId,\n subscriptionOptions,\n queryCacheKey,\n abort,\n async unwrap() {\n const result = await statePromise;\n if (result.isError) {\n throw result.error;\n }\n return result.data;\n },\n refetch: () => dispatch(queryAction(arg, {\n subscribe: false,\n forceRefetch: true\n })),\n unsubscribe() {\n if (subscribe) dispatch(unsubscribeQueryResult({\n queryCacheKey,\n requestId\n }));\n },\n updateSubscriptionOptions(options: SubscriptionOptions) {\n statePromise.subscriptionOptions = options;\n dispatch(updateSubscriptionOptions({\n endpointName,\n requestId,\n queryCacheKey,\n options\n }));\n }\n });\n if (!runningQuery && !skippedSynchronously && !forceQueryFn) {\n const running = getOrInsert(runningQueries, dispatch, {});\n running[queryCacheKey] = statePromise;\n statePromise.then(() => {\n delete running[queryCacheKey];\n if (!countObjectKeys(running)) {\n runningQueries.delete(dispatch);\n }\n });\n }\n return statePromise;\n };\n return queryAction;\n }\n function buildInitiateQuery(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) {\n const queryAction: StartQueryActionCreator<any> = buildInitiateAnyQuery(endpointName, endpointDefinition);\n return queryAction;\n }\n function buildInitiateInfiniteQuery(endpointName: string, endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>) {\n const infiniteQueryAction: StartInfiniteQueryActionCreator<any> = buildInitiateAnyQuery(endpointName, endpointDefinition);\n return infiniteQueryAction;\n }\n function buildInitiateMutation(endpointName: string): StartMutationActionCreator<any> {\n return (arg, {\n track = true,\n fixedCacheKey\n } = {}) => (dispatch, getState) => {\n const thunk = mutationThunk({\n type: 'mutation',\n endpointName,\n originalArgs: arg,\n track,\n fixedCacheKey\n });\n const thunkResult = dispatch(thunk);\n middlewareWarning(dispatch);\n const {\n requestId,\n abort,\n unwrap\n } = thunkResult;\n const returnValuePromise = asSafePromise(thunkResult.unwrap().then(data => ({\n data\n })), error => ({\n error\n }));\n const reset = () => {\n dispatch(removeMutationResult({\n requestId,\n fixedCacheKey\n }));\n };\n const ret = Object.assign(returnValuePromise, {\n arg: thunkResult.arg,\n requestId,\n abort,\n unwrap,\n reset\n });\n const running = runningMutations.get(dispatch) || {};\n runningMutations.set(dispatch, running);\n running[requestId] = ret;\n ret.then(() => {\n delete running[requestId];\n if (!countObjectKeys(running)) {\n runningMutations.delete(dispatch);\n }\n });\n if (fixedCacheKey) {\n running[fixedCacheKey] = ret;\n ret.then(() => {\n if (running[fixedCacheKey] === ret) {\n delete running[fixedCacheKey];\n if (!countObjectKeys(running)) {\n runningMutations.delete(dispatch);\n }\n }\n });\n }\n return ret;\n };\n }\n}","import type { Middleware, StoreEnhancer } from 'redux';\nimport type { Tuple } from './utils';\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>) {\n Object.assign(target, ...args);\n}\n\n/**\n * return True if T is `any`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsAny<T, True, False = never> =\n// test if we are going the left AND right path in the condition\ntrue | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;\n\n/**\n * return True if T is `unknown`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsUnknown<T, True, False = never> = unknown extends T ? IsAny<T, False, True> : False;\nexport type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>;\n\n/**\n * @internal\n */\nexport type IfMaybeUndefined<P, True, False> = [undefined] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IfVoid<P, True, False> = [void] extends [P] ? True : False;\n\n/**\n * @internal\n */\nexport type IsEmptyObj<T, True, False = never> = T extends any ? keyof T extends never ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>> : False : never;\n\n/**\n * returns True if TS version is above 3.5, False if below.\n * uses feature detection to detect TS version >= 3.5\n * * versions below 3.5 will return `{}` for unresolvable interference\n * * versions above will return `unknown`\n *\n * @internal\n */\nexport type AtLeastTS35<True, False> = [True, False][IsUnknown<ReturnType<<T>() => T>, 0, 1>];\n\n/**\n * @internal\n */\nexport type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<IsUnknown<T, True, False>, IsEmptyObj<T, True, IsUnknown<T, True, False>>>;\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;\n\n// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified\nexport type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [infer Head, ...infer Tail] ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]> : Acc;\ntype ExtractDispatchFromMiddlewareTuple<MiddlewareTuple extends readonly any[], Acc extends {}> = MiddlewareTuple extends [infer Head, ...infer Tail] ? ExtractDispatchFromMiddlewareTuple<Tail, Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})> : Acc;\nexport type ExtractDispatchExtensions<M> = M extends Tuple<infer MiddlewareTuple> ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}> : M extends ReadonlyArray<Middleware> ? ExtractDispatchFromMiddlewareTuple<[...M], {}> : never;\ntype ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStoreExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})> : Acc;\nexport type ExtractStoreExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<infer Ext> ? Ext extends {} ? IsAny<Ext, {}, Ext> : {} : {}> : never;\ntype ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple extends readonly any[], Acc extends {}> = EnhancerTuple extends [infer Head, ...infer Tail] ? ExtractStateExtensionsFromEnhancerTuple<Tail, Acc & (Head extends StoreEnhancer<any, infer StateExt> ? IsAny<StateExt, {}, StateExt> : {})> : Acc;\nexport type ExtractStateExtensions<E> = E extends Tuple<infer EnhancerTuple> ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}> : E extends ReadonlyArray<StoreEnhancer> ? UnionToIntersection<E[number] extends StoreEnhancer<any, infer StateExt> ? StateExt extends {} ? IsAny<StateExt, {}, StateExt> : {} : {}> : never;\n\n/**\n * Helper type. Passes T out again, but boxes it in a way that it cannot\n * \"widen\" the type by accident if it is a generic that should be inferred\n * from elsewhere.\n *\n * @internal\n */\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type WithOptionalProp<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\nexport interface TypeGuard<T> {\n (value: any): value is T;\n}\nexport interface HasMatchFunction<T> {\n match: TypeGuard<T>;\n}\nexport const hasMatchFunction = <T,>(v: Matcher<T>): v is HasMatchFunction<T> => {\n return v && typeof (v as HasMatchFunction<T>).match === 'function';\n};\n\n/** @public */\nexport type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>;\n\n/** @public */\nexport type ActionFromMatcher<M extends Matcher<any>> = M extends Matcher<infer T> ? T : never;\nexport type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type Tail<T extends any[]> = T extends [any, ...infer Tail] ? Tail : never;\nexport type UnknownIfNonSpecific<T> = {} extends T ? unknown : T;\n\n/**\n * A Promise that will never reject.\n * @see https://github.com/reduxjs/redux-toolkit/issues/4101\n */\nexport type SafePromise<T> = Promise<T> & {\n __linterBrands: 'SafePromise';\n};\n\n/**\n * Properly wraps a Promise as a {@link SafePromise} with .catch(fallback).\n */\nexport function asSafePromise<Resolved, Rejected>(promise: Promise<Resolved>, fallback: (error: unknown) => Rejected) {\n return promise.catch(fallback) as SafePromise<Resolved | Rejected>;\n}","import type { Action, PayloadAction, UnknownAction } from '@reduxjs/toolkit';\nimport { combineReducers, createAction, createSlice, isAnyOf, isFulfilled, isRejectedWithValue, createNextState, prepareAutoBatched, SHOULD_AUTOBATCH, nanoid } from './rtkImports';\nimport type { QuerySubstateIdentifier, QuerySubState, MutationSubstateIdentifier, MutationSubState, MutationState, QueryState, InvalidationState, Subscribers, QueryCacheKey, SubscriptionState, ConfigState, QueryKeys, InfiniteQuerySubState, InfiniteQueryDirection } from './apiState';\nimport { QueryStatus } from './apiState';\nimport type { AllQueryKeys, QueryArgFromAnyQueryDefinition, DataFromAnyQueryDefinition, InfiniteQueryThunk, MutationThunk, QueryThunk, QueryThunkArg, RejectedAction } from './buildThunks';\nimport { calculateProvidedByThunk } from './buildThunks';\nimport { isInfiniteQueryDefinition, type AssertTagTypes, type DefinitionType, type EndpointDefinitions, type FullTagDescription, type QueryArgFrom, type QueryDefinition, type ResultTypeFrom } from '../endpointDefinitions';\nimport type { Patch } from 'immer';\nimport { isDraft } from 'immer';\nimport { applyPatches, original } from 'immer';\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners';\nimport { isDocumentVisible, isOnline, copyWithStructuralSharing } from '../utils';\nimport type { ApiContext } from '../apiTypes';\nimport { isUpsertQuery } from './buildInitiate';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\n\n/**\n * A typesafe single entry to be upserted into the cache\n */\nexport type NormalizedQueryUpsertEntry<Definitions extends EndpointDefinitions, EndpointName extends AllQueryKeys<Definitions>> = {\n endpointName: EndpointName;\n arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>;\n value: DataFromAnyQueryDefinition<Definitions, EndpointName>;\n};\n\n/**\n * The internal version that is not typesafe since we can't carry the generics through `createSlice`\n */\ntype NormalizedQueryUpsertEntryPayload = {\n endpointName: string;\n arg: unknown;\n value: unknown;\n};\nexport type ProcessedQueryUpsertEntry = {\n queryDescription: QueryThunkArg;\n value: unknown;\n};\n\n/**\n * A typesafe representation of a util action creator that accepts cache entry descriptions to upsert\n */\nexport type UpsertEntries<Definitions extends EndpointDefinitions> = (<EndpointNames extends Array<AllQueryKeys<Definitions>>>(entries: [...{ [I in keyof EndpointNames]: NormalizedQueryUpsertEntry<Definitions, EndpointNames[I]> }]) => PayloadAction<NormalizedQueryUpsertEntryPayload[]>) & {\n match: (action: unknown) => action is PayloadAction<NormalizedQueryUpsertEntryPayload[]>;\n};\nfunction updateQuerySubstateIfExists(state: QueryState<any>, queryCacheKey: QueryCacheKey, update: (substate: QuerySubState<any> | InfiniteQuerySubState<any>) => void) {\n const substate = state[queryCacheKey];\n if (substate) {\n update(substate);\n }\n}\nexport function getMutationCacheKey(id: MutationSubstateIdentifier | {\n requestId: string;\n arg: {\n fixedCacheKey?: string | undefined;\n };\n}): string;\nexport function getMutationCacheKey(id: {\n fixedCacheKey?: string;\n requestId?: string;\n}): string | undefined;\nexport function getMutationCacheKey(id: {\n fixedCacheKey?: string;\n requestId?: string;\n} | MutationSubstateIdentifier | {\n requestId: string;\n arg: {\n fixedCacheKey?: string | undefined;\n };\n}): string | undefined {\n return ('arg' in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId;\n}\nfunction updateMutationSubstateIfExists(state: MutationState<any>, id: MutationSubstateIdentifier | {\n requestId: string;\n arg: {\n fixedCacheKey?: string | undefined;\n };\n}, update: (substate: MutationSubState<any>) => void) {\n const substate = state[getMutationCacheKey(id)];\n if (substate) {\n update(substate);\n }\n}\nconst initialState = {} as any;\nexport function buildSlice({\n reducerPath,\n queryThunk,\n mutationThunk,\n serializeQueryArgs,\n context: {\n endpointDefinitions: definitions,\n apiUid,\n extractRehydrationInfo,\n hasRehydrationInfo\n },\n assertTagType,\n config\n}: {\n reducerPath: string;\n queryThunk: QueryThunk;\n infiniteQueryThunk: InfiniteQueryThunk<any>;\n mutationThunk: MutationThunk;\n serializeQueryArgs: InternalSerializeQueryArgs;\n context: ApiContext<EndpointDefinitions>;\n assertTagType: AssertTagTypes;\n config: Omit<ConfigState<string>, 'online' | 'focused' | 'middlewareRegistered'>;\n}) {\n const resetApiState = createAction(`${reducerPath}/resetApiState`);\n function writePendingCacheEntry(draft: QueryState<any>, arg: QueryThunkArg, upserting: boolean, meta: {\n arg: QueryThunkArg;\n requestId: string;\n // requestStatus: 'pending'\n } & {\n startedTimeStamp: number;\n }) {\n draft[arg.queryCacheKey] ??= {\n status: QueryStatus.uninitialized,\n endpointName: arg.endpointName\n };\n updateQuerySubstateIfExists(draft, arg.queryCacheKey, substate => {\n substate.status = QueryStatus.pending;\n substate.requestId = upserting && substate.requestId ?\n // for `upsertQuery` **updates**, keep the current `requestId`\n substate.requestId :\n // for normal queries or `upsertQuery` **inserts** always update the `requestId`\n meta.requestId;\n if (arg.originalArgs !== undefined) {\n substate.originalArgs = arg.originalArgs;\n }\n substate.startedTimeStamp = meta.startedTimeStamp;\n const endpointDefinition = definitions[meta.arg.endpointName];\n if (isInfiniteQueryDefinition(endpointDefinition) && 'direction' in arg) {\n ;\n (substate as InfiniteQuerySubState<any>).direction = arg.direction as InfiniteQueryDirection;\n }\n });\n }\n function writeFulfilledCacheEntry(draft: QueryState<any>, meta: {\n arg: QueryThunkArg;\n requestId: string;\n } & {\n fulfilledTimeStamp: number;\n baseQueryMeta: unknown;\n }, payload: unknown, upserting: boolean) {\n updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, substate => {\n if (substate.requestId !== meta.requestId && !upserting) return;\n const {\n merge\n } = definitions[meta.arg.endpointName] as QueryDefinition<any, any, any, any>;\n substate.status = QueryStatus.fulfilled;\n if (merge) {\n if (substate.data !== undefined) {\n const {\n fulfilledTimeStamp,\n arg,\n baseQueryMeta,\n requestId\n } = meta;\n // There's existing cache data. Let the user merge it in themselves.\n // We're already inside an Immer-powered reducer, and the user could just mutate `substate.data`\n // themselves inside of `merge()`. But, they might also want to return a new value.\n // Try to let Immer figure that part out, save the result, and assign it to `substate.data`.\n let newData = createNextState(substate.data, draftSubstateData => {\n // As usual with Immer, you can mutate _or_ return inside here, but not both\n return merge(draftSubstateData, payload, {\n arg: arg.originalArgs,\n baseQueryMeta,\n fulfilledTimeStamp,\n requestId\n });\n });\n substate.data = newData;\n } else {\n // Presumably a fresh request. Just cache the response data.\n substate.data = payload;\n }\n } else {\n // Assign or safely update the cache data.\n substate.data = definitions[meta.arg.endpointName].structuralSharing ?? true ? copyWithStructuralSharing(isDraft(substate.data) ? original(substate.data) : substate.data, payload) : payload;\n }\n delete substate.error;\n substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\n });\n }\n const querySlice = createSlice({\n name: `${reducerPath}/queries`,\n initialState: initialState as QueryState<any>,\n reducers: {\n removeQueryResult: {\n reducer(draft, {\n payload: {\n queryCacheKey\n }\n }: PayloadAction<QuerySubstateIdentifier>) {\n delete draft[queryCacheKey];\n },\n prepare: prepareAutoBatched<QuerySubstateIdentifier>()\n },\n cacheEntriesUpserted: {\n reducer(draft, action: PayloadAction<ProcessedQueryUpsertEntry[], string, {\n RTK_autoBatch: boolean;\n requestId: string;\n timestamp: number;\n }>) {\n for (const entry of action.payload) {\n const {\n queryDescription: arg,\n value\n } = entry;\n writePendingCacheEntry(draft, arg, true, {\n arg,\n requestId: action.meta.requestId,\n startedTimeStamp: action.meta.timestamp\n });\n writeFulfilledCacheEntry(draft, {\n arg,\n requestId: action.meta.requestId,\n fulfilledTimeStamp: action.meta.timestamp,\n baseQueryMeta: {}\n }, value,\n // We know we're upserting here\n true);\n }\n },\n prepare: (payload: NormalizedQueryUpsertEntryPayload[]) => {\n const queryDescriptions: ProcessedQueryUpsertEntry[] = payload.map(entry => {\n const {\n endpointName,\n arg,\n value\n } = entry;\n const endpointDefinition = definitions[endpointName];\n const queryDescription: QueryThunkArg = {\n type: 'query',\n endpointName: endpointName,\n originalArgs: entry.arg,\n queryCacheKey: serializeQueryArgs({\n queryArgs: arg,\n endpointDefinition,\n endpointName\n })\n };\n return {\n queryDescription,\n value\n };\n });\n const result = {\n payload: queryDescriptions,\n meta: {\n [SHOULD_AUTOBATCH]: true,\n requestId: nanoid(),\n timestamp: Date.now()\n }\n };\n return result;\n }\n },\n queryResultPatched: {\n reducer(draft, {\n payload: {\n queryCacheKey,\n patches\n }\n }: PayloadAction<QuerySubstateIdentifier & {\n patches: readonly Patch[];\n }>) {\n updateQuerySubstateIfExists(draft, queryCacheKey, substate => {\n substate.data = applyPatches(substate.data as any, patches.concat());\n });\n },\n prepare: prepareAutoBatched<QuerySubstateIdentifier & {\n patches: readonly Patch[];\n }>()\n }\n },\n extraReducers(builder) {\n builder.addCase(queryThunk.pending, (draft, {\n meta,\n meta: {\n arg\n }\n }) => {\n const upserting = isUpsertQuery(arg);\n writePendingCacheEntry(draft, arg, upserting, meta);\n }).addCase(queryThunk.fulfilled, (draft, {\n meta,\n payload\n }) => {\n const upserting = isUpsertQuery(meta.arg);\n writeFulfilledCacheEntry(draft, meta, payload, upserting);\n }).addCase(queryThunk.rejected, (draft, {\n meta: {\n condition,\n arg,\n requestId\n },\n error,\n payload\n }) => {\n updateQuerySubstateIfExists(draft, arg.queryCacheKey, substate => {\n if (condition) {\n // request was aborted due to condition (another query already running)\n } else {\n // request failed\n if (substate.requestId !== requestId) return;\n substate.status = QueryStatus.rejected;\n substate.error = (payload ?? error) as any;\n }\n });\n }).addMatcher(hasRehydrationInfo, (draft, action) => {\n const {\n queries\n } = extractRehydrationInfo(action)!;\n for (const [key, entry] of Object.entries(queries)) {\n if (\n // do not rehydrate entries that were currently in flight.\n entry?.status === QueryStatus.fulfilled || entry?.status === QueryStatus.rejected) {\n draft[key] = entry;\n }\n }\n });\n }\n });\n const mutationSlice = createSlice({\n name: `${reducerPath}/mutations`,\n initialState: initialState as MutationState<any>,\n reducers: {\n removeMutationResult: {\n reducer(draft, {\n payload\n }: PayloadAction<MutationSubstateIdentifier>) {\n const cacheKey = getMutationCacheKey(payload);\n if (cacheKey in draft) {\n delete draft[cacheKey];\n }\n },\n prepare: prepareAutoBatched<MutationSubstateIdentifier>()\n }\n },\n extraReducers(builder) {\n builder.addCase(mutationThunk.pending, (draft, {\n meta,\n meta: {\n requestId,\n arg,\n startedTimeStamp\n }\n }) => {\n if (!arg.track) return;\n draft[getMutationCacheKey(meta)] = {\n requestId,\n status: QueryStatus.pending,\n endpointName: arg.endpointName,\n startedTimeStamp\n };\n }).addCase(mutationThunk.fulfilled, (draft, {\n payload,\n meta\n }) => {\n if (!meta.arg.track) return;\n updateMutationSubstateIfExists(draft, meta, substate => {\n if (substate.requestId !== meta.requestId) return;\n substate.status = QueryStatus.fulfilled;\n substate.data = payload;\n substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;\n });\n }).addCase(mutationThunk.rejected, (draft, {\n payload,\n error,\n meta\n }) => {\n if (!meta.arg.track) return;\n updateMutationSubstateIfExists(draft, meta, substate => {\n if (substate.requestId !== meta.requestId) return;\n substate.status = QueryStatus.rejected;\n substate.error = (payload ?? error) as any;\n });\n }).addMatcher(hasRehydrationInfo, (draft, action) => {\n const {\n mutations\n } = extractRehydrationInfo(action)!;\n for (const [key, entry] of Object.entries(mutations)) {\n if (\n // do not rehydrate entries that were currently in flight.\n (entry?.status === QueryStatus.fulfilled || entry?.status === QueryStatus.rejected) &&\n // only rehydrate endpoints that were persisted using a `fixedCacheKey`\n key !== entry?.requestId) {\n draft[key] = entry;\n }\n }\n });\n }\n });\n const invalidationSlice = createSlice({\n name: `${reducerPath}/invalidation`,\n initialState: initialState as InvalidationState<string>,\n reducers: {\n updateProvidedBy: {\n reducer(draft, action: PayloadAction<{\n queryCacheKey: QueryCacheKey;\n providedTags: readonly FullTagDescription<string>[];\n }>) {\n const {\n queryCacheKey,\n providedTags\n } = action.payload;\n for (const tagTypeSubscriptions of Object.values(draft)) {\n for (const idSubscriptions of Object.values(tagTypeSubscriptions)) {\n const foundAt = idSubscriptions.indexOf(queryCacheKey);\n if (foundAt !== -1) {\n idSubscriptions.splice(foundAt, 1);\n }\n }\n }\n for (const {\n type,\n id\n } of providedTags) {\n const subscribedQueries = (draft[type] ??= {})[id || '__internal_without_id'] ??= [];\n const alreadySubscribed = subscribedQueries.includes(queryCacheKey);\n if (!alreadySubscribed) {\n subscribedQueries.push(queryCacheKey);\n }\n }\n },\n prepare: prepareAutoBatched<{\n queryCacheKey: QueryCacheKey;\n providedTags: readonly FullTagDescription<string>[];\n }>()\n }\n },\n extraReducers(builder) {\n builder.addCase(querySlice.actions.removeQueryResult, (draft, {\n payload: {\n queryCacheKey\n }\n }) => {\n for (const tagTypeSubscriptions of Object.values(draft)) {\n for (const idSubscriptions of Object.values(tagTypeSubscriptions)) {\n const foundAt = idSubscriptions.indexOf(queryCacheKey);\n if (foundAt !== -1) {\n idSubscriptions.splice(foundAt, 1);\n }\n }\n }\n }).addMatcher(hasRehydrationInfo, (draft, action) => {\n const {\n provided\n } = extractRehydrationInfo(action)!;\n for (const [type, incomingTags] of Object.entries(provided)) {\n for (const [id, cacheKeys] of Object.entries(incomingTags)) {\n const subscribedQueries = (draft[type] ??= {})[id || '__internal_without_id'] ??= [];\n for (const queryCacheKey of cacheKeys) {\n const alreadySubscribed = subscribedQueries.includes(queryCacheKey);\n if (!alreadySubscribed) {\n subscribedQueries.push(queryCacheKey);\n }\n }\n }\n }\n }).addMatcher(isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)), (draft, action) => {\n const providedTags = calculateProvidedByThunk(action, 'providesTags', definitions, assertTagType);\n const {\n queryCacheKey\n } = action.meta.arg;\n invalidationSlice.caseReducers.updateProvidedBy(draft, invalidationSlice.actions.updateProvidedBy({\n queryCacheKey,\n providedTags\n }));\n });\n }\n });\n\n // Dummy slice to generate actions\n const subscriptionSlice = createSlice({\n name: `${reducerPath}/subscriptions`,\n initialState: initialState as SubscriptionState,\n reducers: {\n updateSubscriptionOptions(d, a: PayloadAction<{\n endpointName: string;\n requestId: string;\n options: Subscribers[number];\n } & QuerySubstateIdentifier>) {\n // Dummy\n },\n unsubscribeQueryResult(d, a: PayloadAction<{\n requestId: string;\n } & QuerySubstateIdentifier>) {\n // Dummy\n },\n internal_getRTKQSubscriptions() {}\n }\n });\n const internalSubscriptionsSlice = createSlice({\n name: `${reducerPath}/internalSubscriptions`,\n initialState: initialState as SubscriptionState,\n reducers: {\n subscriptionsUpdated: {\n reducer(state, action: PayloadAction<Patch[]>) {\n return applyPatches(state, action.payload);\n },\n prepare: prepareAutoBatched<Patch[]>()\n }\n }\n });\n const configSlice = createSlice({\n name: `${reducerPath}/config`,\n initialState: {\n online: isOnline(),\n focused: isDocumentVisible(),\n middlewareRegistered: false,\n ...config\n } as ConfigState<string>,\n reducers: {\n middlewareRegistered(state, {\n payload\n }: PayloadAction<string>) {\n state.middlewareRegistered = state.middlewareRegistered === 'conflict' || apiUid !== payload ? 'conflict' : true;\n }\n },\n extraReducers: builder => {\n builder.addCase(onOnline, state => {\n state.online = true;\n }).addCase(onOffline, state => {\n state.online = false;\n }).addCase(onFocus, state => {\n state.focused = true;\n }).addCase(onFocusLost, state => {\n state.focused = false;\n })\n // update the state to be a new object to be picked up as a \"state change\"\n // by redux-persist's `autoMergeLevel2`\n .addMatcher(hasRehydrationInfo, draft => ({\n ...draft\n }));\n }\n });\n const combinedReducer = combineReducers({\n queries: querySlice.reducer,\n mutations: mutationSlice.reducer,\n provided: invalidationSlice.reducer,\n subscriptions: internalSubscriptionsSlice.reducer,\n config: configSlice.reducer\n });\n const reducer: typeof combinedReducer = (state, action) => combinedReducer(resetApiState.match(action) ? undefined : state, action);\n const actions = {\n ...configSlice.actions,\n ...querySlice.actions,\n ...subscriptionSlice.actions,\n ...internalSubscriptionsSlice.actions,\n ...mutationSlice.actions,\n ...invalidationSlice.actions,\n resetApiState\n };\n return {\n reducer,\n actions\n };\n}\nexport type SliceActions = ReturnType<typeof buildSlice>['actions'];","import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { EndpointDefinition, EndpointDefinitions, InfiniteQueryArgFrom, InfiniteQueryDefinition, MutationDefinition, QueryArgFrom, QueryDefinition, ReducerPathFrom, TagDescription, TagTypesFrom } from '../endpointDefinitions';\nimport { expandTagDescription } from '../endpointDefinitions';\nimport { flatten, isNotNullish } from '../utils';\nimport type { InfiniteData, InfiniteQueryConfigOptions, InfiniteQuerySubState, MutationSubState, QueryCacheKey, QueryKeys, QueryState, QuerySubState, RequestStatusFlags, RootState as _RootState } from './apiState';\nimport { QueryStatus, getRequestStatusFlags } from './apiState';\nimport { getMutationCacheKey } from './buildSlice';\nimport type { createSelector as _createSelector } from './rtkImports';\nimport { createNextState } from './rtkImports';\nimport { getNextPageParam, getPreviousPageParam } from './buildThunks';\nexport type SkipToken = typeof skipToken;\n/**\n * Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`\n * instead of the query argument to get the same effect as if setting\n * `skip: true` in the query options.\n *\n * Useful for scenarios where a query should be skipped when `arg` is `undefined`\n * and TypeScript complains about it because `arg` is not allowed to be passed\n * in as `undefined`, such as\n *\n * ```ts\n * // codeblock-meta title=\"will error if the query argument is not allowed to be undefined\" no-transpile\n * useSomeQuery(arg, { skip: !!arg })\n * ```\n *\n * ```ts\n * // codeblock-meta title=\"using skipToken instead\" no-transpile\n * useSomeQuery(arg ?? skipToken)\n * ```\n *\n * If passed directly into a query or mutation selector, that selector will always\n * return an uninitialized state.\n */\nexport const skipToken = /* @__PURE__ */Symbol.for('RTKQ/skipToken');\nexport type BuildSelectorsApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n select: QueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\nexport type BuildSelectorsApiEndpointInfiniteQuery<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n select: InfiniteQueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\nexport type BuildSelectorsApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> = {\n select: MutationResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;\n};\ntype QueryResultSelectorFactory<Definition extends QueryDefinition<any, any, any, any>, RootState> = (queryArg: QueryArgFrom<Definition> | SkipToken) => (state: RootState) => QueryResultSelectorResult<Definition>;\nexport type QueryResultSelectorResult<Definition extends QueryDefinition<any, any, any, any>> = QuerySubState<Definition> & RequestStatusFlags;\ntype InfiniteQueryResultSelectorFactory<Definition extends InfiniteQueryDefinition<any, any, any, any, any>, RootState> = (queryArg: InfiniteQueryArgFrom<Definition> | SkipToken) => (state: RootState) => InfiniteQueryResultSelectorResult<Definition>;\nexport type InfiniteQueryResultFlags = {\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n isFetchingNextPage: boolean;\n isFetchingPreviousPage: boolean;\n isFetchNextPageError: boolean;\n isFetchPreviousPageError: boolean;\n};\nexport type InfiniteQueryResultSelectorResult<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = InfiniteQuerySubState<Definition> & RequestStatusFlags & InfiniteQueryResultFlags;\ntype MutationResultSelectorFactory<Definition extends MutationDefinition<any, any, any, any>, RootState> = (requestId: string | {\n requestId: string | undefined;\n fixedCacheKey: string | undefined;\n} | SkipToken) => (state: RootState) => MutationResultSelectorResult<Definition>;\nexport type MutationResultSelectorResult<Definition extends MutationDefinition<any, any, any, any>> = MutationSubState<Definition> & RequestStatusFlags;\nconst initialSubState: QuerySubState<any> = {\n status: QueryStatus.uninitialized as const\n};\n\n// abuse immer to freeze default states\nconst defaultQuerySubState = /* @__PURE__ */createNextState(initialSubState, () => {});\nconst defaultMutationSubState = /* @__PURE__ */createNextState(initialSubState as MutationSubState<any>, () => {});\nexport type AllSelectors = ReturnType<typeof buildSelectors>;\nexport function buildSelectors<Definitions extends EndpointDefinitions, ReducerPath extends string>({\n serializeQueryArgs,\n reducerPath,\n createSelector\n}: {\n serializeQueryArgs: InternalSerializeQueryArgs;\n reducerPath: ReducerPath;\n createSelector: typeof _createSelector;\n}) {\n type RootState = _RootState<Definitions, string, string>;\n const selectSkippedQuery = (state: RootState) => defaultQuerySubState;\n const selectSkippedMutation = (state: RootState) => defaultMutationSubState;\n return {\n buildQuerySelector,\n buildInfiniteQuerySelector,\n buildMutationSelector,\n selectInvalidatedBy,\n selectCachedArgsForQuery,\n selectApiState,\n selectQueries,\n selectMutations,\n selectQueryEntry,\n selectConfig\n };\n function withRequestFlags<T extends {\n status: QueryStatus;\n }>(substate: T): T & RequestStatusFlags {\n return {\n ...substate,\n ...getRequestStatusFlags(substate.status)\n };\n }\n function selectApiState(rootState: RootState) {\n const state = rootState[reducerPath];\n if (process.env.NODE_ENV !== 'production') {\n if (!state) {\n if ((selectApiState as any).triggered) return state;\n (selectApiState as any).triggered = true;\n console.error(`Error: No data found at \\`state.${reducerPath}\\`. Did you forget to add the reducer to the store?`);\n }\n }\n return state;\n }\n function selectQueries(rootState: RootState) {\n return selectApiState(rootState)?.queries;\n }\n function selectQueryEntry(rootState: RootState, cacheKey: QueryCacheKey) {\n return selectQueries(rootState)?.[cacheKey];\n }\n function selectMutations(rootState: RootState) {\n return selectApiState(rootState)?.mutations;\n }\n function selectConfig(rootState: RootState) {\n return selectApiState(rootState)?.config;\n }\n function buildAnyQuerySelector(endpointName: string, endpointDefinition: EndpointDefinition<any, any, any, any>, combiner: <T extends {\n status: QueryStatus;\n }>(substate: T) => T & RequestStatusFlags) {\n return (queryArgs: any) => {\n // Avoid calling serializeQueryArgs if the arg is skipToken\n if (queryArgs === skipToken) {\n return createSelector(selectSkippedQuery, combiner);\n }\n const serializedArgs = serializeQueryArgs({\n queryArgs,\n endpointDefinition,\n endpointName\n });\n const selectQuerySubstate = (state: RootState) => selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState;\n return createSelector(selectQuerySubstate, combiner);\n };\n }\n function buildQuerySelector(endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) {\n return buildAnyQuerySelector(endpointName, endpointDefinition, withRequestFlags) as QueryResultSelectorFactory<any, RootState>;\n }\n function buildInfiniteQuerySelector(endpointName: string, endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>) {\n const {\n infiniteQueryOptions\n } = endpointDefinition;\n function withInfiniteQueryResultFlags<T extends {\n status: QueryStatus;\n }>(substate: T): T & RequestStatusFlags & InfiniteQueryResultFlags {\n const stateWithRequestFlags = {\n ...(substate as InfiniteQuerySubState<any>),\n ...getRequestStatusFlags(substate.status)\n };\n const {\n isLoading,\n isError,\n direction\n } = stateWithRequestFlags;\n const isForward = direction === 'forward';\n const isBackward = direction === 'backward';\n return {\n ...stateWithRequestFlags,\n hasNextPage: getHasNextPage(infiniteQueryOptions, stateWithRequestFlags.data),\n hasPreviousPage: getHasPreviousPage(infiniteQueryOptions, stateWithRequestFlags.data),\n isFetchingNextPage: isLoading && isForward,\n isFetchingPreviousPage: isLoading && isBackward,\n isFetchNextPageError: isError && isForward,\n isFetchPreviousPageError: isError && isBackward\n };\n }\n return buildAnyQuerySelector(endpointName, endpointDefinition, withInfiniteQueryResultFlags) as unknown as InfiniteQueryResultSelectorFactory<any, RootState>;\n }\n function buildMutationSelector() {\n return (id => {\n let mutationId: string | typeof skipToken;\n if (typeof id === 'object') {\n mutationId = getMutationCacheKey(id) ?? skipToken;\n } else {\n mutationId = id;\n }\n const selectMutationSubstate = (state: RootState) => selectApiState(state)?.mutations?.[mutationId as string] ?? defaultMutationSubState;\n const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;\n return createSelector(finalSelectMutationSubstate, withRequestFlags);\n }) as MutationResultSelectorFactory<any, RootState>;\n }\n function selectInvalidatedBy(state: RootState, tags: ReadonlyArray<TagDescription<string> | null | undefined>): Array<{\n endpointName: string;\n originalArgs: any;\n queryCacheKey: QueryCacheKey;\n }> {\n const apiState = state[reducerPath];\n const toInvalidate = new Set<QueryCacheKey>();\n for (const tag of tags.filter(isNotNullish).map(expandTagDescription)) {\n const provided = apiState.provided[tag.type];\n if (!provided) {\n continue;\n }\n let invalidateSubscriptions = (tag.id !== undefined ?\n // id given: invalidate all queries that provide this type & id\n provided[tag.id] :\n // no id: invalidate all queries that provide this type\n flatten(Object.values(provided))) ?? [];\n for (const invalidate of invalidateSubscriptions) {\n toInvalidate.add(invalidate);\n }\n }\n return flatten(Array.from(toInvalidate.values()).map(queryCacheKey => {\n const querySubState = apiState.queries[queryCacheKey];\n return querySubState ? [{\n queryCacheKey,\n endpointName: querySubState.endpointName!,\n originalArgs: querySubState.originalArgs\n }] : [];\n }));\n }\n function selectCachedArgsForQuery<QueryName extends QueryKeys<Definitions>>(state: RootState, queryName: QueryName): Array<QueryArgFrom<Definitions[QueryName]>> {\n return Object.values(selectQueries(state) as QueryState<any>).filter((entry): entry is Exclude<QuerySubState<Definitions[QueryName]>, {\n status: QueryStatus.uninitialized;\n }> => entry?.endpointName === queryName && entry.status !== QueryStatus.uninitialized).map(entry => entry.originalArgs);\n }\n function getHasNextPage(options: InfiniteQueryConfigOptions<any, any>, data?: InfiniteData<unknown, unknown>): boolean {\n if (!data) return false;\n return getNextPageParam(options, data) != null;\n }\n function getHasPreviousPage(options: InfiniteQueryConfigOptions<any, any>, data?: InfiniteData<unknown, unknown>): boolean {\n if (!data || !options.getPreviousPageParam) return false;\n return getPreviousPageParam(options, data) != null;\n }\n}","import { formatProdErrorMessage as _formatProdErrorMessage, formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage3 } from \"@reduxjs/toolkit\";\nimport type { Api, ApiContext, Module, ModuleName } from './apiTypes';\nimport type { CombinedState } from './core/apiState';\nimport type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes';\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs';\nimport type { EndpointBuilder, EndpointDefinitions } from './endpointDefinitions';\nimport { DefinitionType, isInfiniteQueryDefinition, isQueryDefinition } from './endpointDefinitions';\nimport { nanoid } from './core/rtkImports';\nimport type { UnknownAction } from '@reduxjs/toolkit';\nimport type { NoInfer } from './tsHelpers';\nimport { weakMapMemoize } from 'reselect';\nexport interface CreateApiOptions<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never> {\n /**\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.\n *\n * @example\n *\n * ```ts\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * const api = createApi({\n * // highlight-start\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * // highlight-end\n * endpoints: (build) => ({\n * // ...endpoints\n * }),\n * })\n * ```\n */\n baseQuery: BaseQuery;\n /**\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).\n *\n * @example\n *\n * ```ts\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * const api = createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * // highlight-start\n * tagTypes: ['Post', 'User'],\n * // highlight-end\n * endpoints: (build) => ({\n * // ...endpoints\n * }),\n * })\n * ```\n */\n tagTypes?: readonly TagTypes[];\n /**\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'`.\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"apis.js\"\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';\n *\n * const apiOne = createApi({\n * // highlight-start\n * reducerPath: 'apiOne',\n * // highlight-end\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * endpoints: (builder) => ({\n * // ...endpoints\n * }),\n * });\n *\n * const apiTwo = createApi({\n * // highlight-start\n * reducerPath: 'apiTwo',\n * // highlight-end\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * endpoints: (builder) => ({\n * // ...endpoints\n * }),\n * });\n * ```\n */\n reducerPath?: ReducerPath;\n /**\n * Accepts a custom function if you have a need to change the creation of cache keys for any reason.\n */\n serializeQueryArgs?: SerializeQueryArgs<unknown>;\n /**\n * Endpoints are a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are three endpoint types: [`query`](../../rtk-query/usage/queries), [`infiniteQuery`](../../rtk-query/usage/infinite-queries) and [`mutation`](../../rtk-query/usage/mutations).\n */\n endpoints(build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>): Definitions;\n /**\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.\n *\n * ```ts\n * // codeblock-meta title=\"keepUnusedDataFor example\"\n *\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n * interface Post {\n * id: number\n * name: string\n * }\n * type PostsResponse = Post[]\n *\n * const api = createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * endpoints: (build) => ({\n * getPosts: build.query<PostsResponse, void>({\n * query: () => 'posts',\n * // highlight-start\n * keepUnusedDataFor: 5\n * // highlight-end\n * })\n * })\n * })\n * ```\n */\n keepUnusedDataFor?: number;\n /**\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.\n * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\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.\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.\n *\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n */\n refetchOnMountOrArgChange?: boolean | number;\n /**\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.\n *\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n *\n * Note: requires [`setupListeners`](./setupListeners) to have been called.\n */\n refetchOnFocus?: boolean;\n /**\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.\n *\n * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n *\n * Note: requires [`setupListeners`](./setupListeners) to have been called.\n */\n refetchOnReconnect?: boolean;\n /**\n * Defaults to `'delayed'`. This setting allows you to control when tags are invalidated after a mutation.\n *\n * - `'immediately'`: Queries are invalidated instantly after the mutation finished, even if they are running.\n * If the query provides tags that were invalidated while it ran, it won't be re-fetched.\n * - `'delayed'`: Invalidation only happens after all queries and mutations are settled.\n * This ensures that queries are always invalidated correctly and automatically \"batches\" invalidations of concurrent mutations.\n * Note that if you constantly have some queries (or mutations) running, this can delay tag invalidations indefinitely.\n */\n invalidationBehavior?: 'delayed' | 'immediately';\n /**\n * A function that is passed every dispatched action. If this returns something other than `undefined`,\n * that return value will be used to rehydrate fulfilled & errored queries.\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"next-redux-wrapper rehydration example\"\n * import type { Action, PayloadAction } from '@reduxjs/toolkit'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n * import { HYDRATE } from 'next-redux-wrapper'\n *\n * type RootState = any; // normally inferred from state\n *\n * function isHydrateAction(action: Action): action is PayloadAction<RootState> {\n * return action.type === HYDRATE\n * }\n *\n * export const api = createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n * // highlight-start\n * extractRehydrationInfo(action, { reducerPath }): any {\n * if (isHydrateAction(action)) {\n * return action.payload[reducerPath]\n * }\n * },\n * // highlight-end\n * endpoints: (build) => ({\n * // omitted\n * }),\n * })\n * ```\n */\n extractRehydrationInfo?: (action: UnknownAction, {\n reducerPath\n }: {\n reducerPath: ReducerPath;\n }) => undefined | CombinedState<NoInfer<Definitions>, NoInfer<TagTypes>, NoInfer<ReducerPath>>;\n}\nexport type CreateApi<Modules extends ModuleName> = {\n /**\n * Creates a service to use in your application. Contains only the basic redux logic (the core module).\n *\n * @link https://rtk-query-docs.netlify.app/api/createApi\n */\n <BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never>(options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>;\n};\n\n/**\n * Builds a `createApi` method based on the provided `modules`.\n *\n * @link https://rtk-query-docs.netlify.app/concepts/customizing-create-api\n *\n * @example\n * ```ts\n * const MyContext = React.createContext<ReactReduxContextValue | null>(null);\n * const customCreateApi = buildCreateApi(\n * coreModule(),\n * reactHooksModule({\n * hooks: {\n * useDispatch: createDispatchHook(MyContext),\n * useSelector: createSelectorHook(MyContext),\n * useStore: createStoreHook(MyContext)\n * }\n * })\n * );\n * ```\n *\n * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints\n * @returns A `createApi` method using the provided `modules`.\n */\nexport function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(...modules: Modules): CreateApi<Modules[number]['name']> {\n return function baseCreateApi(options) {\n const extractRehydrationInfo = weakMapMemoize((action: UnknownAction) => options.extractRehydrationInfo?.(action, {\n reducerPath: (options.reducerPath ?? 'api') as any\n }));\n const optionsWithDefaults: CreateApiOptions<any, any, any, any> = {\n reducerPath: 'api',\n keepUnusedDataFor: 60,\n refetchOnMountOrArgChange: false,\n refetchOnFocus: false,\n refetchOnReconnect: false,\n invalidationBehavior: 'delayed',\n ...options,\n extractRehydrationInfo,\n serializeQueryArgs(queryArgsApi) {\n let finalSerializeQueryArgs = defaultSerializeQueryArgs;\n if ('serializeQueryArgs' in queryArgsApi.endpointDefinition) {\n const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs!;\n finalSerializeQueryArgs = queryArgsApi => {\n const initialResult = endpointSQA(queryArgsApi);\n if (typeof initialResult === 'string') {\n // If the user function returned a string, use it as-is\n return initialResult;\n } else {\n // Assume they returned an object (such as a subset of the original\n // query args) or a primitive, and serialize it ourselves\n return defaultSerializeQueryArgs({\n ...queryArgsApi,\n queryArgs: initialResult\n });\n }\n };\n } else if (options.serializeQueryArgs) {\n finalSerializeQueryArgs = options.serializeQueryArgs;\n }\n return finalSerializeQueryArgs(queryArgsApi);\n },\n tagTypes: [...(options.tagTypes || [])]\n };\n const context: ApiContext<EndpointDefinitions> = {\n endpointDefinitions: {},\n batch(fn) {\n // placeholder \"batch\" method to be overridden by plugins, for example with React.unstable_batchedUpdate\n fn();\n },\n apiUid: nanoid(),\n extractRehydrationInfo,\n hasRehydrationInfo: weakMapMemoize(action => extractRehydrationInfo(action) != null)\n };\n const api = {\n injectEndpoints,\n enhanceEndpoints({\n addTagTypes,\n endpoints\n }) {\n if (addTagTypes) {\n for (const eT of addTagTypes) {\n if (!optionsWithDefaults.tagTypes!.includes(eT as any)) {\n ;\n (optionsWithDefaults.tagTypes as any[]).push(eT);\n }\n }\n }\n if (endpoints) {\n for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {\n if (typeof partialDefinition === 'function') {\n partialDefinition(context.endpointDefinitions[endpointName]);\n } else {\n Object.assign(context.endpointDefinitions[endpointName] || {}, partialDefinition);\n }\n }\n }\n return api;\n }\n } as Api<BaseQueryFn, {}, string, string, Modules[number]['name']>;\n const initializedModules = modules.map(m => m.init(api as any, optionsWithDefaults as any, context));\n function injectEndpoints(inject: Parameters<typeof api.injectEndpoints>[0]) {\n const evaluatedEndpoints = inject.endpoints({\n query: x => ({\n ...x,\n type: DefinitionType.query\n }) as any,\n mutation: x => ({\n ...x,\n type: DefinitionType.mutation\n }) as any,\n infiniteQuery: x => ({\n ...x,\n type: DefinitionType.infinitequery\n }) as any\n });\n for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {\n if (inject.overrideExisting !== true && endpointName in context.endpointDefinitions) {\n if (inject.overrideExisting === 'throw') {\n throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(39) : `called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``);\n } else if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n console.error(`called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``);\n }\n continue;\n }\n if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n if (isInfiniteQueryDefinition(definition)) {\n const {\n infiniteQueryOptions\n } = definition;\n const {\n maxPages,\n getPreviousPageParam\n } = infiniteQueryOptions;\n if (typeof maxPages === 'number') {\n if (maxPages < 1) {\n throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage2(40) : `maxPages for endpoint '${endpointName}' must be a number greater than 0`);\n }\n if (typeof getPreviousPageParam !== 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage3(41) : `getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`);\n }\n }\n }\n }\n context.endpointDefinitions[endpointName] = definition;\n for (const m of initializedModules) {\n m.injectEndpoint(endpointName, definition);\n }\n }\n return api as any;\n }\n return api.injectEndpoints({\n endpoints: options.endpoints as any\n });\n };\n}","import type { QueryCacheKey } from './core/apiState';\nimport type { EndpointDefinition } from './endpointDefinitions';\nimport { isPlainObject } from './core/rtkImports';\nconst cache: WeakMap<any, string> | undefined = WeakMap ? new WeakMap() : undefined;\nexport const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({\n endpointName,\n queryArgs\n}) => {\n let serialized = '';\n const cached = cache?.get(queryArgs);\n if (typeof cached === 'string') {\n serialized = cached;\n } else {\n const stringified = JSON.stringify(queryArgs, (key, value) => {\n // Handle bigints\n value = typeof value === 'bigint' ? {\n $bigint: value.toString()\n } : value;\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 })\n value = isPlainObject(value) ? Object.keys(value).sort().reduce<any>((acc, key) => {\n acc[key] = (value as any)[key];\n return acc;\n }, {}) : value;\n return value;\n });\n if (isPlainObject(queryArgs)) {\n cache?.set(queryArgs, stringified);\n }\n serialized = stringified;\n }\n return `${endpointName}(${serialized})`;\n};\nexport type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {\n queryArgs: QueryArgs;\n endpointDefinition: EndpointDefinition<any, any, any, any>;\n endpointName: string;\n}) => ReturnType;\nexport type InternalSerializeQueryArgs = (_: {\n queryArgs: any;\n endpointDefinition: EndpointDefinition<any, any, any, any>;\n endpointName: string;\n}) => QueryCacheKey;","import { formatProdErrorMessage as _formatProdErrorMessage } from \"@reduxjs/toolkit\";\nimport type { BaseQueryFn } from './baseQueryTypes';\nexport const _NEVER = /* @__PURE__ */Symbol();\nexport type NEVER = typeof _NEVER;\n\n/**\n * Creates a \"fake\" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.\n * This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.\n */\nexport function fakeBaseQuery<ErrorType>(): BaseQueryFn<void, NEVER, ErrorType, {}> {\n return function () {\n throw new Error(process.env.NODE_ENV === \"production\" ? _formatProdErrorMessage(33) : 'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.');\n };\n}","/**\n * Note: this file should import all other files for type discovery and declaration merging\n */\nimport type { ActionCreatorWithPayload, Middleware, Reducer, ThunkAction, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport { enablePatches } from 'immer';\nimport type { Api, Module } from '../apiTypes';\nimport type { BaseQueryFn } from '../baseQueryTypes';\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';\nimport type { AssertTagTypes, EndpointDefinitions, InfiniteQueryDefinition, MutationDefinition, QueryArgFrom, QueryDefinition, TagDescription } from '../endpointDefinitions';\nimport { isInfiniteQueryDefinition, isMutationDefinition, isQueryDefinition } from '../endpointDefinitions';\nimport { assertCast, safeAssign } from '../tsHelpers';\nimport type { CombinedState, MutationKeys, QueryKeys, RootState } from './apiState';\nimport type { BuildInitiateApiEndpointMutation, BuildInitiateApiEndpointQuery, MutationActionCreatorResult, QueryActionCreatorResult, InfiniteQueryActionCreatorResult, BuildInitiateApiEndpointInfiniteQuery } from './buildInitiate';\nimport { buildInitiate } from './buildInitiate';\nimport type { ReferenceCacheCollection, ReferenceCacheLifecycle, ReferenceQueryLifecycle } from './buildMiddleware';\nimport { buildMiddleware } from './buildMiddleware';\nimport type { BuildSelectorsApiEndpointInfiniteQuery, BuildSelectorsApiEndpointMutation, BuildSelectorsApiEndpointQuery } from './buildSelectors';\nimport { buildSelectors } from './buildSelectors';\nimport type { SliceActions, UpsertEntries } from './buildSlice';\nimport { buildSlice } from './buildSlice';\nimport type { AllQueryKeys, BuildThunksApiEndpointInfiniteQuery, BuildThunksApiEndpointMutation, BuildThunksApiEndpointQuery, PatchQueryDataThunk, QueryArgFromAnyQueryDefinition, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';\nimport { buildThunks } from './buildThunks';\nimport { createSelector as _createSelector } from './rtkImports';\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners';\n\n/**\n * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_\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\n *\n * @overloadSummary\n * `force`\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.\n */\nexport type PrefetchOptions = {\n ifOlderThan?: false | number;\n} | {\n force?: boolean;\n};\nexport const coreModuleName = /* @__PURE__ */Symbol();\nexport type CoreModule = typeof coreModuleName | ReferenceCacheLifecycle | ReferenceQueryLifecycle | ReferenceCacheCollection;\nexport type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>;\nexport interface ApiModules<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nBaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {\n [coreModuleName]: {\n /**\n * This api's reducer should be mounted at `store[api.reducerPath]`.\n *\n * @example\n * ```ts\n * configureStore({\n * reducer: {\n * [api.reducerPath]: api.reducer,\n * },\n * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n * })\n * ```\n */\n reducerPath: ReducerPath;\n /**\n * Internal actions not part of the public API. Note: These are subject to change at any given time.\n */\n internalActions: InternalActions;\n /**\n * A standard redux reducer that enables core functionality. Make sure it's included in your store.\n *\n * @example\n * ```ts\n * configureStore({\n * reducer: {\n * [api.reducerPath]: api.reducer,\n * },\n * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n * })\n * ```\n */\n reducer: Reducer<CombinedState<Definitions, TagTypes, ReducerPath>, UnknownAction>;\n /**\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.\n *\n * @example\n * ```ts\n * configureStore({\n * reducer: {\n * [api.reducerPath]: api.reducer,\n * },\n * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n * })\n * ```\n */\n middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, UnknownAction>>;\n /**\n * A collection of utility thunks for various situations.\n */\n util: {\n /**\n * A thunk that (if dispatched) will return a specific running query, identified\n * by `endpointName` and `arg`.\n * If that query is not running, dispatching the thunk will result in `undefined`.\n *\n * Can be used to await a specific query triggered in any way,\n * including via hook calls or manually dispatching `initiate` actions.\n *\n * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n */\n getRunningQueryThunk<EndpointName extends AllQueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>): ThunkWithReturnValue<QueryActionCreatorResult<Definitions[EndpointName] & {\n type: 'query';\n }> | InfiniteQueryActionCreatorResult<Definitions[EndpointName] & {\n type: 'infinitequery';\n }> | undefined>;\n\n /**\n * A thunk that (if dispatched) will return a specific running mutation, identified\n * by `endpointName` and `fixedCacheKey` or `requestId`.\n * If that mutation is not running, dispatching the thunk will result in `undefined`.\n *\n * Can be used to await a specific mutation triggered in any way,\n * including via hook trigger functions or manually dispatching `initiate` actions.\n *\n * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n */\n getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(endpointName: EndpointName, fixedCacheKeyOrRequestId: string): ThunkWithReturnValue<MutationActionCreatorResult<Definitions[EndpointName] & {\n type: 'mutation';\n }> | undefined>;\n\n /**\n * A thunk that (if dispatched) will return all running queries.\n *\n * Useful for SSR scenarios to await all running queries triggered in any way,\n * including via hook calls or manually dispatching `initiate` actions.\n *\n * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n */\n getRunningQueriesThunk(): ThunkWithReturnValue<Array<QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>>>;\n\n /**\n * A thunk that (if dispatched) will return all running mutations.\n *\n * Useful for SSR scenarios to await all running mutations triggered in any way,\n * including via hook calls or manually dispatching `initiate` actions.\n *\n * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n */\n getRunningMutationsThunk(): ThunkWithReturnValue<Array<MutationActionCreatorResult<any>>>;\n\n /**\n * A Redux thunk that can be used to manually trigger pre-fetching of data.\n *\n * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.\n *\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.\n *\n * @example\n *\n * ```ts no-transpile\n * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))\n * ```\n */\n prefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, options: PrefetchOptions): ThunkAction<void, any, any, UnknownAction>;\n /**\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.\n *\n * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and an `updateRecipe` 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.\n *\n * The thunk executes _synchronously_, and 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).\n *\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, arg, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.\n *\n * Note that the first two arguments (`endpointName` and `arg`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.\n *\n * @example\n *\n * ```ts\n * const patchCollection = dispatch(\n * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n * draftPosts.push({ id: 1, name: 'Teddy' })\n * })\n * )\n * ```\n */\n updateQueryData: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n\n /**\n * A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.\n *\n * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and the data to upsert.\n *\n * If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.\n *\n * The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.\n *\n * If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a \"last result wins\" update behavior.\n *\n * @example\n *\n * ```ts\n * await dispatch(\n * api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: \"Hello!\"})\n * )\n * ```\n */\n upsertQueryData: UpsertQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n /**\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.\n *\n * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.\n *\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.\n *\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.\n *\n * @example\n * ```ts\n * const patchCollection = dispatch(\n * api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n * draftPosts.push({ id: 1, name: 'Teddy' })\n * })\n * )\n *\n * // later\n * dispatch(\n * api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)\n * )\n *\n * // or\n * patchCollection.undo()\n * ```\n */\n patchQueryData: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;\n\n /**\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'.\n *\n * @example\n *\n * ```ts\n * dispatch(api.util.resetApiState())\n * ```\n */\n resetApiState: SliceActions['resetApiState'];\n upsertQueryEntries: UpsertEntries<Definitions>;\n\n /**\n * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).\n *\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.\n *\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.\n *\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:\n *\n * - `[TagType]`\n * - `[{ type: TagType }]`\n * - `[{ type: TagType, id: number | string }]`\n *\n * @example\n *\n * ```ts\n * dispatch(api.util.invalidateTags(['Post']))\n * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))\n * dispatch(\n * api.util.invalidateTags([\n * { type: 'Post', id: 1 },\n * { type: 'Post', id: 'LIST' },\n * ])\n * )\n * ```\n */\n invalidateTags: ActionCreatorWithPayload<Array<TagDescription<TagTypes> | null | undefined>, string>;\n\n /**\n * A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.\n *\n * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.\n */\n selectInvalidatedBy: (state: RootState<Definitions, string, ReducerPath>, tags: ReadonlyArray<TagDescription<TagTypes> | null | undefined>) => Array<{\n endpointName: string;\n originalArgs: any;\n queryCacheKey: string;\n }>;\n\n /**\n * A function to select all arguments currently cached for a given endpoint.\n *\n * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.\n */\n selectCachedArgsForQuery: <QueryName extends QueryKeys<Definitions>>(state: RootState<Definitions, string, ReducerPath>, queryName: QueryName) => Array<QueryArgFrom<Definitions[QueryName]>>;\n };\n /**\n * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.\n */\n endpoints: { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? ApiEndpointQuery<Definitions[K], Definitions> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? ApiEndpointMutation<Definitions[K], Definitions> : Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? ApiEndpointInfiniteQuery<Definitions[K], Definitions> : never };\n };\n}\nexport interface ApiEndpointQuery<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends QueryDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointQuery<Definition>, BuildInitiateApiEndpointQuery<Definition>, BuildSelectorsApiEndpointQuery<Definition, Definitions> {\n name: string;\n /**\n * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n */\n Types: NonNullable<Definition['Types']>;\n}\nexport interface ApiEndpointInfiniteQuery<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends InfiniteQueryDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointInfiniteQuery<Definition>, BuildInitiateApiEndpointInfiniteQuery<Definition>, BuildSelectorsApiEndpointInfiniteQuery<Definition, Definitions> {\n name: string;\n /**\n * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n */\n Types: NonNullable<Definition['Types']>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface ApiEndpointMutation<\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinition extends MutationDefinition<any, any, any, any, any>,\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nDefinitions extends EndpointDefinitions> extends BuildThunksApiEndpointMutation<Definition>, BuildInitiateApiEndpointMutation<Definition>, BuildSelectorsApiEndpointMutation<Definition, Definitions> {\n name: string;\n /**\n * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n */\n Types: NonNullable<Definition['Types']>;\n}\nexport type ListenerActions = {\n /**\n * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior\n * @link https://rtk-query-docs.netlify.app/api/setupListeners\n */\n onOnline: typeof onOnline;\n onOffline: typeof onOffline;\n /**\n * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior\n * @link https://rtk-query-docs.netlify.app/api/setupListeners\n */\n onFocus: typeof onFocus;\n onFocusLost: typeof onFocusLost;\n};\nexport type InternalActions = SliceActions & ListenerActions;\nexport interface CoreModuleOptions {\n /**\n * A selector creator (usually from `reselect`, or matching the same signature)\n */\n createSelector?: typeof _createSelector;\n}\n\n/**\n * Creates a module containing the basic redux logic for use with `buildCreateApi`.\n *\n * @example\n * ```ts\n * const createBaseApi = buildCreateApi(coreModule());\n * ```\n */\nexport const coreModule = ({\n createSelector = _createSelector\n}: CoreModuleOptions = {}): Module<CoreModule> => ({\n name: coreModuleName,\n init(api, {\n baseQuery,\n tagTypes,\n reducerPath,\n serializeQueryArgs,\n keepUnusedDataFor,\n refetchOnMountOrArgChange,\n refetchOnFocus,\n refetchOnReconnect,\n invalidationBehavior\n }, context) {\n enablePatches();\n assertCast<InternalSerializeQueryArgs>(serializeQueryArgs);\n const assertTagType: AssertTagTypes = tag => {\n if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n if (!tagTypes.includes(tag.type as any)) {\n console.error(`Tag type '${tag.type}' was used, but not specified in \\`tagTypes\\`!`);\n }\n }\n return tag;\n };\n Object.assign(api, {\n reducerPath,\n endpoints: {},\n internalActions: {\n onOnline,\n onOffline,\n onFocus,\n onFocusLost\n },\n util: {}\n });\n const selectors = buildSelectors({\n serializeQueryArgs: serializeQueryArgs as any,\n reducerPath,\n createSelector\n });\n const {\n selectInvalidatedBy,\n selectCachedArgsForQuery,\n buildQuerySelector,\n buildInfiniteQuerySelector,\n buildMutationSelector\n } = selectors;\n safeAssign(api.util, {\n selectInvalidatedBy,\n selectCachedArgsForQuery\n });\n const {\n queryThunk,\n infiniteQueryThunk,\n mutationThunk,\n patchQueryData,\n updateQueryData,\n upsertQueryData,\n prefetch,\n buildMatchThunkActions\n } = buildThunks({\n baseQuery,\n reducerPath,\n context,\n api,\n serializeQueryArgs,\n assertTagType,\n selectors\n });\n const {\n reducer,\n actions: sliceActions\n } = buildSlice({\n context,\n queryThunk,\n infiniteQueryThunk,\n mutationThunk,\n serializeQueryArgs,\n reducerPath,\n assertTagType,\n config: {\n refetchOnFocus,\n refetchOnReconnect,\n refetchOnMountOrArgChange,\n keepUnusedDataFor,\n reducerPath,\n invalidationBehavior\n }\n });\n safeAssign(api.util, {\n patchQueryData,\n updateQueryData,\n upsertQueryData,\n prefetch,\n resetApiState: sliceActions.resetApiState,\n upsertQueryEntries: sliceActions.cacheEntriesUpserted as any\n });\n safeAssign(api.internalActions, sliceActions);\n const {\n middleware,\n actions: middlewareActions\n } = buildMiddleware({\n reducerPath,\n context,\n queryThunk,\n mutationThunk,\n infiniteQueryThunk,\n api,\n assertTagType,\n selectors\n });\n safeAssign(api.util, middlewareActions);\n safeAssign(api, {\n reducer: reducer as any,\n middleware\n });\n const {\n buildInitiateQuery,\n buildInitiateInfiniteQuery,\n buildInitiateMutation,\n getRunningMutationThunk,\n getRunningMutationsThunk,\n getRunningQueriesThunk,\n getRunningQueryThunk\n } = buildInitiate({\n queryThunk,\n mutationThunk,\n infiniteQueryThunk,\n api,\n serializeQueryArgs: serializeQueryArgs as any,\n context\n });\n safeAssign(api.util, {\n getRunningMutationThunk,\n getRunningMutationsThunk,\n getRunningQueryThunk,\n getRunningQueriesThunk\n });\n return {\n name: coreModuleName,\n injectEndpoint(endpointName, definition) {\n const anyApi = api as any as Api<any, Record<string, any>, string, string, CoreModule>;\n const endpoint = anyApi.endpoints[endpointName] ??= {} as any;\n if (isQueryDefinition(definition)) {\n safeAssign(endpoint, {\n name: endpointName,\n select: buildQuerySelector(endpointName, definition),\n initiate: buildInitiateQuery(endpointName, definition)\n }, buildMatchThunkActions(queryThunk, endpointName));\n }\n if (isMutationDefinition(definition)) {\n safeAssign(endpoint, {\n name: endpointName,\n select: buildMutationSelector(),\n initiate: buildInitiateMutation(endpointName)\n }, buildMatchThunkActions(mutationThunk, endpointName));\n }\n if (isInfiniteQueryDefinition(definition)) {\n safeAssign(endpoint, {\n name: endpointName,\n select: buildInfiniteQuerySelector(endpointName, definition),\n initiate: buildInitiateInfiniteQuery(endpointName, definition)\n }, buildMatchThunkActions(queryThunk, endpointName));\n }\n }\n };\n }\n});","export type Id<T> = { [K in keyof T]: T[K] } & {};\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;\nexport type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never;\nexport function assertCast<T>(v: any): asserts v is T {}\nexport function safeAssign<T extends object>(target: T, ...args: Array<Partial<NoInfer<T>>>): T {\n return Object.assign(target, ...args);\n}\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;\nexport type NonOptionalKeys<T> = { [K in keyof T]-?: undefined extends T[K] ? never : K }[keyof T];\nexport type HasRequiredProps<T, True, False> = NonOptionalKeys<T> extends never ? False : True;\nexport type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>;\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\nexport type NonUndefined<T> = T extends undefined ? never : T;\nexport type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T;\nexport type MaybePromise<T> = T | PromiseLike<T>;\nexport type OmitFromUnion<T, K extends keyof T> = T extends any ? Omit<T, K> : never;\nexport type IsAny<T, True, False = never> = true | false extends (T extends never ? true : false) ? True : False;\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>;","import type { InternalHandlerBuilder, SubscriptionSelectors } from './types';\nimport type { SubscriptionState } from '../apiState';\nimport { produceWithPatches } from 'immer';\nimport type { Action } from '@reduxjs/toolkit';\nimport { countObjectKeys } from '../../utils/countObjectKeys';\nexport const buildBatchedActionsHandler: InternalHandlerBuilder<[actionShouldContinue: boolean, returnValue: SubscriptionSelectors | boolean]> = ({\n api,\n queryThunk,\n internalState\n}) => {\n const subscriptionsPrefix = `${api.reducerPath}/subscriptions`;\n let previousSubscriptions: SubscriptionState = null as unknown as SubscriptionState;\n let updateSyncTimer: ReturnType<typeof window.setTimeout> | null = null;\n const {\n updateSubscriptionOptions,\n unsubscribeQueryResult\n } = api.internalActions;\n\n // Actually intentionally mutate the subscriptions state used in the middleware\n // This is done to speed up perf when loading many components\n const actuallyMutateSubscriptions = (mutableState: SubscriptionState, action: Action) => {\n if (updateSubscriptionOptions.match(action)) {\n const {\n queryCacheKey,\n requestId,\n options\n } = action.payload;\n if (mutableState?.[queryCacheKey]?.[requestId]) {\n mutableState[queryCacheKey]![requestId] = options;\n }\n return true;\n }\n if (unsubscribeQueryResult.match(action)) {\n const {\n queryCacheKey,\n requestId\n } = action.payload;\n if (mutableState[queryCacheKey]) {\n delete mutableState[queryCacheKey]![requestId];\n }\n return true;\n }\n if (api.internalActions.removeQueryResult.match(action)) {\n delete mutableState[action.payload.queryCacheKey];\n return true;\n }\n if (queryThunk.pending.match(action)) {\n const {\n meta: {\n arg,\n requestId\n }\n } = action;\n const substate = mutableState[arg.queryCacheKey] ??= {};\n substate[`${requestId}_running`] = {};\n if (arg.subscribe) {\n substate[requestId] = arg.subscriptionOptions ?? substate[requestId] ?? {};\n }\n return true;\n }\n let mutated = false;\n if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action)) {\n const state = mutableState[action.meta.arg.queryCacheKey] || {};\n const key = `${action.meta.requestId}_running`;\n mutated ||= !!state[key];\n delete state[key];\n }\n if (queryThunk.rejected.match(action)) {\n const {\n meta: {\n condition,\n arg,\n requestId\n }\n } = action;\n if (condition && arg.subscribe) {\n const substate = mutableState[arg.queryCacheKey] ??= {};\n substate[requestId] = arg.subscriptionOptions ?? substate[requestId] ?? {};\n mutated = true;\n }\n }\n return mutated;\n };\n const getSubscriptions = () => internalState.currentSubscriptions;\n const getSubscriptionCount = (queryCacheKey: string) => {\n const subscriptions = getSubscriptions();\n const subscriptionsForQueryArg = subscriptions[queryCacheKey] ?? {};\n return countObjectKeys(subscriptionsForQueryArg);\n };\n const isRequestSubscribed = (queryCacheKey: string, requestId: string) => {\n const subscriptions = getSubscriptions();\n return !!subscriptions?.[queryCacheKey]?.[requestId];\n };\n const subscriptionSelectors: SubscriptionSelectors = {\n getSubscriptions,\n getSubscriptionCount,\n isRequestSubscribed\n };\n return (action, mwApi): [actionShouldContinue: boolean, result: SubscriptionSelectors | boolean] => {\n if (!previousSubscriptions) {\n // Initialize it the first time this handler runs\n previousSubscriptions = JSON.parse(JSON.stringify(internalState.currentSubscriptions));\n }\n if (api.util.resetApiState.match(action)) {\n previousSubscriptions = internalState.currentSubscriptions = {};\n updateSyncTimer = null;\n return [true, false];\n }\n\n // Intercept requests by hooks to see if they're subscribed\n // We return the internal state reference so that hooks\n // can do their own checks to see if they're still active.\n // It's stupid and hacky, but it does cut down on some dispatch calls.\n if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {\n return [false, subscriptionSelectors];\n }\n\n // Update subscription data based on this action\n const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);\n let actionShouldContinue = true;\n if (didMutate) {\n if (!updateSyncTimer) {\n // We only use the subscription state for the Redux DevTools at this point,\n // as the real data is kept here in the middleware.\n // Given that, we can throttle synchronizing this state significantly to\n // save on overall perf.\n // In 1.9, it was updated in a microtask, but now we do it at most every 500ms.\n updateSyncTimer = setTimeout(() => {\n // Deep clone the current subscription data\n const newSubscriptions: SubscriptionState = JSON.parse(JSON.stringify(internalState.currentSubscriptions));\n // Figure out a smaller diff between original and current\n const [, patches] = produceWithPatches(previousSubscriptions, () => newSubscriptions);\n\n // Sync the store state for visibility\n mwApi.next(api.internalActions.subscriptionsUpdated(patches));\n // Save the cloned state for later reference\n previousSubscriptions = newSubscriptions;\n updateSyncTimer = null;\n }, 500);\n }\n const isSubscriptionSliceAction = typeof action.type == 'string' && !!action.type.startsWith(subscriptionsPrefix);\n const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;\n actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;\n }\n return [actionShouldContinue, false];\n };\n};","import type { QueryDefinition } from '../../endpointDefinitions';\nimport type { ConfigState, QueryCacheKey } from '../apiState';\nimport { isAnyOf } from '../rtkImports';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, QueryStateMeta, SubMiddlewareApi, TimeoutId } from './types';\nexport type ReferenceCacheCollection = never;\nfunction isObjectEmpty(obj: Record<any, any>) {\n // Apparently a for..in loop is faster than `Object.keys()` here:\n // https://stackoverflow.com/a/59787784/62937\n for (const k in obj) {\n // If there is at least one key, it's not empty\n return false;\n }\n return true;\n}\nexport type CacheCollectionQueryExtraOptions = {\n /**\n * Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(This value is in seconds.)_\n *\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.\n */\n keepUnusedDataFor?: number;\n};\n\n// Per https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value , browsers store\n// `setTimeout()` timer values in a 32-bit int. If we pass a value in that's larger than that,\n// it wraps and ends up executing immediately.\n// Our `keepUnusedDataFor` values are in seconds, so adjust the numbers here accordingly.\nexport const THIRTY_TWO_BIT_MAX_INT = 2_147_483_647;\nexport const THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2_147_483_647 / 1_000 - 1;\nexport const buildCacheCollectionHandler: InternalHandlerBuilder = ({\n reducerPath,\n api,\n queryThunk,\n context,\n internalState,\n selectors: {\n selectQueryEntry,\n selectConfig\n }\n}) => {\n const {\n removeQueryResult,\n unsubscribeQueryResult,\n cacheEntriesUpserted\n } = api.internalActions;\n const canTriggerUnsubscribe = isAnyOf(unsubscribeQueryResult.match, queryThunk.fulfilled, queryThunk.rejected, cacheEntriesUpserted.match);\n function anySubscriptionsRemainingForKey(queryCacheKey: string) {\n const subscriptions = internalState.currentSubscriptions[queryCacheKey];\n return !!subscriptions && !isObjectEmpty(subscriptions);\n }\n const currentRemovalTimeouts: QueryStateMeta<TimeoutId> = {};\n const handler: ApiMiddlewareInternalHandler = (action, mwApi, internalState) => {\n const state = mwApi.getState();\n const config = selectConfig(state);\n if (canTriggerUnsubscribe(action)) {\n let queryCacheKeys: QueryCacheKey[];\n if (cacheEntriesUpserted.match(action)) {\n queryCacheKeys = action.payload.map(entry => entry.queryDescription.queryCacheKey);\n } else {\n const {\n queryCacheKey\n } = unsubscribeQueryResult.match(action) ? action.payload : action.meta.arg;\n queryCacheKeys = [queryCacheKey];\n }\n handleUnsubscribeMany(queryCacheKeys, mwApi, config);\n }\n if (api.util.resetApiState.match(action)) {\n for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {\n if (timeout) clearTimeout(timeout);\n delete currentRemovalTimeouts[key];\n }\n }\n if (context.hasRehydrationInfo(action)) {\n const {\n queries\n } = context.extractRehydrationInfo(action)!;\n // Gotcha:\n // If rehydrating before the endpoint has been injected,the global `keepUnusedDataFor`\n // will be used instead of the endpoint-specific one.\n handleUnsubscribeMany(Object.keys(queries) as QueryCacheKey[], mwApi, config);\n }\n };\n function handleUnsubscribeMany(cacheKeys: QueryCacheKey[], api: SubMiddlewareApi, config: ConfigState<string>) {\n const state = api.getState();\n for (const queryCacheKey of cacheKeys) {\n const entry = selectQueryEntry(state, queryCacheKey);\n handleUnsubscribe(queryCacheKey, entry?.endpointName, api, config);\n }\n }\n function handleUnsubscribe(queryCacheKey: QueryCacheKey, endpointName: string | undefined, api: SubMiddlewareApi, config: ConfigState<string>) {\n const endpointDefinition = context.endpointDefinitions[endpointName!] as QueryDefinition<any, any, any, any>;\n const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;\n if (keepUnusedDataFor === Infinity) {\n // Hey, user said keep this forever!\n return;\n }\n // Prevent `setTimeout` timers from overflowing a 32-bit internal int, by\n // clamping the max value to be at most 1000ms less than the 32-bit max.\n // Look, a 24.8-day keepalive ought to be enough for anybody, right? :)\n // Also avoid negative values too.\n const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));\n if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n const currentTimeout = currentRemovalTimeouts[queryCacheKey];\n if (currentTimeout) {\n clearTimeout(currentTimeout);\n }\n currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {\n if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n api.dispatch(removeQueryResult({\n queryCacheKey\n }));\n }\n delete currentRemovalTimeouts![queryCacheKey];\n }, finalKeepUnusedDataFor * 1000);\n }\n }\n return handler;\n};","import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes';\nimport type { BaseEndpointDefinition } from '../../endpointDefinitions';\nimport { DefinitionType } from '../../endpointDefinitions';\nimport type { QueryCacheKey, RootState } from '../apiState';\nimport type { MutationResultSelectorResult, QueryResultSelectorResult } from '../buildSelectors';\nimport { getMutationCacheKey } from '../buildSlice';\nimport type { PatchCollection, Recipe } from '../buildThunks';\nimport { isAsyncThunkAction, isFulfilled } from '../rtkImports';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, PromiseWithKnownReason, SubMiddlewareApi } from './types';\nexport type ReferenceCacheLifecycle = never;\nexport interface QueryBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends LifecycleApi<ReducerPath> {\n /**\n * Gets the current value of this cache entry.\n */\n getCacheEntry(): QueryResultSelectorResult<{\n type: DefinitionType.query;\n } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType>>;\n /**\n * Updates the current cache entry value.\n * For documentation see `api.util.updateQueryData`.\n */\n updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection;\n}\nexport type MutationBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = LifecycleApi<ReducerPath> & {\n /**\n * Gets the current value of this cache entry.\n */\n getCacheEntry(): MutationResultSelectorResult<{\n type: DefinitionType.mutation;\n } & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType>>;\n};\ntype LifecycleApi<ReducerPath extends string = string> = {\n /**\n * The dispatch method for the store\n */\n dispatch: ThunkDispatch<any, any, UnknownAction>;\n /**\n * A method to get the current state\n */\n getState(): RootState<any, any, ReducerPath>;\n /**\n * `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.\n */\n extra: unknown;\n /**\n * A unique ID generated for the mutation\n */\n requestId: string;\n};\ntype CacheLifecyclePromises<ResultType = unknown, MetaType = unknown> = {\n /**\n * Promise that will resolve with the first value for this cache key.\n * This allows you to `await` until an actual value is in cache.\n *\n * If the cache entry is removed from the cache before any value has ever\n * been resolved, this Promise will reject with\n * `new Error('Promise never resolved before cacheEntryRemoved.')`\n * to prevent memory leaks.\n * You can just re-throw that error (or not handle it at all) -\n * it will be caught outside of `cacheEntryAdded`.\n *\n * If you don't interact with this promise, it will not throw.\n */\n cacheDataLoaded: PromiseWithKnownReason<{\n /**\n * The (transformed) query result.\n */\n data: ResultType;\n /**\n * The `meta` returned by the `baseQuery`\n */\n meta: MetaType;\n }, typeof neverResolvedError>;\n /**\n * Promise that allows you to wait for the point in time when the cache entry\n * has been removed from the cache, by not being used/subscribed to any more\n * in the application for too long or by dispatching `api.util.resetApiState`.\n */\n cacheEntryRemoved: Promise<void>;\n};\nexport interface QueryCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}\nexport type MutationCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>>;\nexport type CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n onCacheEntryAdded?(arg: QueryArg, api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport type CacheLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = CacheLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport type CacheLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n onCacheEntryAdded?(arg: QueryArg, api: MutationCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nconst neverResolvedError = new Error('Promise never resolved before cacheEntryRemoved.') as Error & {\n message: 'Promise never resolved before cacheEntryRemoved.';\n};\nexport const buildCacheLifecycleHandler: InternalHandlerBuilder = ({\n api,\n reducerPath,\n context,\n queryThunk,\n mutationThunk,\n internalState,\n selectors: {\n selectQueryEntry,\n selectApiState\n }\n}) => {\n const isQueryThunk = isAsyncThunkAction(queryThunk);\n const isMutationThunk = isAsyncThunkAction(mutationThunk);\n const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk);\n type CacheLifecycle = {\n valueResolved?(value: {\n data: unknown;\n meta: unknown;\n }): unknown;\n cacheEntryRemoved(): void;\n };\n const lifecycleMap: Record<string, CacheLifecycle> = {};\n function resolveLifecycleEntry(cacheKey: string, data: unknown, meta: unknown) {\n const lifecycle = lifecycleMap[cacheKey];\n if (lifecycle?.valueResolved) {\n lifecycle.valueResolved({\n data,\n meta\n });\n delete lifecycle.valueResolved;\n }\n }\n function removeLifecycleEntry(cacheKey: string) {\n const lifecycle = lifecycleMap[cacheKey];\n if (lifecycle) {\n delete lifecycleMap[cacheKey];\n lifecycle.cacheEntryRemoved();\n }\n }\n const handler: ApiMiddlewareInternalHandler = (action, mwApi, stateBefore) => {\n const cacheKey = getCacheKey(action) as QueryCacheKey;\n function checkForNewCacheKey(endpointName: string, cacheKey: QueryCacheKey, requestId: string, originalArgs: unknown) {\n const oldEntry = selectQueryEntry(stateBefore, cacheKey);\n const newEntry = selectQueryEntry(mwApi.getState(), cacheKey);\n if (!oldEntry && newEntry) {\n handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);\n }\n }\n if (queryThunk.pending.match(action)) {\n checkForNewCacheKey(action.meta.arg.endpointName, cacheKey, action.meta.requestId, action.meta.arg.originalArgs);\n } else if (api.internalActions.cacheEntriesUpserted.match(action)) {\n for (const {\n queryDescription,\n value\n } of action.payload) {\n const {\n endpointName,\n originalArgs,\n queryCacheKey\n } = queryDescription;\n checkForNewCacheKey(endpointName, queryCacheKey, action.meta.requestId, originalArgs);\n resolveLifecycleEntry(queryCacheKey, value, {});\n }\n } else if (mutationThunk.pending.match(action)) {\n const state = mwApi.getState()[reducerPath].mutations[cacheKey];\n if (state) {\n handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);\n }\n } else if (isFulfilledThunk(action)) {\n resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta);\n } else if (api.internalActions.removeQueryResult.match(action) || api.internalActions.removeMutationResult.match(action)) {\n removeLifecycleEntry(cacheKey);\n } else if (api.util.resetApiState.match(action)) {\n for (const cacheKey of Object.keys(lifecycleMap)) {\n removeLifecycleEntry(cacheKey);\n }\n }\n };\n function getCacheKey(action: any) {\n if (isQueryThunk(action)) return action.meta.arg.queryCacheKey;\n if (isMutationThunk(action)) {\n return action.meta.arg.fixedCacheKey ?? action.meta.requestId;\n }\n if (api.internalActions.removeQueryResult.match(action)) return action.payload.queryCacheKey;\n if (api.internalActions.removeMutationResult.match(action)) return getMutationCacheKey(action.payload);\n return '';\n }\n function handleNewKey(endpointName: string, originalArgs: any, queryCacheKey: string, mwApi: SubMiddlewareApi, requestId: string) {\n const endpointDefinition = context.endpointDefinitions[endpointName];\n const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;\n if (!onCacheEntryAdded) return;\n const lifecycle = {} as CacheLifecycle;\n const cacheEntryRemoved = new Promise<void>(resolve => {\n lifecycle.cacheEntryRemoved = resolve;\n });\n const cacheDataLoaded: PromiseWithKnownReason<{\n data: unknown;\n meta: unknown;\n }, typeof neverResolvedError> = Promise.race([new Promise<{\n data: unknown;\n meta: unknown;\n }>(resolve => {\n lifecycle.valueResolved = resolve;\n }), cacheEntryRemoved.then(() => {\n throw neverResolvedError;\n })]);\n // prevent uncaught promise rejections from happening.\n // if the original promise is used in any way, that will create a new promise that will throw again\n cacheDataLoaded.catch(() => {});\n lifecycleMap[queryCacheKey] = lifecycle;\n const selector = (api.endpoints[endpointName] as any).select(endpointDefinition.type === DefinitionType.query ? originalArgs : queryCacheKey);\n const extra = mwApi.dispatch((_, __, extra) => extra);\n const lifecycleApi = {\n ...mwApi,\n getCacheEntry: () => selector(mwApi.getState()),\n requestId,\n extra,\n updateCachedData: (endpointDefinition.type === DefinitionType.query ? (updateRecipe: Recipe<any>) => mwApi.dispatch(api.util.updateQueryData(endpointName as never, originalArgs as never, updateRecipe)) : undefined) as any,\n cacheDataLoaded,\n cacheEntryRemoved\n };\n const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi as any);\n // if a `neverResolvedError` was thrown, but not handled in the running handler, do not let it leak out further\n Promise.resolve(runningHandler).catch(e => {\n if (e === neverResolvedError) return;\n throw e;\n });\n }\n return handler;\n};","import type { InternalHandlerBuilder } from './types';\nexport const buildDevCheckHandler: InternalHandlerBuilder = ({\n api,\n context: {\n apiUid\n },\n reducerPath\n}) => {\n return (action, mwApi) => {\n if (api.util.resetApiState.match(action)) {\n // dispatch after api reset\n mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\n }\n if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {\n if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && mwApi.getState()[reducerPath]?.config?.middlewareRegistered === 'conflict') {\n console.warn(`There is a mismatch between slice and middleware for the reducerPath \"${reducerPath}\".\nYou can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === 'api' ? `\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ''}`);\n }\n }\n };\n};","import { isAnyOf, isFulfilled, isRejected, isRejectedWithValue } from '../rtkImports';\nimport type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';\nimport { calculateProvidedBy } from '../../endpointDefinitions';\nimport type { CombinedState, QueryCacheKey } from '../apiState';\nimport { QueryStatus } from '../apiState';\nimport { calculateProvidedByThunk } from '../buildThunks';\nimport type { SubMiddlewareApi, InternalHandlerBuilder, ApiMiddlewareInternalHandler, InternalMiddlewareState } from './types';\nimport { countObjectKeys } from '../../utils/countObjectKeys';\nexport const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({\n reducerPath,\n context,\n context: {\n endpointDefinitions\n },\n mutationThunk,\n queryThunk,\n api,\n assertTagType,\n refetchQuery,\n internalState\n}) => {\n const {\n removeQueryResult\n } = api.internalActions;\n const isThunkActionWithTags = isAnyOf(isFulfilled(mutationThunk), isRejectedWithValue(mutationThunk));\n const isQueryEnd = isAnyOf(isFulfilled(mutationThunk, queryThunk), isRejected(mutationThunk, queryThunk));\n let pendingTagInvalidations: FullTagDescription<string>[] = [];\n const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n if (isThunkActionWithTags(action)) {\n invalidateTags(calculateProvidedByThunk(action, 'invalidatesTags', endpointDefinitions, assertTagType), mwApi);\n } else if (isQueryEnd(action)) {\n invalidateTags([], mwApi);\n } else if (api.util.invalidateTags.match(action)) {\n invalidateTags(calculateProvidedBy(action.payload, undefined, undefined, undefined, undefined, assertTagType), mwApi);\n }\n };\n function hasPendingRequests(state: CombinedState<EndpointDefinitions, string, string>) {\n const {\n queries,\n mutations\n } = state;\n for (const cacheRecord of [queries, mutations]) {\n for (const key in cacheRecord) {\n if (cacheRecord[key]?.status === QueryStatus.pending) return true;\n }\n }\n return false;\n }\n function invalidateTags(newTags: readonly FullTagDescription<string>[], mwApi: SubMiddlewareApi) {\n const rootState = mwApi.getState();\n const state = rootState[reducerPath];\n pendingTagInvalidations.push(...newTags);\n if (state.config.invalidationBehavior === 'delayed' && hasPendingRequests(state)) {\n return;\n }\n const tags = pendingTagInvalidations;\n pendingTagInvalidations = [];\n if (tags.length === 0) return;\n const toInvalidate = api.util.selectInvalidatedBy(rootState, tags);\n context.batch(() => {\n const valuesArray = Array.from(toInvalidate.values());\n for (const {\n queryCacheKey\n } of valuesArray) {\n const querySubState = state.queries[queryCacheKey];\n const subscriptionSubState = internalState.currentSubscriptions[queryCacheKey] ?? {};\n if (querySubState) {\n if (countObjectKeys(subscriptionSubState) === 0) {\n mwApi.dispatch(removeQueryResult({\n queryCacheKey: queryCacheKey as QueryCacheKey\n }));\n } else if (querySubState.status !== QueryStatus.uninitialized) {\n mwApi.dispatch(refetchQuery(querySubState));\n }\n }\n }\n });\n }\n return handler;\n};","import type { QueryCacheKey, QuerySubstateIdentifier, Subscribers } from '../apiState';\nimport { QueryStatus } from '../apiState';\nimport type { QueryStateMeta, SubMiddlewareApi, TimeoutId, InternalHandlerBuilder, ApiMiddlewareInternalHandler, InternalMiddlewareState } from './types';\nexport const buildPollingHandler: InternalHandlerBuilder = ({\n reducerPath,\n queryThunk,\n api,\n refetchQuery,\n internalState\n}) => {\n const currentPolls: QueryStateMeta<{\n nextPollTimestamp: number;\n timeout?: TimeoutId;\n pollingInterval: number;\n }> = {};\n const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) {\n updatePollingInterval(action.payload, mwApi);\n }\n if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {\n updatePollingInterval(action.meta.arg, mwApi);\n }\n if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {\n startNextPoll(action.meta.arg, mwApi);\n }\n if (api.util.resetApiState.match(action)) {\n clearPolls();\n }\n };\n function getCacheEntrySubscriptions(queryCacheKey: QueryCacheKey, api: SubMiddlewareApi) {\n const state = api.getState()[reducerPath];\n const querySubState = state.queries[queryCacheKey];\n const subscriptions = internalState.currentSubscriptions[queryCacheKey];\n if (!querySubState || querySubState.status === QueryStatus.uninitialized) return;\n return subscriptions;\n }\n function startNextPoll({\n queryCacheKey\n }: QuerySubstateIdentifier, api: SubMiddlewareApi) {\n const state = api.getState()[reducerPath];\n const querySubState = state.queries[queryCacheKey];\n const subscriptions = internalState.currentSubscriptions[queryCacheKey];\n if (!querySubState || querySubState.status === QueryStatus.uninitialized) return;\n const {\n lowestPollingInterval,\n skipPollingIfUnfocused\n } = findLowestPollingInterval(subscriptions);\n if (!Number.isFinite(lowestPollingInterval)) return;\n const currentPoll = currentPolls[queryCacheKey];\n if (currentPoll?.timeout) {\n clearTimeout(currentPoll.timeout);\n currentPoll.timeout = undefined;\n }\n const nextPollTimestamp = Date.now() + lowestPollingInterval;\n currentPolls[queryCacheKey] = {\n nextPollTimestamp,\n pollingInterval: lowestPollingInterval,\n timeout: setTimeout(() => {\n if (state.config.focused || !skipPollingIfUnfocused) {\n api.dispatch(refetchQuery(querySubState));\n }\n startNextPoll({\n queryCacheKey\n }, api);\n }, lowestPollingInterval)\n };\n }\n function updatePollingInterval({\n queryCacheKey\n }: QuerySubstateIdentifier, api: SubMiddlewareApi) {\n const state = api.getState()[reducerPath];\n const querySubState = state.queries[queryCacheKey];\n const subscriptions = internalState.currentSubscriptions[queryCacheKey];\n if (!querySubState || querySubState.status === QueryStatus.uninitialized) {\n return;\n }\n const {\n lowestPollingInterval\n } = findLowestPollingInterval(subscriptions);\n if (!Number.isFinite(lowestPollingInterval)) {\n cleanupPollForKey(queryCacheKey);\n return;\n }\n const currentPoll = currentPolls[queryCacheKey];\n const nextPollTimestamp = Date.now() + lowestPollingInterval;\n if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {\n startNextPoll({\n queryCacheKey\n }, api);\n }\n }\n function cleanupPollForKey(key: string) {\n const existingPoll = currentPolls[key];\n if (existingPoll?.timeout) {\n clearTimeout(existingPoll.timeout);\n }\n delete currentPolls[key];\n }\n function clearPolls() {\n for (const key of Object.keys(currentPolls)) {\n cleanupPollForKey(key);\n }\n }\n function findLowestPollingInterval(subscribers: Subscribers = {}) {\n let skipPollingIfUnfocused: boolean | undefined = false;\n let lowestPollingInterval = Number.POSITIVE_INFINITY;\n for (let key in subscribers) {\n if (!!subscribers[key].pollingInterval) {\n lowestPollingInterval = Math.min(subscribers[key].pollingInterval!, lowestPollingInterval);\n skipPollingIfUnfocused = subscribers[key].skipPollingIfUnfocused || skipPollingIfUnfocused;\n }\n }\n return {\n lowestPollingInterval,\n skipPollingIfUnfocused\n };\n }\n return handler;\n};","import type { BaseQueryError, BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes';\nimport { DefinitionType } from '../../endpointDefinitions';\nimport type { Recipe } from '../buildThunks';\nimport { isFulfilled, isPending, isRejected } from '../rtkImports';\nimport type { MutationBaseLifecycleApi, QueryBaseLifecycleApi } from './cacheLifecycle';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, PromiseConstructorWithKnownReason, PromiseWithKnownReason } from './types';\nexport type ReferenceQueryLifecycle = never;\ntype QueryLifecyclePromises<ResultType, BaseQuery extends BaseQueryFn> = {\n /**\n * Promise that will resolve with the (transformed) query result.\n *\n * If the query fails, this promise will reject with the error.\n *\n * This allows you to `await` for the query to finish.\n *\n * If you don't interact with this promise, it will not throw.\n */\n queryFulfilled: PromiseWithKnownReason<{\n /**\n * The (transformed) query result.\n */\n data: ResultType;\n /**\n * The `meta` returned by the `baseQuery`\n */\n meta: BaseQueryMeta<BaseQuery>;\n }, QueryFulfilledRejectionReason<BaseQuery>>;\n};\ntype QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> = {\n error: BaseQueryError<BaseQuery>;\n /**\n * If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.\n */\n isUnhandledError: false;\n /**\n * The `meta` returned by the `baseQuery`\n */\n meta: BaseQueryMeta<BaseQuery>;\n} | {\n error: unknown;\n meta?: undefined;\n /**\n * If this is `true`, that means that this error is the result of `baseQueryFn`, `queryFn`, `transformResponse` or `transformErrorResponse` throwing an error instead of handling it properly.\n * There can not be made any assumption about the shape of `error`.\n */\n isUnhandledError: true;\n};\nexport type QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n /**\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).\n *\n * Can be used to perform side-effects throughout the lifecycle of the query.\n *\n * @example\n * ```ts\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n * import { messageCreated } from './notificationsSlice\n * export interface Post {\n * id: number\n * name: string\n * }\n *\n * const api = createApi({\n * baseQuery: fetchBaseQuery({\n * baseUrl: '/',\n * }),\n * endpoints: (build) => ({\n * getPost: build.query<Post, number>({\n * query: (id) => `post/${id}`,\n * async onQueryStarted(id, { dispatch, queryFulfilled }) {\n * // `onStart` side-effect\n * dispatch(messageCreated('Fetching posts...'))\n * try {\n * const { data } = await queryFulfilled\n * // `onSuccess` side-effect\n * dispatch(messageCreated('Posts received!'))\n * } catch (err) {\n * // `onError` side-effect\n * dispatch(messageCreated('Error fetching posts!'))\n * }\n * }\n * }),\n * }),\n * })\n * ```\n */\n onQueryStarted?(queryArgument: QueryArg, queryLifeCycleApi: QueryLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport type QueryLifecycleInfiniteQueryExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArg, BaseQuery, ReducerPath>;\nexport type QueryLifecycleMutationExtraOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> = {\n /**\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).\n *\n * Can be used for `optimistic updates`.\n *\n * @example\n *\n * ```ts\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n * export interface Post {\n * id: number\n * name: string\n * }\n *\n * const api = createApi({\n * baseQuery: fetchBaseQuery({\n * baseUrl: '/',\n * }),\n * tagTypes: ['Post'],\n * endpoints: (build) => ({\n * getPost: build.query<Post, number>({\n * query: (id) => `post/${id}`,\n * providesTags: ['Post'],\n * }),\n * updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({\n * query: ({ id, ...patch }) => ({\n * url: `post/${id}`,\n * method: 'PATCH',\n * body: patch,\n * }),\n * invalidatesTags: ['Post'],\n * async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\n * const patchResult = dispatch(\n * api.util.updateQueryData('getPost', id, (draft) => {\n * Object.assign(draft, patch)\n * })\n * )\n * try {\n * await queryFulfilled\n * } catch {\n * patchResult.undo()\n * }\n * },\n * }),\n * }),\n * })\n * ```\n */\n onQueryStarted?(queryArgument: QueryArg, mutationLifeCycleApi: MutationLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;\n};\nexport interface QueryLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, QueryLifecyclePromises<ResultType, BaseQuery> {}\nexport type MutationLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> & QueryLifecyclePromises<ResultType, BaseQuery>;\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleQueryExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific query.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedQueryOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n * id: number\n * title: string\n * userId: number\n * }\n *\n * type PostsApiResponse = {\n * posts: Post[]\n * total: number\n * skip: number\n * limit: number\n * }\n *\n * type QueryArgument = number | undefined\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n * reducerPath: 'postsApi',\n * tagTypes: ['Posts'],\n * endpoints: (build) => ({\n * getPosts: build.query<PostsApiResponse, void>({\n * query: () => `/posts`,\n * }),\n *\n * getPostById: build.query<Post, QueryArgument>({\n * query: (postId) => `/posts/${postId}`,\n * }),\n * }),\n * })\n *\n * const updatePostOnFulfilled: TypedQueryOnQueryStarted<\n * PostsApiResponse,\n * QueryArgument,\n * BaseQueryFunction,\n * 'postsApi'\n * > = async (queryArgument, { dispatch, queryFulfilled }) => {\n * const result = await queryFulfilled\n *\n * const { posts } = result.data\n *\n * // Pre-fill the individual post entries with the results\n * // from the list endpoint query\n * dispatch(\n * baseApiSlice.util.upsertQueryEntries(\n * posts.map((post) => ({\n * endpointName: 'getPostById',\n * arg: post.id,\n * value: post,\n * })),\n * ),\n * )\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n * endpoints: (build) => ({\n * getPostsByUserId: build.query<PostsApiResponse, QueryArgument>({\n * query: (userId) => `/posts/user/${userId}`,\n *\n * onQueryStarted: updatePostOnFulfilled,\n * }),\n * }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedQueryOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleQueryExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleMutationExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific mutation.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedMutationOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n * id: number\n * title: string\n * userId: number\n * }\n *\n * type PostsApiResponse = {\n * posts: Post[]\n * total: number\n * skip: number\n * limit: number\n * }\n *\n * type QueryArgument = Pick<Post, 'id'> & Partial<Post>\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n * baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n * reducerPath: 'postsApi',\n * tagTypes: ['Posts'],\n * endpoints: (build) => ({\n * getPosts: build.query<PostsApiResponse, void>({\n * query: () => `/posts`,\n * }),\n *\n * getPostById: build.query<Post, number>({\n * query: (postId) => `/posts/${postId}`,\n * }),\n * }),\n * })\n *\n * const updatePostOnFulfilled: TypedMutationOnQueryStarted<\n * Post,\n * QueryArgument,\n * BaseQueryFunction,\n * 'postsApi'\n * > = async ({ id, ...patch }, { dispatch, queryFulfilled }) => {\n * const patchCollection = dispatch(\n * baseApiSlice.util.updateQueryData('getPostById', id, (draftPost) => {\n * Object.assign(draftPost, patch)\n * }),\n * )\n *\n * try {\n * await queryFulfilled\n * } catch {\n * patchCollection.undo()\n * }\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n * endpoints: (build) => ({\n * addPost: build.mutation<Post, Omit<QueryArgument, 'id'>>({\n * query: (body) => ({\n * url: `posts/add`,\n * method: 'POST',\n * body,\n * }),\n *\n * onQueryStarted: updatePostOnFulfilled,\n * }),\n *\n * updatePost: build.mutation<Post, QueryArgument>({\n * query: ({ id, ...patch }) => ({\n * url: `post/${id}`,\n * method: 'PATCH',\n * body: patch,\n * }),\n *\n * onQueryStarted: updatePostOnFulfilled,\n * }),\n * }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedMutationOnQueryStarted<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, ReducerPath extends string = string> = QueryLifecycleMutationExtraOptions<ResultType, QueryArgumentType, BaseQueryFunctionType, ReducerPath>['onQueryStarted'];\nexport const buildQueryLifecycleHandler: InternalHandlerBuilder = ({\n api,\n context,\n queryThunk,\n mutationThunk\n}) => {\n const isPendingThunk = isPending(queryThunk, mutationThunk);\n const isRejectedThunk = isRejected(queryThunk, mutationThunk);\n const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk);\n type CacheLifecycle = {\n resolve(value: {\n data: unknown;\n meta: unknown;\n }): unknown;\n reject(value: QueryFulfilledRejectionReason<any>): unknown;\n };\n const lifecycleMap: Record<string, CacheLifecycle> = {};\n const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n if (isPendingThunk(action)) {\n const {\n requestId,\n arg: {\n endpointName,\n originalArgs\n }\n } = action.meta;\n const endpointDefinition = context.endpointDefinitions[endpointName];\n const onQueryStarted = endpointDefinition?.onQueryStarted;\n if (onQueryStarted) {\n const lifecycle = {} as CacheLifecycle;\n const queryFulfilled = new (Promise as PromiseConstructorWithKnownReason)<{\n data: unknown;\n meta: unknown;\n }, QueryFulfilledRejectionReason<any>>((resolve, reject) => {\n lifecycle.resolve = resolve;\n lifecycle.reject = reject;\n });\n // prevent uncaught promise rejections from happening.\n // if the original promise is used in any way, that will create a new promise that will throw again\n queryFulfilled.catch(() => {});\n lifecycleMap[requestId] = lifecycle;\n const selector = (api.endpoints[endpointName] as any).select(endpointDefinition.type === DefinitionType.query ? originalArgs : requestId);\n const extra = mwApi.dispatch((_, __, extra) => extra);\n const lifecycleApi = {\n ...mwApi,\n getCacheEntry: () => selector(mwApi.getState()),\n requestId,\n extra,\n updateCachedData: (endpointDefinition.type === DefinitionType.query ? (updateRecipe: Recipe<any>) => mwApi.dispatch(api.util.updateQueryData(endpointName as never, originalArgs as never, updateRecipe)) : undefined) as any,\n queryFulfilled\n };\n onQueryStarted(originalArgs, lifecycleApi as any);\n }\n } else if (isFullfilledThunk(action)) {\n const {\n requestId,\n baseQueryMeta\n } = action.meta;\n lifecycleMap[requestId]?.resolve({\n data: action.payload,\n meta: baseQueryMeta\n });\n delete lifecycleMap[requestId];\n } else if (isRejectedThunk(action)) {\n const {\n requestId,\n rejectedWithValue,\n baseQueryMeta\n } = action.meta;\n lifecycleMap[requestId]?.reject({\n error: action.payload ?? action.error,\n isUnhandledError: !rejectedWithValue,\n meta: baseQueryMeta as any\n });\n delete lifecycleMap[requestId];\n }\n };\n return handler;\n};","import { QueryStatus } from '../apiState';\nimport type { QueryCacheKey } from '../apiState';\nimport { onFocus, onOnline } from '../setupListeners';\nimport type { ApiMiddlewareInternalHandler, InternalHandlerBuilder, SubMiddlewareApi } from './types';\nimport { countObjectKeys } from '../../utils/countObjectKeys';\nexport const buildWindowEventHandler: InternalHandlerBuilder = ({\n reducerPath,\n context,\n api,\n refetchQuery,\n internalState\n}) => {\n const {\n removeQueryResult\n } = api.internalActions;\n const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n if (onFocus.match(action)) {\n refetchValidQueries(mwApi, 'refetchOnFocus');\n }\n if (onOnline.match(action)) {\n refetchValidQueries(mwApi, 'refetchOnReconnect');\n }\n };\n function refetchValidQueries(api: SubMiddlewareApi, type: 'refetchOnFocus' | 'refetchOnReconnect') {\n const state = api.getState()[reducerPath];\n const queries = state.queries;\n const subscriptions = internalState.currentSubscriptions;\n context.batch(() => {\n for (const queryCacheKey of Object.keys(subscriptions)) {\n const querySubState = queries[queryCacheKey];\n const subscriptionSubState = subscriptions[queryCacheKey];\n if (!subscriptionSubState || !querySubState) continue;\n const shouldRefetch = Object.values(subscriptionSubState).some(sub => sub[type] === true) || Object.values(subscriptionSubState).every(sub => sub[type] === undefined) && state.config[type];\n if (shouldRefetch) {\n if (countObjectKeys(subscriptionSubState) === 0) {\n api.dispatch(removeQueryResult({\n queryCacheKey: queryCacheKey as QueryCacheKey\n }));\n } else if (querySubState.status !== QueryStatus.uninitialized) {\n api.dispatch(refetchQuery(querySubState));\n }\n }\n }\n });\n }\n return handler;\n};","import type { Action, Middleware, ThunkDispatch, UnknownAction } from '@reduxjs/toolkit';\nimport type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';\nimport type { QueryStatus, QuerySubState, RootState } from '../apiState';\nimport type { QueryThunkArg } from '../buildThunks';\nimport { createAction, isAction } from '../rtkImports';\nimport { buildBatchedActionsHandler } from './batchActions';\nimport { buildCacheCollectionHandler } from './cacheCollection';\nimport { buildCacheLifecycleHandler } from './cacheLifecycle';\nimport { buildDevCheckHandler } from './devMiddleware';\nimport { buildInvalidationByTagsHandler } from './invalidationByTags';\nimport { buildPollingHandler } from './polling';\nimport { buildQueryLifecycleHandler } from './queryLifecycle';\nimport type { BuildMiddlewareInput, InternalHandlerBuilder, InternalMiddlewareState } from './types';\nimport { buildWindowEventHandler } from './windowEventHandling';\nimport type { ApiEndpointQuery } from '../module';\nexport type { ReferenceCacheCollection } from './cacheCollection';\nexport type { MutationCacheLifecycleApi, QueryCacheLifecycleApi, ReferenceCacheLifecycle } from './cacheLifecycle';\nexport type { MutationLifecycleApi, QueryLifecycleApi, ReferenceQueryLifecycle, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './queryLifecycle';\nexport type { SubscriptionSelectors } from './types';\nexport function buildMiddleware<Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string>(input: BuildMiddlewareInput<Definitions, ReducerPath, TagTypes>) {\n const {\n reducerPath,\n queryThunk,\n api,\n context\n } = input;\n const {\n apiUid\n } = context;\n const actions = {\n invalidateTags: createAction<Array<TagTypes | FullTagDescription<TagTypes> | null | undefined>>(`${reducerPath}/invalidateTags`)\n };\n const isThisApiSliceAction = (action: Action) => action.type.startsWith(`${reducerPath}/`);\n const handlerBuilders: InternalHandlerBuilder[] = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler];\n const middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, UnknownAction>> = mwApi => {\n let initialized = false;\n const internalState: InternalMiddlewareState = {\n currentSubscriptions: {}\n };\n const builderArgs = {\n ...(input as any as BuildMiddlewareInput<EndpointDefinitions, string, string>),\n internalState,\n refetchQuery,\n isThisApiSliceAction\n };\n const handlers = handlerBuilders.map(build => build(builderArgs));\n const batchedActionsHandler = buildBatchedActionsHandler(builderArgs);\n const windowEventsHandler = buildWindowEventHandler(builderArgs);\n return next => {\n return action => {\n if (!isAction(action)) {\n return next(action);\n }\n if (!initialized) {\n initialized = true;\n // dispatch before any other action\n mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));\n }\n const mwApiWithNext = {\n ...mwApi,\n next\n };\n const stateBefore = mwApi.getState();\n const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore);\n let res: any;\n if (actionShouldContinue) {\n res = next(action);\n } else {\n res = internalProbeResult;\n }\n if (!!mwApi.getState()[reducerPath]) {\n // Only run these checks if the middleware is registered okay\n\n // This looks for actions that aren't specific to the API slice\n windowEventsHandler(action, mwApiWithNext, stateBefore);\n if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {\n // Only run these additional checks if the actions are part of the API slice,\n // or the action has hydration-related data\n for (const handler of handlers) {\n handler(action, mwApiWithNext, stateBefore);\n }\n }\n }\n return res;\n };\n };\n };\n return {\n middleware,\n actions\n };\n function refetchQuery(querySubState: Exclude<QuerySubState<any>, {\n status: QueryStatus.uninitialized;\n }>) {\n return (input.api.endpoints[querySubState.endpointName] as ApiEndpointQuery<any, any>).initiate(querySubState.originalArgs as any, {\n subscribe: false,\n forceRefetch: true\n });\n }\n}","import { buildCreateApi } from '../createApi';\nimport { coreModule } from './module';\nexport const createApi = /* @__PURE__ */buildCreateApi(coreModule());\nexport { QueryStatus } from './apiState';\nexport type { CombinedState, InfiniteData, InfiniteQueryConfigOptions, InfiniteQuerySubState, MutationKeys, QueryCacheKey, QueryKeys, QuerySubState, RootState, SubscriptionOptions } from './apiState';\nexport type { InfiniteQueryActionCreatorResult, MutationActionCreatorResult, QueryActionCreatorResult, StartQueryActionCreatorOptions } from './buildInitiate';\nexport type { MutationCacheLifecycleApi, MutationLifecycleApi, QueryCacheLifecycleApi, QueryLifecycleApi, SubscriptionSelectors, TypedMutationOnQueryStarted, TypedQueryOnQueryStarted } from './buildMiddleware/index';\nexport { skipToken } from './buildSelectors';\nexport type { InfiniteQueryResultSelectorResult, MutationResultSelectorResult, QueryResultSelectorResult, SkipToken } from './buildSelectors';\nexport type { SliceActions } from './buildSlice';\nexport type { PatchQueryDataThunk, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';\nexport { coreModuleName } from './module';\nexport type { ApiEndpointInfiniteQuery, ApiEndpointMutation, ApiEndpointQuery, CoreModule, InternalActions, PrefetchOptions, ThunkWithReturnValue } from './module';\nexport { setupListeners } from './setupListeners';\nexport { buildCreateApi, coreModule };"],"mappings":"AAqDO,IAAKA,QACVA,EAAA,cAAgB,gBAChBA,EAAA,QAAU,UACVA,EAAA,UAAY,YACZA,EAAA,SAAW,WAJDA,QAAA,IA+BL,SAASC,GAAsBC,EAAyC,CAC7E,MAAO,CACL,OAAAA,EACA,gBAAiBA,IAAW,gBAC5B,UAAWA,IAAW,UACtB,UAAWA,IAAW,YACtB,QAASA,IAAW,UACtB,CACF,CCxFA,OAAS,gBAAAC,EAAc,eAAAC,EAAa,kBAAAC,GAAgB,oBAAAC,GAAkB,mBAAAC,GAAiB,mBAAAC,GAAiB,WAAAC,GAAS,WAAAC,GAAS,YAAAC,GAAU,aA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BC,GAAeC,GAAW,CAAC","names":["QueryStatus","getRequestStatusFlags","status","createAction","createSlice","createSelector","createAsyncThunk","combineReducers","createNextState","isAnyOf","isAllOf","isAction","isPending","isRejected","isFulfilled","isRejectedWithValue","isAsyncThunkAction","prepareAutoBatched","SHOULD_AUTOBATCH","isPlainObject","nanoid","isPlainObject","copyWithStructuralSharing","oldObj","newObj","newKeys","oldKeys","isSameObject","mergeObj","key","countObjectKeys","obj","count","_key","flatten","arr","isAbsoluteUrl","url","isDocumentVisible","isNotNullish","v","isOnline","withoutTrailingSlash","url","withoutLeadingSlash","joinUrls","base","isAbsoluteUrl","delimiter","getOrInsert","map","key","value","defaultFetchFn","args","defaultValidateStatus","response","defaultIsJsonContentType","headers","stripUndefined","obj","isPlainObject","copy","k","v","fetchBaseQuery","baseUrl","prepareHeaders","x","fetchFn","paramsSerializer","isJsonContentType","jsonContentType","jsonReplacer","defaultTimeout","globalResponseHandler","globalValidateStatus","baseFetchOptions","arg","api","extraOptions","getState","extra","endpoint","forced","type","meta","url","params","responseHandler","validateStatus","timeout","rest","abortController","signal","config","isJsonifiable","body","divider","query","joinUrls","request","timedOut","timeoutId","e","responseClone","resultData","responseText","handleResponseError","handleResponse","r","text","HandledError","value","meta","defaultBackoff","attempt","maxRetries","attempts","timeout","resolve","res","fail","error","meta","HandledError","EMPTY_OPTIONS","retryWithBackoff","baseQuery","defaultOptions","args","api","extraOptions","possibleMaxRetries","x","options","_","__","retry","result","e","onFocus","createAction","onFocusLost","onOnline","onOffline","initialized","setupListeners","dispatch","customHandler","defaultHandler","handleFocus","handleFocusLost","handleOnline","handleOffline","handleVisibilityChange","isQueryDefinition","isMutationDefinition","isInfiniteQueryDefinition","calculateProvidedBy","description","result","error","queryArg","meta","assertTagTypes","isFunction","isNotNullish","expandTagDescription","t","isDraftable","produceWithPatches","asSafePromise","promise","fallback","forceQueryFnSymbol","isUpsertQuery","arg","buildInitiate","serializeQueryArgs","queryThunk","infiniteQueryThunk","mutationThunk","api","context","runningQueries","runningMutations","unsubscribeQueryResult","removeMutationResult","updateSubscriptionOptions","buildInitiateQuery","buildInitiateInfiniteQuery","buildInitiateMutation","getRunningQueryThunk","getRunningMutationThunk","getRunningQueriesThunk","getRunningMutationsThunk","endpointName","queryArgs","dispatch","endpointDefinition","queryCacheKey","_endpointName","fixedCacheKeyOrRequestId","isNotNullish","middlewareWarning","buildInitiateAnyQuery","queryAction","subscribe","forceRefetch","subscriptionOptions","forceQueryFn","rest","getState","thunk","commonThunkArgs","isQueryDefinition","direction","initialPageParam","selector","thunkResult","stateAfter","requestId","abort","skippedSynchronously","runningQuery","selectFromState","statePromise","result","options","running","getOrInsert","countObjectKeys","track","fixedCacheKey","unwrap","returnValuePromise","asSafePromise","data","error","reset","ret","defaultTransformResponse","baseQueryReturnValue","addShouldAutoBatch","arg","SHOULD_AUTOBATCH","buildThunks","reducerPath","baseQuery","endpointDefinitions","serializeQueryArgs","api","assertTagType","selectors","patchQueryData","endpointName","patches","updateProvided","dispatch","getState","endpointDefinition","queryCacheKey","newValue","providedTags","calculateProvidedBy","addToStart","items","item","max","newItems","addToEnd","updateQueryData","updateRecipe","currentState","ret","isDraftable","value","inversePatches","produceWithPatches","upsertQueryData","forceQueryFnSymbol","getTransformCallbackForEndpoint","transformFieldName","executeEndpoint","signal","abort","rejectWithValue","fulfillWithValue","extra","transformResponse","baseQueryApi","isForcedQuery","forceQueryFn","finalQueryReturnValue","fetchPage","data","param","maxPages","previous","finalQueryArg","pageResponse","executeRequest","addTo","result","extraOptions","HandledError","transformedResponse","infiniteQueryOptions","blankData","cachedData","existingData","getPreviousPageParam","getNextPageParam","initialPageParam","cachedPageParams","firstPageParam","totalPages","i","error","catchedError","transformErrorResponse","e","state","requestState","baseFetchOnMountOrArgChange","fulfilledVal","refetchVal","createQueryThunk","createAsyncThunk","isInfiniteQueryDefinition","queryThunkArg","currentArg","previousArg","direction","isUpsertQuery","isQueryDefinition","queryThunk","infiniteQueryThunk","mutationThunk","hasTheForce","options","hasMaxAge","prefetch","force","maxAge","queryAction","latestStateValue","lastFulfilledTs","matchesEndpoint","action","buildMatchThunkActions","thunk","isAllOf","isPending","isFulfilled","isRejected","pages","pageParams","lastIndex","calculateProvidedByThunk","type","isRejectedWithValue","isDraft","applyPatches","original","updateQuerySubstateIfExists","state","queryCacheKey","update","substate","getMutationCacheKey","id","updateMutationSubstateIfExists","initialState","buildSlice","reducerPath","queryThunk","mutationThunk","serializeQueryArgs","definitions","apiUid","extractRehydrationInfo","hasRehydrationInfo","assertTagType","config","resetApiState","createAction","writePendingCacheEntry","draft","arg","upserting","meta","endpointDefinition","isInfiniteQueryDefinition","writeFulfilledCacheEntry","payload","merge","fulfilledTimeStamp","baseQueryMeta","requestId","newData","createNextState","draftSubstateData","copyWithStructuralSharing","isDraft","original","querySlice","createSlice","prepareAutoBatched","action","entry","value","endpointName","SHOULD_AUTOBATCH","nanoid","patches","applyPatches","builder","isUpsertQuery","condition","error","queries","key","mutationSlice","cacheKey","startedTimeStamp","mutations","invalidationSlice","providedTags","tagTypeSubscriptions","idSubscriptions","foundAt","type","subscribedQueries","provided","incomingTags","cacheKeys","isAnyOf","isFulfilled","isRejectedWithValue","calculateProvidedByThunk","subscriptionSlice","d","a","internalSubscriptionsSlice","configSlice","isOnline","isDocumentVisible","onOnline","onOffline","onFocus","onFocusLost","combinedReducer","combineReducers","reducer","actions","skipToken","initialSubState","defaultQuerySubState","createNextState","defaultMutationSubState","buildSelectors","serializeQueryArgs","reducerPath","createSelector","selectSkippedQuery","state","selectSkippedMutation","buildQuerySelector","buildInfiniteQuerySelector","buildMutationSelector","selectInvalidatedBy","selectCachedArgsForQuery","selectApiState","selectQueries","selectMutations","selectQueryEntry","selectConfig","withRequestFlags","substate","getRequestStatusFlags","rootState","cacheKey","buildAnyQuerySelector","endpointName","endpointDefinition","combiner","queryArgs","serializedArgs","infiniteQueryOptions","withInfiniteQueryResultFlags","stateWithRequestFlags","isLoading","isError","direction","isForward","isBackward","getHasNextPage","getHasPreviousPage","id","mutationId","getMutationCacheKey","tags","apiState","toInvalidate","tag","isNotNullish","expandTagDescription","provided","invalidateSubscriptions","flatten","invalidate","queryCacheKey","querySubState","queryName","entry","options","data","getNextPageParam","getPreviousPageParam","_formatProdErrorMessage","cache","defaultSerializeQueryArgs","endpointName","queryArgs","serialized","cached","stringified","key","value","isPlainObject","acc","weakMapMemoize","buildCreateApi","modules","options","extractRehydrationInfo","action","optionsWithDefaults","queryArgsApi","finalSerializeQueryArgs","defaultSerializeQueryArgs","endpointSQA","initialResult","context","fn","nanoid","api","injectEndpoints","addTagTypes","endpoints","eT","endpointName","partialDefinition","initializedModules","m","inject","evaluatedEndpoints","x","definition","_formatProdErrorMessage","_formatProdErrorMessage","_NEVER","fakeBaseQuery","enablePatches","safeAssign","target","args","produceWithPatches","buildBatchedActionsHandler","api","queryThunk","internalState","subscriptionsPrefix","previousSubscriptions","updateSyncTimer","updateSubscriptionOptions","unsubscribeQueryResult","actuallyMutateSubscriptions","mutableState","action","queryCacheKey","requestId","options","arg","substate","mutated","state","key","condition","getSubscriptions","subscriptionSelectors","subscriptionsForQueryArg","countObjectKeys","mwApi","didMutate","actionShouldContinue","newSubscriptions","patches","produceWithPatches","isSubscriptionSliceAction","isAdditionalSubscriptionAction","isObjectEmpty","obj","k","THIRTY_TWO_BIT_MAX_TIMER_SECONDS","buildCacheCollectionHandler","reducerPath","api","queryThunk","context","internalState","selectQueryEntry","selectConfig","removeQueryResult","unsubscribeQueryResult","cacheEntriesUpserted","canTriggerUnsubscribe","isAnyOf","anySubscriptionsRemainingForKey","queryCacheKey","subscriptions","isObjectEmpty","currentRemovalTimeouts","handler","action","mwApi","state","config","queryCacheKeys","entry","handleUnsubscribeMany","key","timeout","queries","cacheKeys","handleUnsubscribe","endpointName","keepUnusedDataFor","finalKeepUnusedDataFor","currentTimeout","neverResolvedError","buildCacheLifecycleHandler","api","reducerPath","context","queryThunk","mutationThunk","internalState","selectQueryEntry","selectApiState","isQueryThunk","isAsyncThunkAction","isMutationThunk","isFulfilledThunk","isFulfilled","lifecycleMap","resolveLifecycleEntry","cacheKey","data","meta","lifecycle","removeLifecycleEntry","handler","action","mwApi","stateBefore","getCacheKey","checkForNewCacheKey","endpointName","requestId","originalArgs","oldEntry","newEntry","handleNewKey","queryDescription","value","queryCacheKey","getMutationCacheKey","endpointDefinition","onCacheEntryAdded","cacheEntryRemoved","resolve","cacheDataLoaded","selector","extra","_","__","lifecycleApi","updateRecipe","runningHandler","e","buildDevCheckHandler","api","apiUid","reducerPath","action","mwApi","buildInvalidationByTagsHandler","reducerPath","context","endpointDefinitions","mutationThunk","queryThunk","api","assertTagType","refetchQuery","internalState","removeQueryResult","isThunkActionWithTags","isAnyOf","isFulfilled","isRejectedWithValue","isQueryEnd","isRejected","pendingTagInvalidations","handler","action","mwApi","invalidateTags","calculateProvidedByThunk","calculateProvidedBy","hasPendingRequests","state","queries","mutations","cacheRecord","key","newTags","rootState","tags","toInvalidate","valuesArray","queryCacheKey","querySubState","subscriptionSubState","countObjectKeys","buildPollingHandler","reducerPath","queryThunk","api","refetchQuery","internalState","currentPolls","handler","action","mwApi","updatePollingInterval","startNextPoll","clearPolls","getCacheEntrySubscriptions","queryCacheKey","querySubState","subscriptions","state","lowestPollingInterval","skipPollingIfUnfocused","findLowestPollingInterval","currentPoll","nextPollTimestamp","cleanupPollForKey","key","existingPoll","subscribers","buildQueryLifecycleHandler","api","context","queryThunk","mutationThunk","isPendingThunk","isPending","isRejectedThunk","isRejected","isFullfilledThunk","isFulfilled","lifecycleMap","action","mwApi","requestId","endpointName","originalArgs","endpointDefinition","onQueryStarted","lifecycle","queryFulfilled","resolve","reject","selector","extra","_","__","lifecycleApi","updateRecipe","baseQueryMeta","rejectedWithValue","buildWindowEventHandler","reducerPath","context","api","refetchQuery","internalState","removeQueryResult","handler","action","mwApi","onFocus","refetchValidQueries","onOnline","type","state","queries","subscriptions","queryCacheKey","querySubState","subscriptionSubState","sub","countObjectKeys","buildMiddleware","input","reducerPath","queryThunk","api","context","apiUid","actions","createAction","isThisApiSliceAction","action","handlerBuilders","buildDevCheckHandler","buildCacheCollectionHandler","buildInvalidationByTagsHandler","buildPollingHandler","buildCacheLifecycleHandler","buildQueryLifecycleHandler","mwApi","initialized","builderArgs","refetchQuery","handlers","build","batchedActionsHandler","buildBatchedActionsHandler","windowEventsHandler","buildWindowEventHandler","next","isAction","mwApiWithNext","stateBefore","actionShouldContinue","internalProbeResult","res","handler","querySubState","coreModuleName","coreModule","createSelector","api","baseQuery","tagTypes","reducerPath","serializeQueryArgs","keepUnusedDataFor","refetchOnMountOrArgChange","refetchOnFocus","refetchOnReconnect","invalidationBehavior","context","enablePatches","assertTagType","tag","onOnline","onOffline","onFocus","onFocusLost","selectors","buildSelectors","selectInvalidatedBy","selectCachedArgsForQuery","buildQuerySelector","buildInfiniteQuerySelector","buildMutationSelector","safeAssign","queryThunk","infiniteQueryThunk","mutationThunk","patchQueryData","updateQueryData","upsertQueryData","prefetch","buildMatchThunkActions","buildThunks","reducer","sliceActions","buildSlice","middleware","middlewareActions","buildMiddleware","buildInitiateQuery","buildInitiateInfiniteQuery","buildInitiateMutation","getRunningMutationThunk","getRunningMutationsThunk","getRunningQueriesThunk","getRunningQueryThunk","buildInitiate","endpointName","definition","anyApi","endpoint","isQueryDefinition","isMutationDefinition","isInfiniteQueryDefinition","createApi","buildCreateApi","coreModule"]}