Index: node_modules/@reduxjs/toolkit/src/query/HandledError.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/HandledError.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/HandledError.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,6 @@
+export class HandledError {
+  constructor(
+    public readonly value: any,
+    public readonly meta: any = undefined,
+  ) {}
+}
Index: node_modules/@reduxjs/toolkit/src/query/apiTypes.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/apiTypes.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/apiTypes.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,124 @@
+import type { UnknownAction } from '@reduxjs/toolkit'
+import type { BaseQueryFn } from './baseQueryTypes'
+import type { CombinedState, CoreModule, QueryKeys } from './core'
+import type { ApiModules } from './core/module'
+import type { CreateApiOptions } from './createApi'
+import type {
+  EndpointBuilder,
+  EndpointDefinition,
+  EndpointDefinitions,
+  UpdateDefinitions,
+} from './endpointDefinitions'
+import type {
+  NoInfer,
+  UnionToIntersection,
+  WithRequiredProp,
+} from './tsHelpers'
+
+export type ModuleName = keyof ApiModules<any, any, any, any>
+
+export type Module<Name extends ModuleName> = {
+  name: Name
+  init<
+    BaseQuery extends BaseQueryFn,
+    Definitions extends EndpointDefinitions,
+    ReducerPath extends string,
+    TagTypes extends string,
+  >(
+    api: Api<BaseQuery, EndpointDefinitions, ReducerPath, TagTypes, ModuleName>,
+    options: WithRequiredProp<
+      CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>,
+      | 'reducerPath'
+      | 'serializeQueryArgs'
+      | 'keepUnusedDataFor'
+      | 'refetchOnMountOrArgChange'
+      | 'refetchOnFocus'
+      | 'refetchOnReconnect'
+      | 'invalidationBehavior'
+      | 'tagTypes'
+    >,
+    context: ApiContext<Definitions>,
+  ): {
+    injectEndpoint(
+      endpointName: string,
+      definition: EndpointDefinition<any, any, any, any>,
+    ): void
+  }
+}
+
+export interface ApiContext<Definitions extends EndpointDefinitions> {
+  apiUid: string
+  endpointDefinitions: Definitions
+  batch(cb: () => void): void
+  extractRehydrationInfo: (
+    action: UnknownAction,
+  ) => CombinedState<any, any, any> | undefined
+  hasRehydrationInfo: (action: UnknownAction) => boolean
+}
+
+export const getEndpointDefinition = <
+  Definitions extends EndpointDefinitions,
+  EndpointName extends keyof Definitions,
+>(
+  context: ApiContext<Definitions>,
+  endpointName: EndpointName,
+) => context.endpointDefinitions[endpointName]
+
+export type Api<
+  BaseQuery extends BaseQueryFn,
+  Definitions extends EndpointDefinitions,
+  ReducerPath extends string,
+  TagTypes extends string,
+  Enhancers extends ModuleName = CoreModule,
+> = UnionToIntersection<
+  ApiModules<BaseQuery, Definitions, ReducerPath, TagTypes>[Enhancers]
+> & {
+  /**
+   * A function to inject the endpoints into the original API, but also give you that same API with correct types for these endpoints back. Useful with code-splitting.
+   */
+  injectEndpoints<NewDefinitions extends EndpointDefinitions>(_: {
+    endpoints: (
+      build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>,
+    ) => NewDefinitions
+    /**
+     * Optionally allows endpoints to be overridden if defined by multiple `injectEndpoints` calls.
+     *
+     * If set to `true`, will override existing endpoints with the new definition.
+     * If set to `'throw'`, will throw an error if an endpoint is redefined with a different definition.
+     * If set to `false` (or unset), will not override existing endpoints with the new definition, and log a warning in development.
+     */
+    overrideExisting?: boolean | 'throw'
+  }): Api<
+    BaseQuery,
+    Definitions & NewDefinitions,
+    ReducerPath,
+    TagTypes,
+    Enhancers
+  >
+  /**
+   *A function to enhance a generated API with additional information. Useful with code-generation.
+   */
+  enhanceEndpoints<
+    NewTagTypes extends string = never,
+    NewDefinitions extends EndpointDefinitions = never,
+  >(_: {
+    addTagTypes?: readonly NewTagTypes[]
+    endpoints?: UpdateDefinitions<
+      Definitions,
+      TagTypes | NoInfer<NewTagTypes>,
+      NewDefinitions
+    > extends infer NewDefinitions
+      ? {
+          [K in keyof NewDefinitions]?:
+            | Partial<NewDefinitions[K]>
+            | ((definition: NewDefinitions[K]) => void)
+        }
+      : never
+  }): Api<
+    BaseQuery,
+    UpdateDefinitions<Definitions, TagTypes | NewTagTypes, NewDefinitions>,
+    ReducerPath,
+    TagTypes | NewTagTypes,
+    Enhancers
+  >
+}
Index: node_modules/@reduxjs/toolkit/src/query/baseQueryTypes.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/baseQueryTypes.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/baseQueryTypes.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,101 @@
+import type { ThunkDispatch } from '@reduxjs/toolkit'
+import type { MaybePromise, UnwrapPromise } from './tsHelpers'
+
+export interface BaseQueryApi {
+  signal: AbortSignal
+  abort: (reason?: string) => void
+  dispatch: ThunkDispatch<any, any, any>
+  getState: () => unknown
+  extra: unknown
+  endpoint: string
+  type: 'query' | 'mutation'
+  /**
+   * Only available for queries: indicates if a query has been forced,
+   * i.e. it would have been fetched even if there would already be a cache entry
+   * (this does not mean that there is already a cache entry though!)
+   *
+   * This can be used to for example add a `Cache-Control: no-cache` header for
+   * invalidated queries.
+   */
+  forced?: boolean
+  /**
+   * Only available for queries: the cache key that was used to store the query result
+   */
+  queryCacheKey?: string
+}
+
+export type QueryReturnValue<T = unknown, E = unknown, M = unknown> =
+  | {
+      error: E
+      data?: undefined
+      meta?: M
+    }
+  | {
+      error?: undefined
+      data: T
+      meta?: M
+    }
+
+export type BaseQueryFn<
+  Args = any,
+  Result = unknown,
+  Error = unknown,
+  DefinitionExtraOptions = {},
+  Meta = {},
+> = (
+  args: Args,
+  api: BaseQueryApi,
+  extraOptions: DefinitionExtraOptions,
+) => MaybePromise<QueryReturnValue<Result, Error, Meta>>
+
+export type BaseQueryEnhancer<
+  AdditionalArgs = unknown,
+  AdditionalDefinitionExtraOptions = unknown,
+  Config = void,
+> = <BaseQuery extends BaseQueryFn>(
+  baseQuery: BaseQuery,
+  config: Config,
+) => BaseQueryFn<
+  BaseQueryArg<BaseQuery> & AdditionalArgs,
+  BaseQueryResult<BaseQuery>,
+  BaseQueryError<BaseQuery>,
+  BaseQueryExtraOptions<BaseQuery> & AdditionalDefinitionExtraOptions,
+  NonNullable<BaseQueryMeta<BaseQuery>>
+>
+
+/**
+ * @public
+ */
+export type BaseQueryResult<BaseQuery extends BaseQueryFn> =
+  UnwrapPromise<ReturnType<BaseQuery>> extends infer Unwrapped
+    ? Unwrapped extends { data: any }
+      ? Unwrapped['data']
+      : never
+    : never
+
+/**
+ * @public
+ */
+export type BaseQueryMeta<BaseQuery extends BaseQueryFn> = UnwrapPromise<
+  ReturnType<BaseQuery>
+>['meta']
+
+/**
+ * @public
+ */
+export type BaseQueryError<BaseQuery extends BaseQueryFn> = Exclude<
+  UnwrapPromise<ReturnType<BaseQuery>>,
+  { error?: undefined }
+>['error']
+
+/**
+ * @public
+ */
+export type BaseQueryArg<T extends (arg: any, ...args: any[]) => any> =
+  T extends (arg: infer A, ...args: any[]) => any ? A : any
+
+/**
+ * @public
+ */
+export type BaseQueryExtraOptions<BaseQuery extends BaseQueryFn> =
+  Parameters<BaseQuery>[2]
Index: node_modules/@reduxjs/toolkit/src/query/core/apiState.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/apiState.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/apiState.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,377 @@
+import type { SerializedError } from '@reduxjs/toolkit'
+import type { BaseQueryError } from '../baseQueryTypes'
+import type {
+  BaseEndpointDefinition,
+  EndpointDefinitions,
+  FullTagDescription,
+  InfiniteQueryDefinition,
+  MutationDefinition,
+  PageParamFrom,
+  QueryArgFromAnyQuery,
+  QueryDefinition,
+  ResultTypeFrom,
+} from '../endpointDefinitions'
+import type { Id, WithRequiredProp } from '../tsHelpers'
+
+export type QueryCacheKey = string & { _type: 'queryCacheKey' }
+export type QuerySubstateIdentifier = { queryCacheKey: QueryCacheKey }
+export type MutationSubstateIdentifier =
+  | { requestId: string; fixedCacheKey?: string }
+  | { requestId?: string; fixedCacheKey: string }
+
+export type RefetchConfigOptions = {
+  refetchOnMountOrArgChange: boolean | number
+  refetchOnReconnect: boolean
+  refetchOnFocus: boolean
+}
+
+export type InfiniteQueryConfigOptions<DataType, PageParam, QueryArg> = {
+  /**
+   * The initial page parameter to use for the first page fetch.
+   */
+  initialPageParam: PageParam
+  /**
+   * This function is required to automatically get the next cursor for infinite queries.
+   * The result will also be used to determine the value of `hasNextPage`.
+   */
+  getNextPageParam: (
+    lastPage: DataType,
+    allPages: Array<DataType>,
+    lastPageParam: PageParam,
+    allPageParams: Array<PageParam>,
+    queryArg: QueryArg,
+  ) => PageParam | undefined | null
+  /**
+   * This function can be set to automatically get the previous cursor for infinite queries.
+   * The result will also be used to determine the value of `hasPreviousPage`.
+   */
+  getPreviousPageParam?: (
+    firstPage: DataType,
+    allPages: Array<DataType>,
+    firstPageParam: PageParam,
+    allPageParams: Array<PageParam>,
+    queryArg: QueryArg,
+  ) => PageParam | undefined | null
+  /**
+   * If specified, only keep this many pages in cache at once.
+   * If additional pages are fetched, older pages in the other
+   * direction will be dropped from the cache.
+   */
+  maxPages?: number
+  /**
+   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched
+   * (due to tag invalidation, polling, arg change configuration, or manual refetching),
+   * RTK Query will try to sequentially refetch all pages currently in the cache.
+   * When `false` only the first page will be refetched.
+   */
+  refetchCachedPages?: boolean
+}
+
+export type InfiniteData<DataType, PageParam> = {
+  pages: Array<DataType>
+  pageParams: Array<PageParam>
+}
+
+// NOTE: DO NOT import and use this for runtime comparisons internally,
+// except in the RTKQ React package. Use the string versions just below this.
+// ESBuild auto-inlines TS enums, which bloats our bundle with many repeated
+// constants like "initialized":
+// https://github.com/evanw/esbuild/releases/tag/v0.14.7
+// We still have to use this in the React package since we don't publicly export
+// the string constants below.
+/**
+ * Strings describing the query state at any given time.
+ */
+export enum QueryStatus {
+  uninitialized = 'uninitialized',
+  pending = 'pending',
+  fulfilled = 'fulfilled',
+  rejected = 'rejected',
+}
+
+// Use these string constants for runtime comparisons internally
+export const STATUS_UNINITIALIZED = QueryStatus.uninitialized
+export const STATUS_PENDING = QueryStatus.pending
+export const STATUS_FULFILLED = QueryStatus.fulfilled
+export const STATUS_REJECTED = QueryStatus.rejected
+
+export type RequestStatusFlags =
+  | {
+      status: QueryStatus.uninitialized
+      isUninitialized: true
+      isLoading: false
+      isSuccess: false
+      isError: false
+    }
+  | {
+      status: QueryStatus.pending
+      isUninitialized: false
+      isLoading: true
+      isSuccess: false
+      isError: false
+    }
+  | {
+      status: QueryStatus.fulfilled
+      isUninitialized: false
+      isLoading: false
+      isSuccess: true
+      isError: false
+    }
+  | {
+      status: QueryStatus.rejected
+      isUninitialized: false
+      isLoading: false
+      isSuccess: false
+      isError: true
+    }
+
+export function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags {
+  return {
+    status,
+    isUninitialized: status === STATUS_UNINITIALIZED,
+    isLoading: status === STATUS_PENDING,
+    isSuccess: status === STATUS_FULFILLED,
+    isError: status === STATUS_REJECTED,
+  } as any
+}
+
+/**
+ * @public
+ */
+export type SubscriptionOptions = {
+  /**
+   * How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).
+   */
+  pollingInterval?: number
+  /**
+   *  Defaults to 'false'. This setting allows you to control whether RTK Query will continue polling if the window is not focused.
+   *
+   *  If pollingInterval is not set or set to 0, this **will not be evaluated** until pollingInterval is greater than 0.
+   *
+   *  Note: requires [`setupListeners`](./setupListeners) to have been called.
+   */
+  skipPollingIfUnfocused?: boolean
+  /**
+   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.
+   *
+   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
+   *
+   * Note: requires [`setupListeners`](./setupListeners) to have been called.
+   */
+  refetchOnReconnect?: boolean
+  /**
+   * 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.
+   *
+   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
+   *
+   * Note: requires [`setupListeners`](./setupListeners) to have been called.
+   */
+  refetchOnFocus?: boolean
+}
+export type SubscribersInternal = Map<string, SubscriptionOptions>
+export type Subscribers = { [requestId: string]: SubscriptionOptions }
+export type QueryKeys<Definitions extends EndpointDefinitions> = {
+  [K in keyof Definitions]: Definitions[K] extends QueryDefinition<
+    any,
+    any,
+    any,
+    any
+  >
+    ? K
+    : never
+}[keyof Definitions]
+
+export type InfiniteQueryKeys<Definitions extends EndpointDefinitions> = {
+  [K in keyof Definitions]: Definitions[K] extends InfiniteQueryDefinition<
+    any,
+    any,
+    any,
+    any,
+    any
+  >
+    ? K
+    : never
+}[keyof Definitions]
+
+export type MutationKeys<Definitions extends EndpointDefinitions> = {
+  [K in keyof Definitions]: Definitions[K] extends MutationDefinition<
+    any,
+    any,
+    any,
+    any
+  >
+    ? K
+    : never
+}[keyof Definitions]
+
+type BaseQuerySubState<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+  DataType = ResultTypeFrom<D>,
+> = {
+  /**
+   * The argument originally passed into the hook or `initiate` action call
+   */
+  originalArgs: QueryArgFromAnyQuery<D>
+  /**
+   * A unique ID associated with the request
+   */
+  requestId: string
+  /**
+   * The received data from the query
+   */
+  data?: DataType
+  /**
+   * The received error if applicable
+   */
+  error?:
+    | SerializedError
+    | (D extends QueryDefinition<any, infer BaseQuery, any, any>
+        ? BaseQueryError<BaseQuery>
+        : never)
+  /**
+   * The name of the endpoint associated with the query
+   */
+  endpointName: string
+  /**
+   * Time that the latest query started
+   */
+  startedTimeStamp: number
+  /**
+   * Time that the latest query was fulfilled
+   */
+  fulfilledTimeStamp?: number
+}
+
+export type QuerySubState<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+  DataType = ResultTypeFrom<D>,
+> = Id<
+  | ({ status: QueryStatus.fulfilled } & WithRequiredProp<
+      BaseQuerySubState<D, DataType>,
+      'data' | 'fulfilledTimeStamp'
+    > & { error: undefined })
+  | ({ status: QueryStatus.pending } & BaseQuerySubState<D, DataType>)
+  | ({ status: QueryStatus.rejected } & WithRequiredProp<
+      BaseQuerySubState<D, DataType>,
+      'error'
+    >)
+  | {
+      status: QueryStatus.uninitialized
+      originalArgs?: undefined
+      data?: undefined
+      error?: undefined
+      requestId?: undefined
+      endpointName?: string
+      startedTimeStamp?: undefined
+      fulfilledTimeStamp?: undefined
+    }
+>
+
+export type InfiniteQueryDirection = 'forward' | 'backward'
+
+export type InfiniteQuerySubState<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+> =
+  D extends InfiniteQueryDefinition<any, any, any, any, any>
+    ? QuerySubState<D, InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>> & {
+        direction?: InfiniteQueryDirection
+      }
+    : never
+
+type BaseMutationSubState<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+> = {
+  requestId: string
+  data?: ResultTypeFrom<D>
+  error?:
+    | SerializedError
+    | (D extends MutationDefinition<any, infer BaseQuery, any, any>
+        ? BaseQueryError<BaseQuery>
+        : never)
+  endpointName: string
+  startedTimeStamp: number
+  fulfilledTimeStamp?: number
+}
+
+export type MutationSubState<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+> =
+  | (({
+      status: QueryStatus.fulfilled
+    } & WithRequiredProp<
+      BaseMutationSubState<D>,
+      'data' | 'fulfilledTimeStamp'
+    >) & { error: undefined })
+  | (({ status: QueryStatus.pending } & BaseMutationSubState<D>) & {
+      data?: undefined
+    })
+  | ({ status: QueryStatus.rejected } & WithRequiredProp<
+      BaseMutationSubState<D>,
+      'error'
+    >)
+  | {
+      requestId?: undefined
+      status: QueryStatus.uninitialized
+      data?: undefined
+      error?: undefined
+      endpointName?: string
+      startedTimeStamp?: undefined
+      fulfilledTimeStamp?: undefined
+    }
+
+export type CombinedState<
+  D extends EndpointDefinitions,
+  E extends string,
+  ReducerPath extends string,
+> = {
+  queries: QueryState<D>
+  mutations: MutationState<D>
+  provided: InvalidationState<E>
+  subscriptions: SubscriptionState
+  config: ConfigState<ReducerPath>
+}
+
+export type InvalidationState<TagTypes extends string> = {
+  tags: {
+    [_ in TagTypes]: {
+      [id: string]: Array<QueryCacheKey>
+      [id: number]: Array<QueryCacheKey>
+    }
+  }
+  keys: Record<QueryCacheKey, Array<FullTagDescription<any>>>
+}
+
+export type QueryState<D extends EndpointDefinitions> = {
+  [queryCacheKey: string]:
+    | QuerySubState<D[string]>
+    | InfiniteQuerySubState<D[string]>
+    | undefined
+}
+
+export type SubscriptionInternalState = Map<string, SubscribersInternal>
+
+export type SubscriptionState = {
+  [queryCacheKey: string]: Subscribers | undefined
+}
+
+export type ConfigState<ReducerPath> = RefetchConfigOptions & {
+  reducerPath: ReducerPath
+  online: boolean
+  focused: boolean
+  middlewareRegistered: boolean | 'conflict'
+} & ModifiableConfigState
+
+export type ModifiableConfigState = {
+  keepUnusedDataFor: number
+  invalidationBehavior: 'delayed' | 'immediately'
+} & RefetchConfigOptions
+
+export type MutationState<D extends EndpointDefinitions> = {
+  [requestId: string]: MutationSubState<D[string]> | undefined
+}
+
+export type RootState<
+  Definitions extends EndpointDefinitions,
+  TagTypes extends string,
+  ReducerPath extends string,
+> = { [P in ReducerPath]: CombinedState<Definitions, TagTypes, P> }
Index: node_modules/@reduxjs/toolkit/src/query/core/buildInitiate.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildInitiate.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildInitiate.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,596 @@
+import type {
+  AsyncThunkAction,
+  SafePromise,
+  SerializedError,
+  ThunkAction,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import type { Dispatch } from 'redux'
+import { asSafePromise } from '../../tsHelpers'
+import { getEndpointDefinition, type Api, type ApiContext } from '../apiTypes'
+import type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes'
+import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
+import {
+  ENDPOINT_QUERY,
+  isQueryDefinition,
+  type EndpointDefinition,
+  type EndpointDefinitions,
+  type InfiniteQueryArgFrom,
+  type InfiniteQueryDefinition,
+  type MutationDefinition,
+  type PageParamFrom,
+  type QueryArgFrom,
+  type QueryDefinition,
+  type ResultTypeFrom,
+} from '../endpointDefinitions'
+import { filterNullishValues } from '../utils'
+import type {
+  InfiniteData,
+  InfiniteQueryConfigOptions,
+  InfiniteQueryDirection,
+  SubscriptionOptions,
+} from './apiState'
+import type {
+  InfiniteQueryResultSelectorResult,
+  QueryResultSelectorResult,
+} from './buildSelectors'
+import type {
+  InfiniteQueryThunk,
+  InfiniteQueryThunkArg,
+  MutationThunk,
+  QueryThunk,
+  QueryThunkArg,
+  ThunkApiMetaConfig,
+} from './buildThunks'
+import type { ApiEndpointQuery } from './module'
+import type { InternalMiddlewareState } from './buildMiddleware/types'
+
+export type BuildInitiateApiEndpointQuery<
+  Definition extends QueryDefinition<any, any, any, any, any>,
+> = {
+  initiate: StartQueryActionCreator<Definition>
+}
+
+export type BuildInitiateApiEndpointInfiniteQuery<
+  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = {
+  initiate: StartInfiniteQueryActionCreator<Definition>
+}
+
+export type BuildInitiateApiEndpointMutation<
+  Definition extends MutationDefinition<any, any, any, any, any>,
+> = {
+  initiate: StartMutationActionCreator<Definition>
+}
+
+export const forceQueryFnSymbol = Symbol('forceQueryFn')
+export const isUpsertQuery = (arg: QueryThunkArg) =>
+  typeof arg[forceQueryFnSymbol] === 'function'
+
+export type StartQueryActionCreatorOptions = {
+  subscribe?: boolean
+  forceRefetch?: boolean | number
+  subscriptionOptions?: SubscriptionOptions
+  [forceQueryFnSymbol]?: () => QueryReturnValue
+}
+
+type RefetchOptions = {
+  refetchCachedPages?: boolean
+}
+
+export type StartInfiniteQueryActionCreatorOptions<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = StartQueryActionCreatorOptions & {
+  direction?: InfiniteQueryDirection
+  param?: unknown
+} & Partial<
+    Pick<
+      Partial<
+        InfiniteQueryConfigOptions<
+          ResultTypeFrom<D>,
+          PageParamFrom<D>,
+          InfiniteQueryArgFrom<D>
+        >
+      >,
+      'initialPageParam' | 'refetchCachedPages'
+    >
+  >
+
+type AnyQueryActionCreator<D extends EndpointDefinition<any, any, any, any>> = (
+  arg: any,
+  options?: StartQueryActionCreatorOptions,
+) => ThunkAction<AnyActionCreatorResult, any, any, UnknownAction>
+
+type StartQueryActionCreator<
+  D extends QueryDefinition<any, any, any, any, any>,
+> = (
+  arg: QueryArgFrom<D>,
+  options?: StartQueryActionCreatorOptions,
+) => ThunkAction<QueryActionCreatorResult<D>, any, any, UnknownAction>
+
+export type StartInfiniteQueryActionCreator<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = (
+  arg: InfiniteQueryArgFrom<D>,
+  options?: StartInfiniteQueryActionCreatorOptions<D>,
+) => ThunkAction<InfiniteQueryActionCreatorResult<D>, any, any, UnknownAction>
+
+type QueryActionCreatorFields = {
+  requestId: string
+  subscriptionOptions: SubscriptionOptions | undefined
+  abort(): void
+  unsubscribe(): void
+  updateSubscriptionOptions(options: SubscriptionOptions): void
+  queryCacheKey: string
+}
+
+type AnyActionCreatorResult = SafePromise<any> &
+  QueryActionCreatorFields & {
+    arg: any
+    unwrap(): Promise<any>
+    refetch(options?: RefetchOptions): AnyActionCreatorResult
+  }
+
+export type QueryActionCreatorResult<
+  D extends QueryDefinition<any, any, any, any>,
+> = SafePromise<QueryResultSelectorResult<D>> &
+  QueryActionCreatorFields & {
+    arg: QueryArgFrom<D>
+    unwrap(): Promise<ResultTypeFrom<D>>
+    refetch(): QueryActionCreatorResult<D>
+  }
+
+export type InfiniteQueryActionCreatorResult<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = SafePromise<InfiniteQueryResultSelectorResult<D>> &
+  QueryActionCreatorFields & {
+    arg: InfiniteQueryArgFrom<D>
+    unwrap(): Promise<InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>>
+    refetch(
+      options?: Pick<
+        StartInfiniteQueryActionCreatorOptions<D>,
+        'refetchCachedPages'
+      >,
+    ): InfiniteQueryActionCreatorResult<D>
+  }
+
+type StartMutationActionCreator<
+  D extends MutationDefinition<any, any, any, any>,
+> = (
+  arg: QueryArgFrom<D>,
+  options?: {
+    /**
+     * If this mutation should be tracked in the store.
+     * If you just want to manually trigger this mutation using `dispatch` and don't care about the
+     * result, state & potential errors being held in store, you can set this to false.
+     * (defaults to `true`)
+     */
+    track?: boolean
+    fixedCacheKey?: string
+  },
+) => ThunkAction<MutationActionCreatorResult<D>, any, any, UnknownAction>
+
+export type MutationActionCreatorResult<
+  D extends MutationDefinition<any, any, any, any>,
+> = SafePromise<
+  | {
+      data: ResultTypeFrom<D>
+      error?: undefined
+    }
+  | {
+      data?: undefined
+      error:
+        | Exclude<
+            BaseQueryError<
+              D extends MutationDefinition<any, infer BaseQuery, any, any>
+                ? BaseQuery
+                : never
+            >,
+            undefined
+          >
+        | SerializedError
+    }
+> & {
+  /** @internal */
+  arg: {
+    /**
+     * The name of the given endpoint for the mutation
+     */
+    endpointName: string
+    /**
+     * The original arguments supplied to the mutation call
+     */
+    originalArgs: QueryArgFrom<D>
+    /**
+     * Whether the mutation is being tracked in the store.
+     */
+    track?: boolean
+    fixedCacheKey?: string
+  }
+  /**
+   * A unique string generated for the request sequence
+   */
+  requestId: string
+
+  /**
+   * A method to cancel the mutation promise. Note that this is not intended to prevent the mutation
+   * that was fired off from reaching the server, but only to assist in handling the response.
+   *
+   * Calling `abort()` prior to the promise resolving will force it to reach the error state with
+   * the serialized error:
+   * `{ name: 'AbortError', message: 'Aborted' }`
+   *
+   * @example
+   * ```ts
+   * const [updateUser] = useUpdateUserMutation();
+   *
+   * useEffect(() => {
+   *   const promise = updateUser(id);
+   *   promise
+   *     .unwrap()
+   *     .catch((err) => {
+   *       if (err.name === 'AbortError') return;
+   *       // else handle the unexpected error
+   *     })
+   *
+   *   return () => {
+   *     promise.abort();
+   *   }
+   * }, [id, updateUser])
+   * ```
+   */
+  abort(): void
+  /**
+   * Unwraps a mutation call to provide the raw response/error.
+   *
+   * @remarks
+   * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Using .unwrap"
+   * addPost({ id: 1, name: 'Example' })
+   *   .unwrap()
+   *   .then((payload) => console.log('fulfilled', payload))
+   *   .catch((error) => console.error('rejected', error));
+   * ```
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Using .unwrap with async await"
+   * try {
+   *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
+   *   console.log('fulfilled', payload)
+   * } catch (error) {
+   *   console.error('rejected', error);
+   * }
+   * ```
+   */
+  unwrap(): Promise<ResultTypeFrom<D>>
+  /**
+   * A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.
+   The value returned by the hook will reset to `isUninitialized` afterwards.
+   */
+  reset(): void
+}
+
+export function buildInitiate({
+  serializeQueryArgs,
+  queryThunk,
+  infiniteQueryThunk,
+  mutationThunk,
+  api,
+  context,
+  getInternalState,
+}: {
+  serializeQueryArgs: InternalSerializeQueryArgs
+  queryThunk: QueryThunk
+  infiniteQueryThunk: InfiniteQueryThunk<any>
+  mutationThunk: MutationThunk
+  api: Api<any, EndpointDefinitions, any, any>
+  context: ApiContext<EndpointDefinitions>
+  getInternalState: (dispatch: Dispatch) => InternalMiddlewareState
+}) {
+  const getRunningQueries = (dispatch: Dispatch) =>
+    getInternalState(dispatch)?.runningQueries
+  const getRunningMutations = (dispatch: Dispatch) =>
+    getInternalState(dispatch)?.runningMutations
+
+  const {
+    unsubscribeQueryResult,
+    removeMutationResult,
+    updateSubscriptionOptions,
+  } = api.internalActions
+  return {
+    buildInitiateQuery,
+    buildInitiateInfiniteQuery,
+    buildInitiateMutation,
+    getRunningQueryThunk,
+    getRunningMutationThunk,
+    getRunningQueriesThunk,
+    getRunningMutationsThunk,
+  }
+
+  function getRunningQueryThunk(endpointName: string, queryArgs: any) {
+    return (dispatch: Dispatch) => {
+      const endpointDefinition = getEndpointDefinition(context, endpointName)
+      const queryCacheKey = serializeQueryArgs({
+        queryArgs,
+        endpointDefinition,
+        endpointName,
+      })
+      return getRunningQueries(dispatch)?.get(queryCacheKey) as
+        | QueryActionCreatorResult<never>
+        | InfiniteQueryActionCreatorResult<never>
+        | undefined
+    }
+  }
+
+  function getRunningMutationThunk(
+    /**
+     * this is only here to allow TS to infer the result type by input value
+     * we could use it to validate the result, but it's probably not necessary
+     */
+    _endpointName: string,
+    fixedCacheKeyOrRequestId: string,
+  ) {
+    return (dispatch: Dispatch) => {
+      return getRunningMutations(dispatch)?.get(fixedCacheKeyOrRequestId) as
+        | MutationActionCreatorResult<never>
+        | undefined
+    }
+  }
+
+  function getRunningQueriesThunk() {
+    return (dispatch: Dispatch) =>
+      filterNullishValues(getRunningQueries(dispatch))
+  }
+
+  function getRunningMutationsThunk() {
+    return (dispatch: Dispatch) =>
+      filterNullishValues(getRunningMutations(dispatch))
+  }
+
+  function middlewareWarning(dispatch: Dispatch) {
+    if (process.env.NODE_ENV !== 'production') {
+      if ((middlewareWarning as any).triggered) return
+      const returnedValue = dispatch(
+        api.internalActions.internal_getRTKQSubscriptions(),
+      )
+
+      ;(middlewareWarning as any).triggered = true
+
+      // The RTKQ middleware should return the internal state object,
+      // but it should _not_ be the action object.
+      if (
+        typeof returnedValue !== 'object' ||
+        typeof returnedValue?.type === 'string'
+      ) {
+        // Otherwise, must not have been added
+        throw new Error(
+          `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
+You must add the middleware for RTK-Query to function correctly!`,
+        )
+      }
+    }
+  }
+
+  function buildInitiateAnyQuery<T extends 'query' | 'infiniteQuery'>(
+    endpointName: string,
+    endpointDefinition:
+      | QueryDefinition<any, any, any, any>
+      | InfiniteQueryDefinition<any, any, any, any, any>,
+  ) {
+    const queryAction: AnyQueryActionCreator<any> =
+      (
+        arg,
+        {
+          subscribe = true,
+          forceRefetch,
+          subscriptionOptions,
+          [forceQueryFnSymbol]: forceQueryFn,
+          ...rest
+        } = {},
+      ) =>
+      (dispatch, getState) => {
+        const queryCacheKey = serializeQueryArgs({
+          queryArgs: arg,
+          endpointDefinition,
+          endpointName,
+        })
+
+        let thunk: AsyncThunkAction<unknown, QueryThunkArg, ThunkApiMetaConfig>
+
+        const commonThunkArgs = {
+          ...rest,
+          type: ENDPOINT_QUERY as 'query',
+          subscribe,
+          forceRefetch: forceRefetch,
+          subscriptionOptions,
+          endpointName,
+          originalArgs: arg,
+          queryCacheKey,
+          [forceQueryFnSymbol]: forceQueryFn,
+        }
+
+        if (isQueryDefinition(endpointDefinition)) {
+          thunk = queryThunk(commonThunkArgs)
+        } else {
+          const { direction, initialPageParam, refetchCachedPages } =
+            rest as Pick<
+              InfiniteQueryThunkArg<any>,
+              'direction' | 'initialPageParam' | 'refetchCachedPages'
+            >
+          thunk = infiniteQueryThunk({
+            ...(commonThunkArgs as InfiniteQueryThunkArg<any>),
+            // Supply these even if undefined. This helps with a field existence
+            // check over in `buildSlice.ts`
+            direction,
+            initialPageParam,
+            refetchCachedPages,
+          })
+        }
+
+        const selector = (
+          api.endpoints[endpointName] as ApiEndpointQuery<any, any>
+        ).select(arg)
+
+        const thunkResult = dispatch(thunk)
+        const stateAfter = selector(getState())
+
+        middlewareWarning(dispatch)
+
+        const { requestId, abort } = thunkResult
+
+        const skippedSynchronously = stateAfter.requestId !== requestId
+
+        const runningQuery = getRunningQueries(dispatch)?.get(queryCacheKey)
+        const selectFromState = () => selector(getState())
+
+        const statePromise: AnyActionCreatorResult = Object.assign(
+          (forceQueryFn
+            ? // a query has been forced (upsertQueryData)
+              // -> we want to resolve it once data has been written with the data that will be written
+              thunkResult.then(selectFromState)
+            : skippedSynchronously && !runningQuery
+              ? // a query has been skipped due to a condition and we do not have any currently running query
+                // -> we want to resolve it immediately with the current data
+                Promise.resolve(stateAfter)
+              : // query just started or one is already in flight
+                // -> wait for the running query, then resolve with data from after that
+                Promise.all([runningQuery, thunkResult]).then(
+                  selectFromState,
+                )) as SafePromise<any>,
+          {
+            arg,
+            requestId,
+            subscriptionOptions,
+            queryCacheKey,
+            abort,
+            async unwrap() {
+              const result = await statePromise
+
+              if (result.isError) {
+                throw result.error
+              }
+
+              return result.data
+            },
+            refetch: (options?: RefetchOptions) =>
+              dispatch(
+                queryAction(arg, {
+                  subscribe: false,
+                  forceRefetch: true,
+                  ...options,
+                }),
+              ),
+            unsubscribe() {
+              if (subscribe)
+                dispatch(
+                  unsubscribeQueryResult({
+                    queryCacheKey,
+                    requestId,
+                  }),
+                )
+            },
+            updateSubscriptionOptions(options: SubscriptionOptions) {
+              statePromise.subscriptionOptions = options
+              dispatch(
+                updateSubscriptionOptions({
+                  endpointName,
+                  requestId,
+                  queryCacheKey,
+                  options,
+                }),
+              )
+            },
+          },
+        )
+
+        if (!runningQuery && !skippedSynchronously && !forceQueryFn) {
+          const runningQueries = getRunningQueries(dispatch)!
+          runningQueries.set(queryCacheKey, statePromise)
+
+          statePromise.then(() => {
+            runningQueries.delete(queryCacheKey)
+          })
+        }
+
+        return statePromise
+      }
+    return queryAction
+  }
+
+  function buildInitiateQuery(
+    endpointName: string,
+    endpointDefinition: QueryDefinition<any, any, any, any>,
+  ) {
+    const queryAction: StartQueryActionCreator<any> = buildInitiateAnyQuery(
+      endpointName,
+      endpointDefinition,
+    )
+
+    return queryAction
+  }
+
+  function buildInitiateInfiniteQuery(
+    endpointName: string,
+    endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>,
+  ) {
+    const infiniteQueryAction: StartInfiniteQueryActionCreator<any> =
+      buildInitiateAnyQuery(endpointName, endpointDefinition)
+
+    return infiniteQueryAction
+  }
+
+  function buildInitiateMutation(
+    endpointName: string,
+  ): StartMutationActionCreator<any> {
+    return (arg, { track = true, fixedCacheKey } = {}) =>
+      (dispatch, getState) => {
+        const thunk = mutationThunk({
+          type: 'mutation',
+          endpointName,
+          originalArgs: arg,
+          track,
+          fixedCacheKey,
+        })
+        const thunkResult = dispatch(thunk)
+        middlewareWarning(dispatch)
+        const { requestId, abort, unwrap } = thunkResult
+        const returnValuePromise = asSafePromise(
+          thunkResult.unwrap().then((data) => ({ data })),
+          (error) => ({ error }),
+        )
+
+        const reset = () => {
+          dispatch(removeMutationResult({ requestId, fixedCacheKey }))
+        }
+
+        const ret = Object.assign(returnValuePromise, {
+          arg: thunkResult.arg,
+          requestId,
+          abort,
+          unwrap,
+          reset,
+        })
+
+        const runningMutations = getRunningMutations(dispatch)!
+
+        runningMutations.set(requestId, ret)
+        ret.then(() => {
+          runningMutations.delete(requestId)
+        })
+        if (fixedCacheKey) {
+          runningMutations.set(fixedCacheKey, ret)
+          ret.then(() => {
+            if (runningMutations.get(fixedCacheKey) === ret) {
+              runningMutations.delete(fixedCacheKey)
+            }
+          })
+        }
+
+        return ret
+      }
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/batchActions.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/batchActions.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/batchActions.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,207 @@
+import type { InternalHandlerBuilder, SubscriptionSelectors } from './types'
+import type { SubscriptionInternalState, SubscriptionState } from '../apiState'
+import { produceWithPatches } from '../../utils/immerImports'
+import type { Action } from '@reduxjs/toolkit'
+import { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert'
+
+export const buildBatchedActionsHandler: InternalHandlerBuilder<
+  [actionShouldContinue: boolean, returnValue: SubscriptionSelectors | boolean]
+> = ({ api, queryThunk, internalState, mwApi }) => {
+  const subscriptionsPrefix = `${api.reducerPath}/subscriptions`
+
+  let previousSubscriptions: SubscriptionState =
+    null as unknown as SubscriptionState
+
+  let updateSyncTimer: ReturnType<typeof window.setTimeout> | null = null
+
+  const { updateSubscriptionOptions, unsubscribeQueryResult } =
+    api.internalActions
+
+  // Actually intentionally mutate the subscriptions state used in the middleware
+  // This is done to speed up perf when loading many components
+  const actuallyMutateSubscriptions = (
+    currentSubscriptions: SubscriptionInternalState,
+    action: Action,
+  ) => {
+    if (updateSubscriptionOptions.match(action)) {
+      const { queryCacheKey, requestId, options } = action.payload
+
+      const sub = currentSubscriptions.get(queryCacheKey)
+      if (sub?.has(requestId)) {
+        sub.set(requestId, options)
+      }
+      return true
+    }
+    if (unsubscribeQueryResult.match(action)) {
+      const { queryCacheKey, requestId } = action.payload
+      const sub = currentSubscriptions.get(queryCacheKey)
+      if (sub) {
+        sub.delete(requestId)
+      }
+      return true
+    }
+    if (api.internalActions.removeQueryResult.match(action)) {
+      currentSubscriptions.delete(action.payload.queryCacheKey)
+      return true
+    }
+    if (queryThunk.pending.match(action)) {
+      const {
+        meta: { arg, requestId },
+      } = action
+      const substate = getOrInsertComputed(
+        currentSubscriptions,
+        arg.queryCacheKey,
+        createNewMap,
+      )
+      if (arg.subscribe) {
+        substate.set(
+          requestId,
+          arg.subscriptionOptions ?? substate.get(requestId) ?? {},
+        )
+      }
+      return true
+    }
+    let mutated = false
+
+    if (queryThunk.rejected.match(action)) {
+      const {
+        meta: { condition, arg, requestId },
+      } = action
+      if (condition && arg.subscribe) {
+        const substate = getOrInsertComputed(
+          currentSubscriptions,
+          arg.queryCacheKey,
+          createNewMap,
+        )
+        substate.set(
+          requestId,
+          arg.subscriptionOptions ?? substate.get(requestId) ?? {},
+        )
+
+        mutated = true
+      }
+    }
+
+    return mutated
+  }
+
+  const getSubscriptions = () => internalState.currentSubscriptions
+  const getSubscriptionCount = (queryCacheKey: string) => {
+    const subscriptions = getSubscriptions()
+    const subscriptionsForQueryArg = subscriptions.get(queryCacheKey)
+    return subscriptionsForQueryArg?.size ?? 0
+  }
+  const isRequestSubscribed = (queryCacheKey: string, requestId: string) => {
+    const subscriptions = getSubscriptions()
+    return !!subscriptions?.get(queryCacheKey)?.get(requestId)
+  }
+
+  const subscriptionSelectors: SubscriptionSelectors = {
+    getSubscriptions,
+    getSubscriptionCount,
+    isRequestSubscribed,
+  }
+
+  function serializeSubscriptions(
+    currentSubscriptions: SubscriptionInternalState,
+  ): SubscriptionState {
+    // We now use nested Maps for subscriptions, instead of
+    // plain Records. Stringify this accordingly so we can
+    // convert it to the shape we need for the store.
+    return JSON.parse(
+      JSON.stringify(
+        Object.fromEntries(
+          [...currentSubscriptions].map(([k, v]) => [k, Object.fromEntries(v)]),
+        ),
+      ),
+    )
+  }
+
+  return (
+    action,
+    mwApi,
+  ): [
+    actionShouldContinue: boolean,
+    result: SubscriptionSelectors | boolean,
+  ] => {
+    if (!previousSubscriptions) {
+      // Initialize it the first time this handler runs
+      previousSubscriptions = serializeSubscriptions(
+        internalState.currentSubscriptions,
+      )
+    }
+
+    if (api.util.resetApiState.match(action)) {
+      previousSubscriptions = {}
+      internalState.currentSubscriptions.clear()
+      updateSyncTimer = null
+      return [true, false]
+    }
+
+    // Intercept requests by hooks to see if they're subscribed
+    // We return the internal state reference so that hooks
+    // can do their own checks to see if they're still active.
+    // It's stupid and hacky, but it does cut down on some dispatch calls.
+    if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {
+      return [false, subscriptionSelectors]
+    }
+
+    // Update subscription data based on this action
+    const didMutate = actuallyMutateSubscriptions(
+      internalState.currentSubscriptions,
+      action,
+    )
+
+    let actionShouldContinue = true
+
+    // HACK Sneak the test-only polling state back out
+    if (
+      process.env.NODE_ENV === 'test' &&
+      typeof action.type === 'string' &&
+      action.type === `${api.reducerPath}/getPolling`
+    ) {
+      return [false, internalState.currentPolls] as any
+    }
+
+    if (didMutate) {
+      if (!updateSyncTimer) {
+        // We only use the subscription state for the Redux DevTools at this point,
+        // as the real data is kept here in the middleware.
+        // Given that, we can throttle synchronizing this state significantly to
+        // save on overall perf.
+        // In 1.9, it was updated in a microtask, but now we do it at most every 500ms.
+        updateSyncTimer = setTimeout(() => {
+          // Deep clone the current subscription data
+          const newSubscriptions: SubscriptionState = serializeSubscriptions(
+            internalState.currentSubscriptions,
+          )
+          // Figure out a smaller diff between original and current
+          const [, patches] = produceWithPatches(
+            previousSubscriptions,
+            () => newSubscriptions,
+          )
+
+          // Sync the store state for visibility
+          mwApi.next(api.internalActions.subscriptionsUpdated(patches))
+          // Save the cloned state for later reference
+          previousSubscriptions = newSubscriptions
+          updateSyncTimer = null
+        }, 500)
+      }
+
+      const isSubscriptionSliceAction =
+        typeof action.type == 'string' &&
+        !!action.type.startsWith(subscriptionsPrefix)
+
+      const isAdditionalSubscriptionAction =
+        queryThunk.rejected.match(action) &&
+        action.meta.condition &&
+        !!action.meta.arg.subscribe
+
+      actionShouldContinue =
+        !isSubscriptionSliceAction && !isAdditionalSubscriptionAction
+    }
+
+    return [actionShouldContinue, false]
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/cacheCollection.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/cacheCollection.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/cacheCollection.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,204 @@
+import { getEndpointDefinition } from '@internal/query/apiTypes'
+import type { QueryDefinition } from '../../endpointDefinitions'
+import type { ConfigState, QueryCacheKey, QuerySubState } from '../apiState'
+import { isAnyOf } from '../rtkImports'
+import type {
+  ApiMiddlewareInternalHandler,
+  InternalHandlerBuilder,
+  QueryStateMeta,
+  SubMiddlewareApi,
+  TimeoutId,
+} from './types'
+
+export type ReferenceCacheCollection = never
+
+/**
+ * @example
+ * ```ts
+ * // codeblock-meta title="keepUnusedDataFor example"
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+ * interface Post {
+ *   id: number
+ *   name: string
+ * }
+ * type PostsResponse = Post[]
+ *
+ * const api = createApi({
+ *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+ *   endpoints: (build) => ({
+ *     getPosts: build.query<PostsResponse, void>({
+ *       query: () => 'posts',
+ *       // highlight-start
+ *       keepUnusedDataFor: 5
+ *       // highlight-end
+ *     })
+ *   })
+ * })
+ * ```
+ */
+export type CacheCollectionQueryExtraOptions = {
+  /**
+   * Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(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.
+   */
+  keepUnusedDataFor?: number
+}
+
+// Per https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value , browsers store
+// `setTimeout()` timer values in a 32-bit int. If we pass a value in that's larger than that,
+// it wraps and ends up executing immediately.
+// Our `keepUnusedDataFor` values are in seconds, so adjust the numbers here accordingly.
+export const THIRTY_TWO_BIT_MAX_INT = 2_147_483_647
+export const THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2_147_483_647 / 1_000 - 1
+
+export const buildCacheCollectionHandler: InternalHandlerBuilder = ({
+  reducerPath,
+  api,
+  queryThunk,
+  context,
+  internalState,
+  selectors: { selectQueryEntry, selectConfig },
+  getRunningQueryThunk,
+  mwApi,
+}) => {
+  const { removeQueryResult, unsubscribeQueryResult, cacheEntriesUpserted } =
+    api.internalActions
+
+  const canTriggerUnsubscribe = isAnyOf(
+    unsubscribeQueryResult.match,
+    queryThunk.fulfilled,
+    queryThunk.rejected,
+    cacheEntriesUpserted.match,
+  )
+
+  function anySubscriptionsRemainingForKey(queryCacheKey: string) {
+    const subscriptions = internalState.currentSubscriptions.get(queryCacheKey)
+    if (!subscriptions) {
+      return false
+    }
+
+    const hasSubscriptions = subscriptions.size > 0
+    return hasSubscriptions
+  }
+
+  const currentRemovalTimeouts: QueryStateMeta<TimeoutId> = {}
+
+  function abortAllPromises<T extends { abort?: () => void }>(
+    promiseMap: Map<string, T | undefined>,
+  ): void {
+    for (const promise of promiseMap.values()) {
+      promise?.abort?.()
+    }
+  }
+
+  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {
+    const state = mwApi.getState()
+    const config = selectConfig(state)
+
+    if (canTriggerUnsubscribe(action)) {
+      let queryCacheKeys: QueryCacheKey[]
+
+      if (cacheEntriesUpserted.match(action)) {
+        queryCacheKeys = action.payload.map(
+          (entry) => entry.queryDescription.queryCacheKey,
+        )
+      } else {
+        const { queryCacheKey } = unsubscribeQueryResult.match(action)
+          ? action.payload
+          : action.meta.arg
+        queryCacheKeys = [queryCacheKey]
+      }
+
+      handleUnsubscribeMany(queryCacheKeys, mwApi, config)
+    }
+
+    if (api.util.resetApiState.match(action)) {
+      for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {
+        if (timeout) clearTimeout(timeout)
+        delete currentRemovalTimeouts[key]
+      }
+
+      abortAllPromises(internalState.runningQueries)
+      abortAllPromises(internalState.runningMutations)
+    }
+
+    if (context.hasRehydrationInfo(action)) {
+      const { queries } = context.extractRehydrationInfo(action)!
+      // Gotcha:
+      // If rehydrating before the endpoint has been injected,the global `keepUnusedDataFor`
+      // will be used instead of the endpoint-specific one.
+      handleUnsubscribeMany(
+        Object.keys(queries) as QueryCacheKey[],
+        mwApi,
+        config,
+      )
+    }
+  }
+
+  function handleUnsubscribeMany(
+    cacheKeys: QueryCacheKey[],
+    api: SubMiddlewareApi,
+    config: ConfigState<string>,
+  ) {
+    const state = api.getState()
+    for (const queryCacheKey of cacheKeys) {
+      const entry = selectQueryEntry(state, queryCacheKey)
+      if (entry?.endpointName) {
+        handleUnsubscribe(queryCacheKey, entry.endpointName, api, config)
+      }
+    }
+  }
+
+  function handleUnsubscribe(
+    queryCacheKey: QueryCacheKey,
+    endpointName: string,
+    api: SubMiddlewareApi,
+    config: ConfigState<string>,
+  ) {
+    const endpointDefinition = getEndpointDefinition(
+      context,
+      endpointName,
+    ) as QueryDefinition<any, any, any, any>
+    const keepUnusedDataFor =
+      endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor
+
+    if (keepUnusedDataFor === Infinity) {
+      // Hey, user said keep this forever!
+      return
+    }
+    // Prevent `setTimeout` timers from overflowing a 32-bit internal int, by
+    // clamping the max value to be at most 1000ms less than the 32-bit max.
+    // Look, a 24.8-day keepalive ought to be enough for anybody, right? :)
+    // Also avoid negative values too.
+    const finalKeepUnusedDataFor = Math.max(
+      0,
+      Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS),
+    )
+
+    if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
+      const currentTimeout = currentRemovalTimeouts[queryCacheKey]
+      if (currentTimeout) {
+        clearTimeout(currentTimeout)
+      }
+
+      currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {
+        if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
+          // Try to abort any running query for this cache key
+          const entry = selectQueryEntry(api.getState(), queryCacheKey)
+
+          if (entry?.endpointName) {
+            const runningQuery = api.dispatch(
+              getRunningQueryThunk(entry.endpointName, entry.originalArgs),
+            )
+            runningQuery?.abort()
+          }
+          api.dispatch(removeQueryResult({ queryCacheKey }))
+        }
+        delete currentRemovalTimeouts![queryCacheKey]
+      }, finalKeepUnusedDataFor * 1000)
+    }
+  }
+
+  return handler
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/cacheLifecycle.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/cacheLifecycle.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/cacheLifecycle.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,379 @@
+import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit'
+import type {
+  BaseQueryFn,
+  BaseQueryMeta,
+  BaseQueryResult,
+} from '../../baseQueryTypes'
+import type {
+  BaseEndpointDefinition,
+  DefinitionType,
+} from '../../endpointDefinitions'
+import { isAnyQueryDefinition } from '../../endpointDefinitions'
+import type { QueryCacheKey, RootState } from '../apiState'
+import type {
+  MutationResultSelectorResult,
+  QueryResultSelectorResult,
+} from '../buildSelectors'
+import { getMutationCacheKey } from '../buildSlice'
+import type { PatchCollection, Recipe } from '../buildThunks'
+import { isAsyncThunkAction, isFulfilled } from '../rtkImports'
+import type {
+  ApiMiddlewareInternalHandler,
+  InternalHandlerBuilder,
+  PromiseWithKnownReason,
+  SubMiddlewareApi,
+} from './types'
+import { getEndpointDefinition } from '@internal/query/apiTypes'
+
+export type ReferenceCacheLifecycle = never
+
+export interface QueryBaseLifecycleApi<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  ReducerPath extends string = string,
+> extends LifecycleApi<ReducerPath> {
+  /**
+   * Gets the current value of this cache entry.
+   */
+  getCacheEntry(): QueryResultSelectorResult<
+    { type: DefinitionType.query } & BaseEndpointDefinition<
+      QueryArg,
+      BaseQuery,
+      ResultType,
+      BaseQueryResult<BaseQuery>
+    >
+  >
+  /**
+   * Updates the current cache entry value.
+   * For documentation see `api.util.updateQueryData`.
+   */
+  updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection
+}
+
+export type MutationBaseLifecycleApi<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  ReducerPath extends string = string,
+> = LifecycleApi<ReducerPath> & {
+  /**
+   * Gets the current value of this cache entry.
+   */
+  getCacheEntry(): MutationResultSelectorResult<
+    { type: DefinitionType.mutation } & BaseEndpointDefinition<
+      QueryArg,
+      BaseQuery,
+      ResultType,
+      BaseQueryResult<BaseQuery>
+    >
+  >
+}
+
+type LifecycleApi<ReducerPath extends string = string> = {
+  /**
+   * The dispatch method for the store
+   */
+  dispatch: ThunkDispatch<any, any, UnknownAction>
+  /**
+   * A method to get the current state
+   */
+  getState(): RootState<any, any, ReducerPath>
+  /**
+   * `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.
+   */
+  extra: unknown
+  /**
+   * A unique ID generated for the mutation
+   */
+  requestId: string
+}
+
+type CacheLifecyclePromises<ResultType = unknown, MetaType = unknown> = {
+  /**
+   * Promise that will resolve with the first value for this cache key.
+   * This allows you to `await` until an actual value is in cache.
+   *
+   * If the cache entry is removed from the cache before any value has ever
+   * been resolved, this Promise will reject with
+   * `new Error('Promise never resolved before cacheEntryRemoved.')`
+   * to prevent memory leaks.
+   * You can just re-throw that error (or not handle it at all) -
+   * it will be caught outside of `cacheEntryAdded`.
+   *
+   * If you don't interact with this promise, it will not throw.
+   */
+  cacheDataLoaded: PromiseWithKnownReason<
+    {
+      /**
+       * The (transformed) query result.
+       */
+      data: ResultType
+      /**
+       * The `meta` returned by the `baseQuery`
+       */
+      meta: MetaType
+    },
+    typeof neverResolvedError
+  >
+  /**
+   * Promise that allows you to wait for the point in time when the cache entry
+   * has been removed from the cache, by not being used/subscribed to any more
+   * in the application for too long or by dispatching `api.util.resetApiState`.
+   */
+  cacheEntryRemoved: Promise<void>
+}
+
+export interface QueryCacheLifecycleApi<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  ReducerPath extends string = string,
+> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,
+    CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}
+
+export type MutationCacheLifecycleApi<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  ReducerPath extends string = string,
+> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> &
+  CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>>
+
+export type CacheLifecycleQueryExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = {
+  onCacheEntryAdded?(
+    arg: QueryArg,
+    api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,
+  ): Promise<void> | void
+}
+
+export type CacheLifecycleInfiniteQueryExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = CacheLifecycleQueryExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery,
+  ReducerPath
+>
+
+export type CacheLifecycleMutationExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = {
+  onCacheEntryAdded?(
+    arg: QueryArg,
+    api: MutationCacheLifecycleApi<
+      QueryArg,
+      BaseQuery,
+      ResultType,
+      ReducerPath
+    >,
+  ): Promise<void> | void
+}
+
+const neverResolvedError = new Error(
+  'Promise never resolved before cacheEntryRemoved.',
+) as Error & {
+  message: 'Promise never resolved before cacheEntryRemoved.'
+}
+
+export const buildCacheLifecycleHandler: InternalHandlerBuilder = ({
+  api,
+  reducerPath,
+  context,
+  queryThunk,
+  mutationThunk,
+  internalState,
+  selectors: { selectQueryEntry, selectApiState },
+}) => {
+  const isQueryThunk = isAsyncThunkAction(queryThunk)
+  const isMutationThunk = isAsyncThunkAction(mutationThunk)
+  const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk)
+
+  type CacheLifecycle = {
+    valueResolved?(value: { data: unknown; meta: unknown }): unknown
+    cacheEntryRemoved(): void
+  }
+  const lifecycleMap: Record<string, CacheLifecycle> = {}
+
+  const { removeQueryResult, removeMutationResult, cacheEntriesUpserted } =
+    api.internalActions
+
+  function resolveLifecycleEntry(
+    cacheKey: string,
+    data: unknown,
+    meta: unknown,
+  ) {
+    const lifecycle = lifecycleMap[cacheKey]
+
+    if (lifecycle?.valueResolved) {
+      lifecycle.valueResolved({
+        data,
+        meta,
+      })
+      delete lifecycle.valueResolved
+    }
+  }
+
+  function removeLifecycleEntry(cacheKey: string) {
+    const lifecycle = lifecycleMap[cacheKey]
+    if (lifecycle) {
+      delete lifecycleMap[cacheKey]
+      lifecycle.cacheEntryRemoved()
+    }
+  }
+
+  function getActionMetaFields(
+    action:
+      | ReturnType<typeof queryThunk.pending>
+      | ReturnType<typeof mutationThunk.pending>,
+  ) {
+    const { arg, requestId } = action.meta
+    const { endpointName, originalArgs } = arg
+    return [endpointName, originalArgs, requestId] as const
+  }
+
+  const handler: ApiMiddlewareInternalHandler = (
+    action,
+    mwApi,
+    stateBefore,
+  ) => {
+    const cacheKey = getCacheKey(action) as QueryCacheKey
+
+    function checkForNewCacheKey(
+      endpointName: string,
+      cacheKey: QueryCacheKey,
+      requestId: string,
+      originalArgs: unknown,
+    ) {
+      const oldEntry = selectQueryEntry(stateBefore, cacheKey)
+      const newEntry = selectQueryEntry(mwApi.getState(), cacheKey)
+      if (!oldEntry && newEntry) {
+        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId)
+      }
+    }
+
+    if (queryThunk.pending.match(action)) {
+      const [endpointName, originalArgs, requestId] =
+        getActionMetaFields(action)
+      checkForNewCacheKey(endpointName, cacheKey, requestId, originalArgs)
+    } else if (cacheEntriesUpserted.match(action)) {
+      for (const { queryDescription, value } of action.payload) {
+        const { endpointName, originalArgs, queryCacheKey } = queryDescription
+        checkForNewCacheKey(
+          endpointName,
+          queryCacheKey,
+          action.meta.requestId,
+          originalArgs,
+        )
+
+        resolveLifecycleEntry(queryCacheKey, value, {})
+      }
+    } else if (mutationThunk.pending.match(action)) {
+      const state = mwApi.getState()[reducerPath].mutations[cacheKey]
+      if (state) {
+        const [endpointName, originalArgs, requestId] =
+          getActionMetaFields(action)
+        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId)
+      }
+    } else if (isFulfilledThunk(action)) {
+      resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta)
+    } else if (
+      removeQueryResult.match(action) ||
+      removeMutationResult.match(action)
+    ) {
+      removeLifecycleEntry(cacheKey)
+    } else if (api.util.resetApiState.match(action)) {
+      for (const cacheKey of Object.keys(lifecycleMap)) {
+        removeLifecycleEntry(cacheKey)
+      }
+    }
+  }
+
+  function getCacheKey(action: any) {
+    if (isQueryThunk(action)) return action.meta.arg.queryCacheKey
+    if (isMutationThunk(action)) {
+      return action.meta.arg.fixedCacheKey ?? action.meta.requestId
+    }
+    if (removeQueryResult.match(action)) return action.payload.queryCacheKey
+    if (removeMutationResult.match(action))
+      return getMutationCacheKey(action.payload)
+    return ''
+  }
+
+  function handleNewKey(
+    endpointName: string,
+    originalArgs: any,
+    queryCacheKey: string,
+    mwApi: SubMiddlewareApi,
+    requestId: string,
+  ) {
+    const endpointDefinition = getEndpointDefinition(context, endpointName)
+    const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded
+    if (!onCacheEntryAdded) return
+
+    const lifecycle = {} as CacheLifecycle
+
+    const cacheEntryRemoved = new Promise<void>((resolve) => {
+      lifecycle.cacheEntryRemoved = resolve
+    })
+    const cacheDataLoaded: PromiseWithKnownReason<
+      { data: unknown; meta: unknown },
+      typeof neverResolvedError
+    > = Promise.race([
+      new Promise<{ data: unknown; meta: unknown }>((resolve) => {
+        lifecycle.valueResolved = resolve
+      }),
+      cacheEntryRemoved.then(() => {
+        throw neverResolvedError
+      }),
+    ])
+    // prevent uncaught promise rejections from happening.
+    // if the original promise is used in any way, that will create a new promise that will throw again
+    cacheDataLoaded.catch(() => {})
+    lifecycleMap[queryCacheKey] = lifecycle
+    const selector = (api.endpoints[endpointName] as any).select(
+      isAnyQueryDefinition(endpointDefinition) ? originalArgs : queryCacheKey,
+    )
+
+    const extra = mwApi.dispatch((_, __, extra) => extra)
+    const lifecycleApi = {
+      ...mwApi,
+      getCacheEntry: () => selector(mwApi.getState()),
+      requestId,
+      extra,
+      updateCachedData: (isAnyQueryDefinition(endpointDefinition)
+        ? (updateRecipe: Recipe<any>) =>
+            mwApi.dispatch(
+              api.util.updateQueryData(
+                endpointName as never,
+                originalArgs as never,
+                updateRecipe,
+              ),
+            )
+        : undefined) as any,
+
+      cacheDataLoaded,
+      cacheEntryRemoved,
+    }
+
+    const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi as any)
+    // if a `neverResolvedError` was thrown, but not handled in the running handler, do not let it leak out further
+    Promise.resolve(runningHandler).catch((e) => {
+      if (e === neverResolvedError) return
+      throw e
+    })
+  }
+
+  return handler
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/devMiddleware.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/devMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/devMiddleware.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,34 @@
+import type { InternalHandlerBuilder } from './types'
+
+export const buildDevCheckHandler: InternalHandlerBuilder = ({
+  api,
+  context: { apiUid },
+  reducerPath,
+}) => {
+  return (action, mwApi) => {
+    if (api.util.resetApiState.match(action)) {
+      // dispatch after api reset
+      mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid))
+    }
+
+    if (
+      typeof process !== 'undefined' &&
+      process.env.NODE_ENV === 'development'
+    ) {
+      if (
+        api.internalActions.middlewareRegistered.match(action) &&
+        action.payload === apiUid &&
+        mwApi.getState()[reducerPath]?.config?.middlewareRegistered ===
+          'conflict'
+      ) {
+        console.warn(`There is a mismatch between slice and middleware for the reducerPath "${reducerPath}".
+You can only have one api per reducer path, this will lead to crashes in various situations!${
+          reducerPath === 'api'
+            ? `
+If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`
+            : ''
+        }`)
+      }
+    }
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,162 @@
+import type {
+  Action,
+  Middleware,
+  ThunkDispatch,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import type {
+  EndpointDefinitions,
+  FullTagDescription,
+} from '../../endpointDefinitions'
+import type { QueryStatus, QuerySubState, RootState } from '../apiState'
+import type { QueryThunkArg } from '../buildThunks'
+import { createAction, isAction } from '../rtkImports'
+import { buildBatchedActionsHandler } from './batchActions'
+import { buildCacheCollectionHandler } from './cacheCollection'
+import { buildCacheLifecycleHandler } from './cacheLifecycle'
+import { buildDevCheckHandler } from './devMiddleware'
+import { buildInvalidationByTagsHandler } from './invalidationByTags'
+import { buildPollingHandler } from './polling'
+import { buildQueryLifecycleHandler } from './queryLifecycle'
+import type {
+  BuildMiddlewareInput,
+  InternalHandlerBuilder,
+  InternalMiddlewareState,
+} from './types'
+import { buildWindowEventHandler } from './windowEventHandling'
+import type { ApiEndpointQuery } from '../module'
+export type { ReferenceCacheCollection } from './cacheCollection'
+export type {
+  MutationCacheLifecycleApi,
+  QueryCacheLifecycleApi,
+  ReferenceCacheLifecycle,
+} from './cacheLifecycle'
+export type {
+  MutationLifecycleApi,
+  QueryLifecycleApi,
+  ReferenceQueryLifecycle,
+  TypedMutationOnQueryStarted,
+  TypedQueryOnQueryStarted,
+} from './queryLifecycle'
+export type { SubscriptionSelectors } from './types'
+
+export function buildMiddleware<
+  Definitions extends EndpointDefinitions,
+  ReducerPath extends string,
+  TagTypes extends string,
+>(input: BuildMiddlewareInput<Definitions, ReducerPath, TagTypes>) {
+  const { reducerPath, queryThunk, api, context, getInternalState } = input
+  const { apiUid } = context
+
+  const actions = {
+    invalidateTags: createAction<
+      Array<TagTypes | FullTagDescription<TagTypes> | null | undefined>
+    >(`${reducerPath}/invalidateTags`),
+  }
+
+  const isThisApiSliceAction = (action: Action) =>
+    action.type.startsWith(`${reducerPath}/`)
+
+  const handlerBuilders: InternalHandlerBuilder[] = [
+    buildDevCheckHandler,
+    buildCacheCollectionHandler,
+    buildInvalidationByTagsHandler,
+    buildPollingHandler,
+    buildCacheLifecycleHandler,
+    buildQueryLifecycleHandler,
+  ]
+
+  const middleware: Middleware<
+    {},
+    RootState<Definitions, string, ReducerPath>,
+    ThunkDispatch<any, any, UnknownAction>
+  > = (mwApi) => {
+    let initialized = false
+
+    const internalState = getInternalState(mwApi.dispatch)
+
+    const builderArgs = {
+      ...(input as any as BuildMiddlewareInput<
+        EndpointDefinitions,
+        string,
+        string
+      >),
+      internalState,
+      refetchQuery,
+      isThisApiSliceAction,
+      mwApi,
+    }
+
+    const handlers = handlerBuilders.map((build) => build(builderArgs))
+
+    const batchedActionsHandler = buildBatchedActionsHandler(builderArgs)
+    const windowEventsHandler = buildWindowEventHandler(builderArgs)
+
+    return (next) => {
+      return (action) => {
+        if (!isAction(action)) {
+          return next(action)
+        }
+        if (!initialized) {
+          initialized = true
+          // dispatch before any other action
+          mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid))
+        }
+
+        const mwApiWithNext = { ...mwApi, next }
+
+        const stateBefore = mwApi.getState()
+
+        const [actionShouldContinue, internalProbeResult] =
+          batchedActionsHandler(action, mwApiWithNext, stateBefore)
+
+        let res: any
+
+        if (actionShouldContinue) {
+          res = next(action)
+        } else {
+          res = internalProbeResult
+        }
+
+        if (!!mwApi.getState()[reducerPath]) {
+          // Only run these checks if the middleware is registered okay
+
+          // This looks for actions that aren't specific to the API slice
+          windowEventsHandler(action, mwApiWithNext, stateBefore)
+
+          if (
+            isThisApiSliceAction(action) ||
+            context.hasRehydrationInfo(action)
+          ) {
+            // Only run these additional checks if the actions are part of the API slice,
+            // or the action has hydration-related data
+            for (const handler of handlers) {
+              handler(action, mwApiWithNext, stateBefore)
+            }
+          }
+        }
+
+        return res
+      }
+    }
+  }
+
+  return { middleware, actions }
+
+  function refetchQuery(
+    querySubState: Exclude<
+      QuerySubState<any>,
+      { status: QueryStatus.uninitialized }
+    >,
+  ) {
+    return (
+      input.api.endpoints[querySubState.endpointName] as ApiEndpointQuery<
+        any,
+        any
+      >
+    ).initiate(querySubState.originalArgs as any, {
+      subscribe: false,
+      forceRefetch: true,
+    })
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/invalidationByTags.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/invalidationByTags.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/invalidationByTags.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,139 @@
+import {
+  isAnyOf,
+  isFulfilled,
+  isRejected,
+  isRejectedWithValue,
+} from '../rtkImports'
+
+import type {
+  EndpointDefinitions,
+  FullTagDescription,
+} from '../../endpointDefinitions'
+import { calculateProvidedBy } from '../../endpointDefinitions'
+import type { CombinedState, QueryCacheKey } from '../apiState'
+import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'
+import { calculateProvidedByThunk } from '../buildThunks'
+import type {
+  SubMiddlewareApi,
+  InternalHandlerBuilder,
+  ApiMiddlewareInternalHandler,
+} from './types'
+import { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert'
+
+export const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({
+  reducerPath,
+  context,
+  context: { endpointDefinitions },
+  mutationThunk,
+  queryThunk,
+  api,
+  assertTagType,
+  refetchQuery,
+  internalState,
+}) => {
+  const { removeQueryResult } = api.internalActions
+  const isThunkActionWithTags = isAnyOf(
+    isFulfilled(mutationThunk),
+    isRejectedWithValue(mutationThunk),
+  )
+
+  const isQueryEnd = isAnyOf(
+    isFulfilled(queryThunk, mutationThunk),
+    isRejected(queryThunk, mutationThunk),
+  )
+  let pendingTagInvalidations: FullTagDescription<string>[] = []
+  // Track via counter so we can avoid iterating over state every time
+  let pendingRequestCount = 0
+
+  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {
+    if (
+      queryThunk.pending.match(action) ||
+      mutationThunk.pending.match(action)
+    ) {
+      pendingRequestCount++
+    }
+
+    if (isQueryEnd(action)) {
+      pendingRequestCount = Math.max(0, pendingRequestCount - 1)
+    }
+
+    if (isThunkActionWithTags(action)) {
+      invalidateTags(
+        calculateProvidedByThunk(
+          action,
+          'invalidatesTags',
+          endpointDefinitions,
+          assertTagType,
+        ),
+        mwApi,
+      )
+    } else if (isQueryEnd(action)) {
+      invalidateTags([], mwApi)
+    } else if (api.util.invalidateTags.match(action)) {
+      invalidateTags(
+        calculateProvidedBy(
+          action.payload,
+          undefined,
+          undefined,
+          undefined,
+          undefined,
+          assertTagType,
+        ),
+        mwApi,
+      )
+    }
+  }
+
+  function hasPendingRequests() {
+    return pendingRequestCount > 0
+  }
+
+  function invalidateTags(
+    newTags: readonly FullTagDescription<string>[],
+    mwApi: SubMiddlewareApi,
+  ) {
+    const rootState = mwApi.getState()
+    const state = rootState[reducerPath]
+
+    pendingTagInvalidations.push(...newTags)
+
+    if (
+      state.config.invalidationBehavior === 'delayed' &&
+      hasPendingRequests()
+    ) {
+      return
+    }
+
+    const tags = pendingTagInvalidations
+    pendingTagInvalidations = []
+    if (tags.length === 0) return
+
+    const toInvalidate = api.util.selectInvalidatedBy(rootState, tags)
+
+    context.batch(() => {
+      const valuesArray = Array.from(toInvalidate.values())
+      for (const { queryCacheKey } of valuesArray) {
+        const querySubState = state.queries[queryCacheKey]
+        const subscriptionSubState = getOrInsertComputed(
+          internalState.currentSubscriptions,
+          queryCacheKey,
+          createNewMap,
+        )
+
+        if (querySubState) {
+          if (subscriptionSubState.size === 0) {
+            mwApi.dispatch(
+              removeQueryResult({
+                queryCacheKey: queryCacheKey as QueryCacheKey,
+              }),
+            )
+          } else if (querySubState.status !== STATUS_UNINITIALIZED) {
+            mwApi.dispatch(refetchQuery(querySubState))
+          }
+        }
+      }
+    })
+  }
+
+  return handler
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/polling.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/polling.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/polling.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,187 @@
+import type {
+  QueryCacheKey,
+  QuerySubstateIdentifier,
+  Subscribers,
+  SubscribersInternal,
+} from '../apiState'
+import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'
+import type {
+  QueryStateMeta,
+  SubMiddlewareApi,
+  TimeoutId,
+  InternalHandlerBuilder,
+  ApiMiddlewareInternalHandler,
+  InternalMiddlewareState,
+} from './types'
+
+export const buildPollingHandler: InternalHandlerBuilder = ({
+  reducerPath,
+  queryThunk,
+  api,
+  refetchQuery,
+  internalState,
+}) => {
+  const { currentPolls, currentSubscriptions } = internalState
+
+  // Batching state for polling updates
+  const pendingPollingUpdates = new Set<string>()
+  let pollingUpdateTimer: ReturnType<typeof setTimeout> | null = null
+
+  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {
+    if (
+      api.internalActions.updateSubscriptionOptions.match(action) ||
+      api.internalActions.unsubscribeQueryResult.match(action)
+    ) {
+      schedulePollingUpdate(action.payload.queryCacheKey, mwApi)
+    }
+
+    if (
+      queryThunk.pending.match(action) ||
+      (queryThunk.rejected.match(action) && action.meta.condition)
+    ) {
+      schedulePollingUpdate(action.meta.arg.queryCacheKey, mwApi)
+    }
+
+    if (
+      queryThunk.fulfilled.match(action) ||
+      (queryThunk.rejected.match(action) && !action.meta.condition)
+    ) {
+      startNextPoll(action.meta.arg, mwApi)
+    }
+
+    if (api.util.resetApiState.match(action)) {
+      clearPolls()
+      // Clear any pending updates
+      if (pollingUpdateTimer) {
+        clearTimeout(pollingUpdateTimer)
+        pollingUpdateTimer = null
+      }
+      pendingPollingUpdates.clear()
+    }
+  }
+
+  function schedulePollingUpdate(queryCacheKey: string, api: SubMiddlewareApi) {
+    pendingPollingUpdates.add(queryCacheKey)
+
+    if (!pollingUpdateTimer) {
+      pollingUpdateTimer = setTimeout(() => {
+        // Process all pending updates in a single batch
+        for (const key of pendingPollingUpdates) {
+          updatePollingInterval({ queryCacheKey: key as any }, api)
+        }
+        pendingPollingUpdates.clear()
+        pollingUpdateTimer = null
+      }, 0)
+    }
+  }
+
+  function startNextPoll(
+    { queryCacheKey }: QuerySubstateIdentifier,
+    api: SubMiddlewareApi,
+  ) {
+    const state = api.getState()[reducerPath]
+    const querySubState = state.queries[queryCacheKey]
+    const subscriptions = currentSubscriptions.get(queryCacheKey)
+
+    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) return
+
+    const { lowestPollingInterval, skipPollingIfUnfocused } =
+      findLowestPollingInterval(subscriptions)
+    if (!Number.isFinite(lowestPollingInterval)) return
+
+    const currentPoll = currentPolls.get(queryCacheKey)
+
+    if (currentPoll?.timeout) {
+      clearTimeout(currentPoll.timeout)
+      currentPoll.timeout = undefined
+    }
+
+    const nextPollTimestamp = Date.now() + lowestPollingInterval
+
+    currentPolls.set(queryCacheKey, {
+      nextPollTimestamp,
+      pollingInterval: lowestPollingInterval,
+      timeout: setTimeout(() => {
+        if (state.config.focused || !skipPollingIfUnfocused) {
+          api.dispatch(refetchQuery(querySubState))
+        }
+        startNextPoll({ queryCacheKey }, api)
+      }, lowestPollingInterval),
+    })
+  }
+
+  function updatePollingInterval(
+    { queryCacheKey }: QuerySubstateIdentifier,
+    api: SubMiddlewareApi,
+  ) {
+    const state = api.getState()[reducerPath]
+    const querySubState = state.queries[queryCacheKey]
+    const subscriptions = currentSubscriptions.get(queryCacheKey)
+
+    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {
+      return
+    }
+
+    const { lowestPollingInterval } = findLowestPollingInterval(subscriptions)
+
+    // HACK add extra data to track how many times this has been called in tests
+    // yes we're mutating a nonexistent field on a Map here
+    if (process.env.NODE_ENV === 'test') {
+      const updateCounters = ((currentPolls as any).pollUpdateCounters ??= {})
+      updateCounters[queryCacheKey] ??= 0
+      updateCounters[queryCacheKey]++
+    }
+
+    if (!Number.isFinite(lowestPollingInterval)) {
+      cleanupPollForKey(queryCacheKey)
+      return
+    }
+
+    const currentPoll = currentPolls.get(queryCacheKey)
+
+    const nextPollTimestamp = Date.now() + lowestPollingInterval
+
+    if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {
+      startNextPoll({ queryCacheKey }, api)
+    }
+  }
+
+  function cleanupPollForKey(key: string) {
+    const existingPoll = currentPolls.get(key)
+    if (existingPoll?.timeout) {
+      clearTimeout(existingPoll.timeout)
+    }
+    currentPolls.delete(key)
+  }
+
+  function clearPolls() {
+    for (const key of currentPolls.keys()) {
+      cleanupPollForKey(key)
+    }
+  }
+
+  function findLowestPollingInterval(
+    subscribers: SubscribersInternal = new Map(),
+  ) {
+    let skipPollingIfUnfocused: boolean | undefined = false
+    let lowestPollingInterval = Number.POSITIVE_INFINITY
+
+    for (const entry of subscribers.values()) {
+      if (!!entry.pollingInterval) {
+        lowestPollingInterval = Math.min(
+          entry.pollingInterval!,
+          lowestPollingInterval,
+        )
+        skipPollingIfUnfocused =
+          entry.skipPollingIfUnfocused || skipPollingIfUnfocused
+      }
+    }
+
+    return {
+      lowestPollingInterval,
+      skipPollingIfUnfocused,
+    }
+  }
+
+  return handler
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/queryLifecycle.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/queryLifecycle.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/queryLifecycle.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,505 @@
+import { getEndpointDefinition } from '@internal/query/apiTypes'
+import type {
+  BaseQueryError,
+  BaseQueryFn,
+  BaseQueryMeta,
+} from '../../baseQueryTypes'
+import { isAnyQueryDefinition } from '../../endpointDefinitions'
+import type { Recipe } from '../buildThunks'
+import { isFulfilled, isPending, isRejected } from '../rtkImports'
+import type {
+  MutationBaseLifecycleApi,
+  QueryBaseLifecycleApi,
+} from './cacheLifecycle'
+import type {
+  ApiMiddlewareInternalHandler,
+  InternalHandlerBuilder,
+  PromiseConstructorWithKnownReason,
+  PromiseWithKnownReason,
+} from './types'
+
+export type ReferenceQueryLifecycle = never
+
+type QueryLifecyclePromises<ResultType, BaseQuery extends BaseQueryFn> = {
+  /**
+   * Promise that will resolve with the (transformed) query result.
+   *
+   * If the query fails, this promise will reject with the error.
+   *
+   * This allows you to `await` for the query to finish.
+   *
+   * If you don't interact with this promise, it will not throw.
+   */
+  queryFulfilled: PromiseWithKnownReason<
+    {
+      /**
+       * The (transformed) query result.
+       */
+      data: ResultType
+      /**
+       * The `meta` returned by the `baseQuery`
+       */
+      meta: BaseQueryMeta<BaseQuery>
+    },
+    QueryFulfilledRejectionReason<BaseQuery>
+  >
+}
+
+type QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> =
+  | {
+      error: BaseQueryError<BaseQuery>
+      /**
+       * If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.
+       */
+      isUnhandledError: false
+      /**
+       * The `meta` returned by the `baseQuery`
+       */
+      meta: BaseQueryMeta<BaseQuery>
+    }
+  | {
+      error: unknown
+      meta?: undefined
+      /**
+       * 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.
+       * There can not be made any assumption about the shape of `error`.
+       */
+      isUnhandledError: true
+    }
+
+export type QueryLifecycleQueryExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = {
+  /**
+   * 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).
+   *
+   * Can be used to perform side-effects throughout the lifecycle of the query.
+   *
+   * @example
+   * ```ts
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+   * import { messageCreated } from './notificationsSlice
+   * export interface Post {
+   *   id: number
+   *   name: string
+   * }
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({
+   *     baseUrl: '/',
+   *   }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, number>({
+   *       query: (id) => `post/${id}`,
+   *       async onQueryStarted(id, { dispatch, queryFulfilled }) {
+   *         // `onStart` side-effect
+   *         dispatch(messageCreated('Fetching posts...'))
+   *         try {
+   *           const { data } = await queryFulfilled
+   *           // `onSuccess` side-effect
+   *           dispatch(messageCreated('Posts received!'))
+   *         } catch (err) {
+   *           // `onError` side-effect
+   *           dispatch(messageCreated('Error fetching posts!'))
+   *         }
+   *       }
+   *     }),
+   *   }),
+   * })
+   * ```
+   */
+  onQueryStarted?(
+    queryArgument: QueryArg,
+    queryLifeCycleApi: QueryLifecycleApi<
+      QueryArg,
+      BaseQuery,
+      ResultType,
+      ReducerPath
+    >,
+  ): Promise<void> | void
+}
+
+export type QueryLifecycleInfiniteQueryExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = QueryLifecycleQueryExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery,
+  ReducerPath
+>
+
+export type QueryLifecycleMutationExtraOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = {
+  /**
+   * 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).
+   *
+   * Can be used for `optimistic updates`.
+   *
+   * @example
+   *
+   * ```ts
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+   * export interface Post {
+   *   id: number
+   *   name: string
+   * }
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({
+   *     baseUrl: '/',
+   *   }),
+   *   tagTypes: ['Post'],
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, number>({
+   *       query: (id) => `post/${id}`,
+   *       providesTags: ['Post'],
+   *     }),
+   *     updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
+   *       query: ({ id, ...patch }) => ({
+   *         url: `post/${id}`,
+   *         method: 'PATCH',
+   *         body: patch,
+   *       }),
+   *       invalidatesTags: ['Post'],
+   *       async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
+   *         const patchResult = dispatch(
+   *           api.util.updateQueryData('getPost', id, (draft) => {
+   *             Object.assign(draft, patch)
+   *           })
+   *         )
+   *         try {
+   *           await queryFulfilled
+   *         } catch {
+   *           patchResult.undo()
+   *         }
+   *       },
+   *     }),
+   *   }),
+   * })
+   * ```
+   */
+  onQueryStarted?(
+    queryArgument: QueryArg,
+    mutationLifeCycleApi: MutationLifecycleApi<
+      QueryArg,
+      BaseQuery,
+      ResultType,
+      ReducerPath
+    >,
+  ): Promise<void> | void
+}
+
+export interface QueryLifecycleApi<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  ReducerPath extends string = string,
+> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,
+    QueryLifecyclePromises<ResultType, BaseQuery> {}
+
+export type MutationLifecycleApi<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  ReducerPath extends string = string,
+> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> &
+  QueryLifecyclePromises<ResultType, BaseQuery>
+
+/**
+ * Provides a way to define a strongly-typed version of
+ * {@linkcode QueryLifecycleQueryExtraOptions.onQueryStarted | onQueryStarted}
+ * for a specific query.
+ *
+ * @example
+ * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>
+ *
+ * ```ts
+ * import type { TypedQueryOnQueryStarted } from '@reduxjs/toolkit/query'
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+ *
+ * type Post = {
+ *   id: number
+ *   title: string
+ *   userId: number
+ * }
+ *
+ * type PostsApiResponse = {
+ *   posts: Post[]
+ *   total: number
+ *   skip: number
+ *   limit: number
+ * }
+ *
+ * type QueryArgument = number | undefined
+ *
+ * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
+ *
+ * const baseApiSlice = createApi({
+ *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),
+ *   reducerPath: 'postsApi',
+ *   tagTypes: ['Posts'],
+ *   endpoints: (build) => ({
+ *     getPosts: build.query<PostsApiResponse, void>({
+ *       query: () => `/posts`,
+ *     }),
+ *
+ *     getPostById: build.query<Post, QueryArgument>({
+ *       query: (postId) => `/posts/${postId}`,
+ *     }),
+ *   }),
+ * })
+ *
+ * const updatePostOnFulfilled: TypedQueryOnQueryStarted<
+ *   PostsApiResponse,
+ *   QueryArgument,
+ *   BaseQueryFunction,
+ *   'postsApi'
+ * > = async (queryArgument, { dispatch, queryFulfilled }) => {
+ *   const result = await queryFulfilled
+ *
+ *   const { posts } = result.data
+ *
+ *   // Pre-fill the individual post entries with the results
+ *   // from the list endpoint query
+ *   dispatch(
+ *     baseApiSlice.util.upsertQueryEntries(
+ *       posts.map((post) => ({
+ *         endpointName: 'getPostById',
+ *         arg: post.id,
+ *         value: post,
+ *       })),
+ *     ),
+ *   )
+ * }
+ *
+ * export const extendedApiSlice = baseApiSlice.injectEndpoints({
+ *   endpoints: (build) => ({
+ *     getPostsByUserId: build.query<PostsApiResponse, QueryArgument>({
+ *       query: (userId) => `/posts/user/${userId}`,
+ *
+ *       onQueryStarted: updatePostOnFulfilled,
+ *     }),
+ *   }),
+ * })
+ * ```
+ *
+ * @template ResultType - The type of the result `data` returned by the query.
+ * @template QueryArgumentType - The type of the argument passed into the query.
+ * @template BaseQueryFunctionType - The type of the base query function being used.
+ * @template ReducerPath - The type representing the `reducerPath` for the API slice.
+ *
+ * @since 2.4.0
+ * @public
+ */
+export type TypedQueryOnQueryStarted<
+  ResultType,
+  QueryArgumentType,
+  BaseQueryFunctionType extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = QueryLifecycleQueryExtraOptions<
+  ResultType,
+  QueryArgumentType,
+  BaseQueryFunctionType,
+  ReducerPath
+>['onQueryStarted']
+
+/**
+ * Provides a way to define a strongly-typed version of
+ * {@linkcode QueryLifecycleMutationExtraOptions.onQueryStarted | onQueryStarted}
+ * for a specific mutation.
+ *
+ * @example
+ * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>
+ *
+ * ```ts
+ * import type { TypedMutationOnQueryStarted } from '@reduxjs/toolkit/query'
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+ *
+ * type Post = {
+ *   id: number
+ *   title: string
+ *   userId: number
+ * }
+ *
+ * type PostsApiResponse = {
+ *   posts: Post[]
+ *   total: number
+ *   skip: number
+ *   limit: number
+ * }
+ *
+ * type QueryArgument = Pick<Post, 'id'> & Partial<Post>
+ *
+ * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
+ *
+ * const baseApiSlice = createApi({
+ *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),
+ *   reducerPath: 'postsApi',
+ *   tagTypes: ['Posts'],
+ *   endpoints: (build) => ({
+ *     getPosts: build.query<PostsApiResponse, void>({
+ *       query: () => `/posts`,
+ *     }),
+ *
+ *     getPostById: build.query<Post, number>({
+ *       query: (postId) => `/posts/${postId}`,
+ *     }),
+ *   }),
+ * })
+ *
+ * const updatePostOnFulfilled: TypedMutationOnQueryStarted<
+ *   Post,
+ *   QueryArgument,
+ *   BaseQueryFunction,
+ *   'postsApi'
+ * > = async ({ id, ...patch }, { dispatch, queryFulfilled }) => {
+ *   const patchCollection = dispatch(
+ *     baseApiSlice.util.updateQueryData('getPostById', id, (draftPost) => {
+ *       Object.assign(draftPost, patch)
+ *     }),
+ *   )
+ *
+ *   try {
+ *     await queryFulfilled
+ *   } catch {
+ *     patchCollection.undo()
+ *   }
+ * }
+ *
+ * export const extendedApiSlice = baseApiSlice.injectEndpoints({
+ *   endpoints: (build) => ({
+ *     addPost: build.mutation<Post, Omit<QueryArgument, 'id'>>({
+ *       query: (body) => ({
+ *         url: `posts/add`,
+ *         method: 'POST',
+ *         body,
+ *       }),
+ *
+ *       onQueryStarted: updatePostOnFulfilled,
+ *     }),
+ *
+ *     updatePost: build.mutation<Post, QueryArgument>({
+ *       query: ({ id, ...patch }) => ({
+ *         url: `post/${id}`,
+ *         method: 'PATCH',
+ *         body: patch,
+ *       }),
+ *
+ *       onQueryStarted: updatePostOnFulfilled,
+ *     }),
+ *   }),
+ * })
+ * ```
+ *
+ * @template ResultType - The type of the result `data` returned by the query.
+ * @template QueryArgumentType - The type of the argument passed into the query.
+ * @template BaseQueryFunctionType - The type of the base query function being used.
+ * @template ReducerPath - The type representing the `reducerPath` for the API slice.
+ *
+ * @since 2.4.0
+ * @public
+ */
+export type TypedMutationOnQueryStarted<
+  ResultType,
+  QueryArgumentType,
+  BaseQueryFunctionType extends BaseQueryFn,
+  ReducerPath extends string = string,
+> = QueryLifecycleMutationExtraOptions<
+  ResultType,
+  QueryArgumentType,
+  BaseQueryFunctionType,
+  ReducerPath
+>['onQueryStarted']
+
+export const buildQueryLifecycleHandler: InternalHandlerBuilder = ({
+  api,
+  context,
+  queryThunk,
+  mutationThunk,
+}) => {
+  const isPendingThunk = isPending(queryThunk, mutationThunk)
+  const isRejectedThunk = isRejected(queryThunk, mutationThunk)
+  const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk)
+
+  type CacheLifecycle = {
+    resolve(value: { data: unknown; meta: unknown }): unknown
+    reject(value: QueryFulfilledRejectionReason<any>): unknown
+  }
+  const lifecycleMap: Record<string, CacheLifecycle> = {}
+
+  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {
+    if (isPendingThunk(action)) {
+      const {
+        requestId,
+        arg: { endpointName, originalArgs },
+      } = action.meta
+      const endpointDefinition = getEndpointDefinition(context, endpointName)
+      const onQueryStarted = endpointDefinition?.onQueryStarted
+      if (onQueryStarted) {
+        const lifecycle = {} as CacheLifecycle
+        const queryFulfilled =
+          new (Promise as PromiseConstructorWithKnownReason)<
+            { data: unknown; meta: unknown },
+            QueryFulfilledRejectionReason<any>
+          >((resolve, reject) => {
+            lifecycle.resolve = resolve
+            lifecycle.reject = reject
+          })
+        // prevent uncaught promise rejections from happening.
+        // if the original promise is used in any way, that will create a new promise that will throw again
+        queryFulfilled.catch(() => {})
+        lifecycleMap[requestId] = lifecycle
+        const selector = (api.endpoints[endpointName] as any).select(
+          isAnyQueryDefinition(endpointDefinition) ? originalArgs : requestId,
+        )
+
+        const extra = mwApi.dispatch((_, __, extra) => extra)
+        const lifecycleApi = {
+          ...mwApi,
+          getCacheEntry: () => selector(mwApi.getState()),
+          requestId,
+          extra,
+          updateCachedData: (isAnyQueryDefinition(endpointDefinition)
+            ? (updateRecipe: Recipe<any>) =>
+                mwApi.dispatch(
+                  api.util.updateQueryData(
+                    endpointName as never,
+                    originalArgs as never,
+                    updateRecipe,
+                  ),
+                )
+            : undefined) as any,
+          queryFulfilled,
+        }
+        onQueryStarted(originalArgs, lifecycleApi as any)
+      }
+    } else if (isFullfilledThunk(action)) {
+      const { requestId, baseQueryMeta } = action.meta
+      lifecycleMap[requestId]?.resolve({
+        data: action.payload,
+        meta: baseQueryMeta,
+      })
+      delete lifecycleMap[requestId]
+    } else if (isRejectedThunk(action)) {
+      const { requestId, rejectedWithValue, baseQueryMeta } = action.meta
+      lifecycleMap[requestId]?.reject({
+        error: action.payload ?? action.error,
+        isUnhandledError: !rejectedWithValue,
+        meta: baseQueryMeta as any,
+      })
+      delete lifecycleMap[requestId]
+    }
+  }
+
+  return handler
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/types.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/types.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/types.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,173 @@
+import type {
+  Action,
+  AsyncThunkAction,
+  Dispatch,
+  Middleware,
+  MiddlewareAPI,
+  ThunkAction,
+  ThunkDispatch,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import type { Api, ApiContext } from '../../apiTypes'
+import type {
+  AssertTagTypes,
+  EndpointDefinitions,
+} from '../../endpointDefinitions'
+import type {
+  QueryStatus,
+  QuerySubState,
+  RootState,
+  SubscriptionInternalState,
+  SubscriptionState,
+} from '../apiState'
+import type {
+  InfiniteQueryThunk,
+  MutationThunk,
+  QueryThunk,
+  QueryThunkArg,
+  ThunkResult,
+} from '../buildThunks'
+import type {
+  InfiniteQueryActionCreatorResult,
+  MutationActionCreatorResult,
+  QueryActionCreatorResult,
+} from '../buildInitiate'
+import type { AllSelectors } from '../buildSelectors'
+
+export type QueryStateMeta<T> = Record<string, undefined | T>
+export type TimeoutId = ReturnType<typeof setTimeout>
+
+type QueryPollState = {
+  nextPollTimestamp: number
+  timeout?: TimeoutId
+  pollingInterval: number
+}
+
+export interface InternalMiddlewareState {
+  currentSubscriptions: SubscriptionInternalState
+  currentPolls: Map<string, QueryPollState>
+  runningQueries: Map<
+    string,
+    | QueryActionCreatorResult<any>
+    | InfiniteQueryActionCreatorResult<any>
+    | undefined
+  >
+  runningMutations: Map<string, MutationActionCreatorResult<any> | undefined>
+}
+
+export interface SubscriptionSelectors {
+  getSubscriptions: () => SubscriptionInternalState
+  getSubscriptionCount: (queryCacheKey: string) => number
+  isRequestSubscribed: (queryCacheKey: string, requestId: string) => boolean
+}
+
+export interface BuildMiddlewareInput<
+  Definitions extends EndpointDefinitions,
+  ReducerPath extends string,
+  TagTypes extends string,
+> {
+  reducerPath: ReducerPath
+  context: ApiContext<Definitions>
+  queryThunk: QueryThunk
+  mutationThunk: MutationThunk
+  infiniteQueryThunk: InfiniteQueryThunk<any>
+  api: Api<any, Definitions, ReducerPath, TagTypes>
+  assertTagType: AssertTagTypes
+  selectors: AllSelectors
+  getRunningQueryThunk: (
+    endpointName: string,
+    queryArgs: any,
+  ) => (dispatch: Dispatch) => QueryActionCreatorResult<any> | undefined
+  getInternalState: (dispatch: Dispatch) => InternalMiddlewareState
+}
+
+export type SubMiddlewareApi = MiddlewareAPI<
+  ThunkDispatch<any, any, UnknownAction>,
+  RootState<EndpointDefinitions, string, string>
+>
+
+export interface BuildSubMiddlewareInput
+  extends BuildMiddlewareInput<EndpointDefinitions, string, string> {
+  internalState: InternalMiddlewareState
+  refetchQuery(
+    querySubState: Exclude<
+      QuerySubState<any>,
+      { status: QueryStatus.uninitialized }
+    >,
+  ): ThunkAction<QueryActionCreatorResult<any>, any, any, UnknownAction>
+  isThisApiSliceAction: (action: Action) => boolean
+  selectors: AllSelectors
+  mwApi: MiddlewareAPI<
+    ThunkDispatch<any, any, UnknownAction>,
+    RootState<EndpointDefinitions, string, string>
+  >
+}
+
+export type SubMiddlewareBuilder = (
+  input: BuildSubMiddlewareInput,
+) => Middleware<
+  {},
+  RootState<EndpointDefinitions, string, string>,
+  ThunkDispatch<any, any, UnknownAction>
+>
+
+type MwNext = Parameters<ReturnType<Middleware>>[0]
+
+export type ApiMiddlewareInternalHandler<Return = void> = (
+  action: Action,
+  mwApi: SubMiddlewareApi & { next: MwNext },
+  prevState: RootState<EndpointDefinitions, string, string>,
+) => Return
+
+export type InternalHandlerBuilder<ReturnType = void> = (
+  input: BuildSubMiddlewareInput,
+) => ApiMiddlewareInternalHandler<ReturnType>
+
+export interface PromiseConstructorWithKnownReason {
+  /**
+   * Creates a new Promise with a known rejection reason.
+   * @param executor A callback used to initialize the promise. This callback is passed two arguments:
+   * a resolve callback used to resolve the promise with a value or the result of another promise,
+   * and a reject callback used to reject the promise with a provided reason or error.
+   */
+  new <T, R>(
+    executor: (
+      resolve: (value: T | PromiseLike<T>) => void,
+      reject: (reason?: R) => void,
+    ) => void,
+  ): PromiseWithKnownReason<T, R>
+}
+
+export type PromiseWithKnownReason<T, R> = Omit<
+  Promise<T>,
+  'then' | 'catch'
+> & {
+  /**
+   * Attaches callbacks for the resolution and/or rejection of the Promise.
+   * @param onfulfilled The callback to execute when the Promise is resolved.
+   * @param onrejected The callback to execute when the Promise is rejected.
+   * @returns A Promise for the completion of which ever callback is executed.
+   */
+  then<TResult1 = T, TResult2 = never>(
+    onfulfilled?:
+      | ((value: T) => TResult1 | PromiseLike<TResult1>)
+      | undefined
+      | null,
+    onrejected?:
+      | ((reason: R) => TResult2 | PromiseLike<TResult2>)
+      | undefined
+      | null,
+  ): Promise<TResult1 | TResult2>
+
+  /**
+   * Attaches a callback for only the rejection of the Promise.
+   * @param onrejected The callback to execute when the Promise is rejected.
+   * @returns A Promise for the completion of the callback.
+   */
+  catch<TResult = never>(
+    onrejected?:
+      | ((reason: R) => TResult | PromiseLike<TResult>)
+      | undefined
+      | null,
+  ): Promise<T | TResult>
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/windowEventHandling.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/windowEventHandling.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildMiddleware/windowEventHandling.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,64 @@
+import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'
+import type { QueryCacheKey } from '../apiState'
+import { onFocus, onOnline } from '../setupListeners'
+import type {
+  ApiMiddlewareInternalHandler,
+  InternalHandlerBuilder,
+  SubMiddlewareApi,
+} from './types'
+
+export const buildWindowEventHandler: InternalHandlerBuilder = ({
+  reducerPath,
+  context,
+  api,
+  refetchQuery,
+  internalState,
+}) => {
+  const { removeQueryResult } = api.internalActions
+
+  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {
+    if (onFocus.match(action)) {
+      refetchValidQueries(mwApi, 'refetchOnFocus')
+    }
+    if (onOnline.match(action)) {
+      refetchValidQueries(mwApi, 'refetchOnReconnect')
+    }
+  }
+
+  function refetchValidQueries(
+    api: SubMiddlewareApi,
+    type: 'refetchOnFocus' | 'refetchOnReconnect',
+  ) {
+    const state = api.getState()[reducerPath]
+    const queries = state.queries
+    const subscriptions = internalState.currentSubscriptions
+
+    context.batch(() => {
+      for (const queryCacheKey of subscriptions.keys()) {
+        const querySubState = queries[queryCacheKey]
+        const subscriptionSubState = subscriptions.get(queryCacheKey)
+
+        if (!subscriptionSubState || !querySubState) continue
+
+        const values = [...subscriptionSubState.values()]
+        const shouldRefetch =
+          values.some((sub) => sub[type] === true) ||
+          (values.every((sub) => sub[type] === undefined) && state.config[type])
+
+        if (shouldRefetch) {
+          if (subscriptionSubState.size === 0) {
+            api.dispatch(
+              removeQueryResult({
+                queryCacheKey: queryCacheKey as QueryCacheKey,
+              }),
+            )
+          } else if (querySubState.status !== STATUS_UNINITIALIZED) {
+            api.dispatch(refetchQuery(querySubState))
+          }
+        }
+      }
+    })
+  }
+
+  return handler
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildSelectors.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildSelectors.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildSelectors.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,413 @@
+import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
+import type {
+  EndpointDefinition,
+  EndpointDefinitions,
+  InfiniteQueryArgFrom,
+  InfiniteQueryDefinition,
+  MutationDefinition,
+  QueryArgFrom,
+  QueryArgFromAnyQuery,
+  QueryDefinition,
+  ReducerPathFrom,
+  TagDescription,
+  TagTypesFrom,
+} from '../endpointDefinitions'
+import { expandTagDescription } from '../endpointDefinitions'
+import { filterMap, isNotNullish } from '../utils'
+import type {
+  InfiniteData,
+  InfiniteQueryConfigOptions,
+  InfiniteQuerySubState,
+  MutationSubState,
+  QueryCacheKey,
+  QueryState,
+  QuerySubState,
+  RequestStatusFlags,
+  RootState as _RootState,
+  QueryStatus,
+} from './apiState'
+import { STATUS_UNINITIALIZED, getRequestStatusFlags } from './apiState'
+import { getMutationCacheKey } from './buildSlice'
+import type { createSelector as _createSelector } from './rtkImports'
+import { createNextState } from './rtkImports'
+import {
+  type AllQueryKeys,
+  getNextPageParam,
+  getPreviousPageParam,
+} from './buildThunks'
+
+export type SkipToken = typeof skipToken
+/**
+ * Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`
+ * instead of the query argument to get the same effect as if setting
+ * `skip: true` in the query options.
+ *
+ * Useful for scenarios where a query should be skipped when `arg` is `undefined`
+ * and TypeScript complains about it because `arg` is not allowed to be passed
+ * in as `undefined`, such as
+ *
+ * ```ts
+ * // codeblock-meta title="will error if the query argument is not allowed to be undefined" no-transpile
+ * useSomeQuery(arg, { skip: !!arg })
+ * ```
+ *
+ * ```ts
+ * // codeblock-meta title="using skipToken instead" no-transpile
+ * useSomeQuery(arg ?? skipToken)
+ * ```
+ *
+ * If passed directly into a query or mutation selector, that selector will always
+ * return an uninitialized state.
+ */
+export const skipToken = /* @__PURE__ */ Symbol.for('RTKQ/skipToken')
+
+export type BuildSelectorsApiEndpointQuery<
+  Definition extends QueryDefinition<any, any, any, any, any>,
+  Definitions extends EndpointDefinitions,
+> = {
+  select: QueryResultSelectorFactory<
+    Definition,
+    _RootState<
+      Definitions,
+      TagTypesFrom<Definition>,
+      ReducerPathFrom<Definition>
+    >
+  >
+}
+
+export type BuildSelectorsApiEndpointInfiniteQuery<
+  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
+  Definitions extends EndpointDefinitions,
+> = {
+  select: InfiniteQueryResultSelectorFactory<
+    Definition,
+    _RootState<
+      Definitions,
+      TagTypesFrom<Definition>,
+      ReducerPathFrom<Definition>
+    >
+  >
+}
+
+export type BuildSelectorsApiEndpointMutation<
+  Definition extends MutationDefinition<any, any, any, any, any>,
+  Definitions extends EndpointDefinitions,
+> = {
+  select: MutationResultSelectorFactory<
+    Definition,
+    _RootState<
+      Definitions,
+      TagTypesFrom<Definition>,
+      ReducerPathFrom<Definition>
+    >
+  >
+}
+
+type QueryResultSelectorFactory<
+  Definition extends QueryDefinition<any, any, any, any>,
+  RootState,
+> = (
+  queryArg: QueryArgFrom<Definition> | SkipToken,
+) => (state: RootState) => QueryResultSelectorResult<Definition>
+
+export type QueryResultSelectorResult<
+  Definition extends QueryDefinition<any, any, any, any>,
+> = QuerySubState<Definition> & RequestStatusFlags
+
+type InfiniteQueryResultSelectorFactory<
+  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
+  RootState,
+> = (
+  queryArg: InfiniteQueryArgFrom<Definition> | SkipToken,
+) => (state: RootState) => InfiniteQueryResultSelectorResult<Definition>
+
+export type InfiniteQueryResultFlags = {
+  hasNextPage: boolean
+  hasPreviousPage: boolean
+  isFetchingNextPage: boolean
+  isFetchingPreviousPage: boolean
+  isFetchNextPageError: boolean
+  isFetchPreviousPageError: boolean
+}
+
+export type InfiniteQueryResultSelectorResult<
+  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = InfiniteQuerySubState<Definition> &
+  RequestStatusFlags &
+  InfiniteQueryResultFlags
+
+type MutationResultSelectorFactory<
+  Definition extends MutationDefinition<any, any, any, any>,
+  RootState,
+> = (
+  requestId:
+    | string
+    | { requestId: string | undefined; fixedCacheKey: string | undefined }
+    | SkipToken,
+) => (state: RootState) => MutationResultSelectorResult<Definition>
+
+export type MutationResultSelectorResult<
+  Definition extends MutationDefinition<any, any, any, any>,
+> = MutationSubState<Definition> & RequestStatusFlags
+
+const initialSubState: QuerySubState<any> = {
+  status: STATUS_UNINITIALIZED,
+}
+
+// abuse immer to freeze default states
+const defaultQuerySubState = /* @__PURE__ */ createNextState(
+  initialSubState,
+  () => {},
+)
+const defaultMutationSubState = /* @__PURE__ */ createNextState(
+  initialSubState as MutationSubState<any>,
+  () => {},
+)
+
+export type AllSelectors = ReturnType<typeof buildSelectors>
+
+export function buildSelectors<
+  Definitions extends EndpointDefinitions,
+  ReducerPath extends string,
+>({
+  serializeQueryArgs,
+  reducerPath,
+  createSelector,
+}: {
+  serializeQueryArgs: InternalSerializeQueryArgs
+  reducerPath: ReducerPath
+  createSelector: typeof _createSelector
+}) {
+  type RootState = _RootState<Definitions, string, string>
+
+  const selectSkippedQuery = (state: RootState) => defaultQuerySubState
+  const selectSkippedMutation = (state: RootState) => defaultMutationSubState
+
+  return {
+    buildQuerySelector,
+    buildInfiniteQuerySelector,
+    buildMutationSelector,
+    selectInvalidatedBy,
+    selectCachedArgsForQuery,
+    selectApiState,
+    selectQueries,
+    selectMutations,
+    selectQueryEntry,
+    selectConfig,
+  }
+
+  function withRequestFlags<T extends { status: QueryStatus }>(
+    substate: T,
+  ): T & RequestStatusFlags {
+    return { ...substate, ...getRequestStatusFlags(substate.status) }
+  }
+
+  function selectApiState(rootState: RootState) {
+    const state = rootState[reducerPath]
+    if (process.env.NODE_ENV !== 'production') {
+      if (!state) {
+        if ((selectApiState as any).triggered) return state
+        ;(selectApiState as any).triggered = true
+        console.error(
+          `Error: No data found at \`state.${reducerPath}\`. Did you forget to add the reducer to the store?`,
+        )
+      }
+    }
+    return state
+  }
+
+  function selectQueries(rootState: RootState) {
+    return selectApiState(rootState)?.queries
+  }
+
+  function selectQueryEntry(rootState: RootState, cacheKey: QueryCacheKey) {
+    return selectQueries(rootState)?.[cacheKey]
+  }
+
+  function selectMutations(rootState: RootState) {
+    return selectApiState(rootState)?.mutations
+  }
+
+  function selectConfig(rootState: RootState) {
+    return selectApiState(rootState)?.config
+  }
+
+  function buildAnyQuerySelector(
+    endpointName: string,
+    endpointDefinition: EndpointDefinition<any, any, any, any>,
+    combiner: <T extends { status: QueryStatus }>(
+      substate: T,
+    ) => T & RequestStatusFlags,
+  ) {
+    return (queryArgs: any) => {
+      // Avoid calling serializeQueryArgs if the arg is skipToken
+      if (queryArgs === skipToken) {
+        return createSelector(selectSkippedQuery, combiner)
+      }
+
+      const serializedArgs = serializeQueryArgs({
+        queryArgs,
+        endpointDefinition,
+        endpointName,
+      })
+      const selectQuerySubstate = (state: RootState) =>
+        selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState
+
+      return createSelector(selectQuerySubstate, combiner)
+    }
+  }
+
+  function buildQuerySelector(
+    endpointName: string,
+    endpointDefinition: QueryDefinition<any, any, any, any>,
+  ) {
+    return buildAnyQuerySelector(
+      endpointName,
+      endpointDefinition,
+      withRequestFlags,
+    ) as QueryResultSelectorFactory<any, RootState>
+  }
+
+  function buildInfiniteQuerySelector(
+    endpointName: string,
+    endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>,
+  ) {
+    const { infiniteQueryOptions } = endpointDefinition
+
+    function withInfiniteQueryResultFlags<T extends { status: QueryStatus }>(
+      substate: T,
+    ): T & RequestStatusFlags & InfiniteQueryResultFlags {
+      const stateWithRequestFlags = {
+        ...(substate as InfiniteQuerySubState<any>),
+        ...getRequestStatusFlags(substate.status),
+      }
+
+      const { isLoading, isError, direction } = stateWithRequestFlags
+      const isForward = direction === 'forward'
+      const isBackward = direction === 'backward'
+
+      return {
+        ...stateWithRequestFlags,
+        hasNextPage: getHasNextPage(
+          infiniteQueryOptions,
+          stateWithRequestFlags.data,
+          stateWithRequestFlags.originalArgs,
+        ),
+        hasPreviousPage: getHasPreviousPage(
+          infiniteQueryOptions,
+          stateWithRequestFlags.data,
+          stateWithRequestFlags.originalArgs,
+        ),
+        isFetchingNextPage: isLoading && isForward,
+        isFetchingPreviousPage: isLoading && isBackward,
+        isFetchNextPageError: isError && isForward,
+        isFetchPreviousPageError: isError && isBackward,
+      }
+    }
+
+    return buildAnyQuerySelector(
+      endpointName,
+      endpointDefinition,
+      withInfiniteQueryResultFlags,
+    ) as unknown as InfiniteQueryResultSelectorFactory<any, RootState>
+  }
+
+  function buildMutationSelector() {
+    return ((id) => {
+      let mutationId: string | typeof skipToken
+      if (typeof id === 'object') {
+        mutationId = getMutationCacheKey(id) ?? skipToken
+      } else {
+        mutationId = id
+      }
+      const selectMutationSubstate = (state: RootState) =>
+        selectApiState(state)?.mutations?.[mutationId as string] ??
+        defaultMutationSubState
+      const finalSelectMutationSubstate =
+        mutationId === skipToken
+          ? selectSkippedMutation
+          : selectMutationSubstate
+
+      return createSelector(finalSelectMutationSubstate, withRequestFlags)
+    }) as MutationResultSelectorFactory<any, RootState>
+  }
+
+  function selectInvalidatedBy(
+    state: RootState,
+    tags: ReadonlyArray<TagDescription<string> | null | undefined>,
+  ): Array<{
+    endpointName: string
+    originalArgs: any
+    queryCacheKey: QueryCacheKey
+  }> {
+    const apiState = state[reducerPath]
+    const toInvalidate = new Set<QueryCacheKey>()
+    const finalTags = filterMap(tags, isNotNullish, expandTagDescription)
+    for (const tag of finalTags) {
+      const provided = apiState.provided.tags[tag.type]
+      if (!provided) {
+        continue
+      }
+
+      let invalidateSubscriptions =
+        (tag.id !== undefined
+          ? // id given: invalidate all queries that provide this type & id
+            provided[tag.id]
+          : // no id: invalidate all queries that provide this type
+            Object.values(provided).flat()) ?? []
+
+      for (const invalidate of invalidateSubscriptions) {
+        toInvalidate.add(invalidate)
+      }
+    }
+
+    return Array.from(toInvalidate.values()).flatMap((queryCacheKey) => {
+      const querySubState = apiState.queries[queryCacheKey]
+      return querySubState
+        ? {
+            queryCacheKey,
+            endpointName: querySubState.endpointName!,
+            originalArgs: querySubState.originalArgs,
+          }
+        : []
+    })
+  }
+
+  function selectCachedArgsForQuery<
+    QueryName extends AllQueryKeys<Definitions>,
+  >(
+    state: RootState,
+    queryName: QueryName,
+  ): Array<QueryArgFromAnyQuery<Definitions[QueryName]>> {
+    return filterMap(
+      Object.values(selectQueries(state) as QueryState<any>),
+      (
+        entry,
+      ): entry is Exclude<
+        QuerySubState<Definitions[QueryName]>,
+        { status: QueryStatus.uninitialized }
+      > =>
+        entry?.endpointName === queryName &&
+        entry.status !== STATUS_UNINITIALIZED,
+      (entry) => entry.originalArgs,
+    )
+  }
+
+  function getHasNextPage(
+    options: InfiniteQueryConfigOptions<any, any, any>,
+    data?: InfiniteData<unknown, unknown>,
+    queryArg?: unknown,
+  ): boolean {
+    if (!data) return false
+    return getNextPageParam(options, data, queryArg) != null
+  }
+
+  function getHasPreviousPage(
+    options: InfiniteQueryConfigOptions<any, any, any>,
+    data?: InfiniteData<unknown, unknown>,
+    queryArg?: unknown,
+  ): boolean {
+    if (!data || !options.getPreviousPageParam) return false
+    return getPreviousPageParam(options, data, queryArg) != null
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/buildSlice.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildSlice.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildSlice.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,735 @@
+import type { PayloadAction } from '@reduxjs/toolkit'
+import {
+  combineReducers,
+  createAction,
+  createSlice,
+  isAnyOf,
+  isFulfilled,
+  isRejectedWithValue,
+  createNextState,
+  prepareAutoBatched,
+  SHOULD_AUTOBATCH,
+  nanoid,
+} from './rtkImports'
+import type {
+  QuerySubstateIdentifier,
+  QuerySubState,
+  MutationSubstateIdentifier,
+  MutationSubState,
+  MutationState,
+  QueryState,
+  InvalidationState,
+  Subscribers,
+  QueryCacheKey,
+  SubscriptionState,
+  ConfigState,
+  InfiniteQuerySubState,
+  InfiniteQueryDirection,
+} from './apiState'
+import {
+  STATUS_FULFILLED,
+  STATUS_PENDING,
+  QueryStatus,
+  STATUS_REJECTED,
+  STATUS_UNINITIALIZED,
+} from './apiState'
+import type {
+  AllQueryKeys,
+  QueryArgFromAnyQueryDefinition,
+  DataFromAnyQueryDefinition,
+  InfiniteQueryThunk,
+  MutationThunk,
+  QueryThunk,
+  QueryThunkArg,
+} from './buildThunks'
+import { calculateProvidedByThunk } from './buildThunks'
+import {
+  ENDPOINT_QUERY,
+  isInfiniteQueryDefinition,
+  type AssertTagTypes,
+  type EndpointDefinitions,
+  type FullTagDescription,
+  type QueryDefinition,
+} from '../endpointDefinitions'
+import type { Patch } from 'immer'
+import { applyPatches, original, isDraft } from '../utils/immerImports'
+import { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners'
+import {
+  isDocumentVisible,
+  isOnline,
+  copyWithStructuralSharing,
+} from '../utils'
+import type { ApiContext } from '../apiTypes'
+import { isUpsertQuery } from './buildInitiate'
+import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
+import type { UnwrapPromise } from '../tsHelpers'
+import { getCurrent } from '../utils/getCurrent'
+
+/**
+ * A typesafe single entry to be upserted into the cache
+ */
+export type NormalizedQueryUpsertEntry<
+  Definitions extends EndpointDefinitions,
+  EndpointName extends AllQueryKeys<Definitions>,
+> = {
+  endpointName: EndpointName
+  arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>
+  value: DataFromAnyQueryDefinition<Definitions, EndpointName>
+}
+
+/**
+ * The internal version that is not typesafe since we can't carry the generics through `createSlice`
+ */
+type NormalizedQueryUpsertEntryPayload = {
+  endpointName: string
+  arg: unknown
+  value: unknown
+}
+
+export type ProcessedQueryUpsertEntry = {
+  queryDescription: QueryThunkArg
+  value: unknown
+}
+
+/**
+ * A typesafe representation of a util action creator that accepts cache entry descriptions to upsert
+ */
+export type UpsertEntries<Definitions extends EndpointDefinitions> = (<
+  EndpointNames extends Array<AllQueryKeys<Definitions>>,
+>(
+  entries: [
+    ...{
+      [I in keyof EndpointNames]: NormalizedQueryUpsertEntry<
+        Definitions,
+        EndpointNames[I]
+      >
+    },
+  ],
+) => PayloadAction<NormalizedQueryUpsertEntryPayload[]>) & {
+  match: (
+    action: unknown,
+  ) => action is PayloadAction<NormalizedQueryUpsertEntryPayload[]>
+}
+
+function updateQuerySubstateIfExists(
+  state: QueryState<any>,
+  queryCacheKey: QueryCacheKey,
+  update: (substate: QuerySubState<any> | InfiniteQuerySubState<any>) => void,
+) {
+  const substate = state[queryCacheKey]
+  if (substate) {
+    update(substate)
+  }
+}
+
+export function getMutationCacheKey(
+  id:
+    | MutationSubstateIdentifier
+    | { requestId: string; arg: { fixedCacheKey?: string | undefined } },
+): string
+export function getMutationCacheKey(id: {
+  fixedCacheKey?: string
+  requestId?: string
+}): string | undefined
+
+export function getMutationCacheKey(
+  id:
+    | { fixedCacheKey?: string; requestId?: string }
+    | MutationSubstateIdentifier
+    | { requestId: string; arg: { fixedCacheKey?: string | undefined } },
+): string | undefined {
+  return ('arg' in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId
+}
+
+function updateMutationSubstateIfExists(
+  state: MutationState<any>,
+  id:
+    | MutationSubstateIdentifier
+    | { requestId: string; arg: { fixedCacheKey?: string | undefined } },
+  update: (substate: MutationSubState<any>) => void,
+) {
+  const substate = state[getMutationCacheKey(id)]
+  if (substate) {
+    update(substate)
+  }
+}
+
+const initialState = {} as any
+
+export function buildSlice({
+  reducerPath,
+  queryThunk,
+  mutationThunk,
+  serializeQueryArgs,
+  context: {
+    endpointDefinitions: definitions,
+    apiUid,
+    extractRehydrationInfo,
+    hasRehydrationInfo,
+  },
+  assertTagType,
+  config,
+}: {
+  reducerPath: string
+  queryThunk: QueryThunk
+  infiniteQueryThunk: InfiniteQueryThunk<any>
+  mutationThunk: MutationThunk
+  serializeQueryArgs: InternalSerializeQueryArgs
+  context: ApiContext<EndpointDefinitions>
+  assertTagType: AssertTagTypes
+  config: Omit<
+    ConfigState<string>,
+    'online' | 'focused' | 'middlewareRegistered'
+  >
+}) {
+  const resetApiState = createAction(`${reducerPath}/resetApiState`)
+
+  function writePendingCacheEntry(
+    draft: QueryState<any>,
+    arg: QueryThunkArg,
+    upserting: boolean,
+    meta: {
+      arg: QueryThunkArg
+      requestId: string
+      // requestStatus: 'pending'
+    } & { startedTimeStamp: number },
+  ) {
+    draft[arg.queryCacheKey] ??= {
+      status: STATUS_UNINITIALIZED,
+      endpointName: arg.endpointName,
+    }
+
+    updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
+      substate.status = STATUS_PENDING
+
+      substate.requestId =
+        upserting && substate.requestId
+          ? // for `upsertQuery` **updates**, keep the current `requestId`
+            substate.requestId
+          : // for normal queries or `upsertQuery` **inserts** always update the `requestId`
+            meta.requestId
+      if (arg.originalArgs !== undefined) {
+        substate.originalArgs = arg.originalArgs
+      }
+      substate.startedTimeStamp = meta.startedTimeStamp
+
+      const endpointDefinition = definitions[meta.arg.endpointName]
+
+      if (isInfiniteQueryDefinition(endpointDefinition) && 'direction' in arg) {
+        ;(substate as InfiniteQuerySubState<any>).direction =
+          arg.direction as InfiniteQueryDirection
+      }
+    })
+  }
+
+  function writeFulfilledCacheEntry(
+    draft: QueryState<any>,
+    meta: { arg: QueryThunkArg; requestId: string } & {
+      fulfilledTimeStamp: number
+      baseQueryMeta: unknown
+    },
+    payload: unknown,
+    upserting: boolean,
+  ) {
+    updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, (substate) => {
+      if (substate.requestId !== meta.requestId && !upserting) return
+      const { merge } = definitions[meta.arg.endpointName] as QueryDefinition<
+        any,
+        any,
+        any,
+        any
+      >
+      substate.status = STATUS_FULFILLED
+
+      if (merge) {
+        if (substate.data !== undefined) {
+          const { fulfilledTimeStamp, arg, baseQueryMeta, requestId } = meta
+          // There's existing cache data. Let the user merge it in themselves.
+          // We're already inside an Immer-powered reducer, and the user could just mutate `substate.data`
+          // themselves inside of `merge()`. But, they might also want to return a new value.
+          // Try to let Immer figure that part out, save the result, and assign it to `substate.data`.
+          let newData = createNextState(substate.data, (draftSubstateData) => {
+            // As usual with Immer, you can mutate _or_ return inside here, but not both
+            return merge(draftSubstateData, payload, {
+              arg: arg.originalArgs,
+              baseQueryMeta,
+              fulfilledTimeStamp,
+              requestId,
+            })
+          })
+          substate.data = newData
+        } else {
+          // Presumably a fresh request. Just cache the response data.
+          substate.data = payload
+        }
+      } else {
+        // Assign or safely update the cache data.
+        substate.data =
+          (definitions[meta.arg.endpointName].structuralSharing ?? true)
+            ? copyWithStructuralSharing(
+                isDraft(substate.data)
+                  ? original(substate.data)
+                  : substate.data,
+                payload,
+              )
+            : payload
+      }
+
+      delete substate.error
+      substate.fulfilledTimeStamp = meta.fulfilledTimeStamp
+    })
+  }
+
+  const querySlice = createSlice({
+    name: `${reducerPath}/queries`,
+    initialState: initialState as QueryState<any>,
+    reducers: {
+      removeQueryResult: {
+        reducer(
+          draft,
+          {
+            payload: { queryCacheKey },
+          }: PayloadAction<QuerySubstateIdentifier>,
+        ) {
+          delete draft[queryCacheKey]
+        },
+        prepare: prepareAutoBatched<QuerySubstateIdentifier>(),
+      },
+      cacheEntriesUpserted: {
+        reducer(
+          draft,
+          action: PayloadAction<
+            ProcessedQueryUpsertEntry[],
+            string,
+            { RTK_autoBatch: boolean; requestId: string; timestamp: number }
+          >,
+        ) {
+          for (const entry of action.payload) {
+            const { queryDescription: arg, value } = entry
+            writePendingCacheEntry(draft, arg, true, {
+              arg,
+              requestId: action.meta.requestId,
+              startedTimeStamp: action.meta.timestamp,
+            })
+
+            writeFulfilledCacheEntry(
+              draft,
+              {
+                arg,
+                requestId: action.meta.requestId,
+                fulfilledTimeStamp: action.meta.timestamp,
+                baseQueryMeta: {},
+              },
+              value,
+              // We know we're upserting here
+              true,
+            )
+          }
+        },
+        prepare: (payload: NormalizedQueryUpsertEntryPayload[]) => {
+          const queryDescriptions: ProcessedQueryUpsertEntry[] = payload.map(
+            (entry) => {
+              const { endpointName, arg, value } = entry
+              const endpointDefinition = definitions[endpointName]
+              const queryDescription: QueryThunkArg = {
+                type: ENDPOINT_QUERY as 'query',
+                endpointName,
+                originalArgs: entry.arg,
+                queryCacheKey: serializeQueryArgs({
+                  queryArgs: arg,
+                  endpointDefinition,
+                  endpointName,
+                }),
+              }
+              return { queryDescription, value }
+            },
+          )
+
+          const result = {
+            payload: queryDescriptions,
+            meta: {
+              [SHOULD_AUTOBATCH]: true,
+              requestId: nanoid(),
+              timestamp: Date.now(),
+            },
+          }
+          return result
+        },
+      },
+      queryResultPatched: {
+        reducer(
+          draft,
+          {
+            payload: { queryCacheKey, patches },
+          }: PayloadAction<
+            QuerySubstateIdentifier & { patches: readonly Patch[] }
+          >,
+        ) {
+          updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {
+            substate.data = applyPatches(substate.data as any, patches.concat())
+          })
+        },
+        prepare: prepareAutoBatched<
+          QuerySubstateIdentifier & { patches: readonly Patch[] }
+        >(),
+      },
+    },
+    extraReducers(builder) {
+      builder
+        .addCase(queryThunk.pending, (draft, { meta, meta: { arg } }) => {
+          const upserting = isUpsertQuery(arg)
+          writePendingCacheEntry(draft, arg, upserting, meta)
+        })
+        .addCase(queryThunk.fulfilled, (draft, { meta, payload }) => {
+          const upserting = isUpsertQuery(meta.arg)
+          writeFulfilledCacheEntry(draft, meta, payload, upserting)
+        })
+        .addCase(
+          queryThunk.rejected,
+          (draft, { meta: { condition, arg, requestId }, error, payload }) => {
+            updateQuerySubstateIfExists(
+              draft,
+              arg.queryCacheKey,
+              (substate) => {
+                if (condition) {
+                  // request was aborted due to condition (another query already running)
+                } else {
+                  // request failed
+                  if (substate.requestId !== requestId) return
+                  substate.status = STATUS_REJECTED
+                  substate.error = (payload ?? error) as any
+                }
+              },
+            )
+          },
+        )
+        .addMatcher(hasRehydrationInfo, (draft, action) => {
+          const { queries } = extractRehydrationInfo(action)!
+          for (const [key, entry] of Object.entries(queries)) {
+            if (
+              // do not rehydrate entries that were currently in flight.
+              entry?.status === STATUS_FULFILLED ||
+              entry?.status === STATUS_REJECTED
+            ) {
+              draft[key] = entry
+            }
+          }
+        })
+    },
+  })
+  const mutationSlice = createSlice({
+    name: `${reducerPath}/mutations`,
+    initialState: initialState as MutationState<any>,
+    reducers: {
+      removeMutationResult: {
+        reducer(draft, { payload }: PayloadAction<MutationSubstateIdentifier>) {
+          const cacheKey = getMutationCacheKey(payload)
+          if (cacheKey in draft) {
+            delete draft[cacheKey]
+          }
+        },
+        prepare: prepareAutoBatched<MutationSubstateIdentifier>(),
+      },
+    },
+    extraReducers(builder) {
+      builder
+        .addCase(
+          mutationThunk.pending,
+          (draft, { meta, meta: { requestId, arg, startedTimeStamp } }) => {
+            if (!arg.track) return
+
+            draft[getMutationCacheKey(meta)] = {
+              requestId,
+              status: STATUS_PENDING,
+              endpointName: arg.endpointName,
+              startedTimeStamp,
+            }
+          },
+        )
+        .addCase(mutationThunk.fulfilled, (draft, { payload, meta }) => {
+          if (!meta.arg.track) return
+
+          updateMutationSubstateIfExists(draft, meta, (substate) => {
+            if (substate.requestId !== meta.requestId) return
+            substate.status = STATUS_FULFILLED
+            substate.data = payload
+            substate.fulfilledTimeStamp = meta.fulfilledTimeStamp
+          })
+        })
+        .addCase(mutationThunk.rejected, (draft, { payload, error, meta }) => {
+          if (!meta.arg.track) return
+
+          updateMutationSubstateIfExists(draft, meta, (substate) => {
+            if (substate.requestId !== meta.requestId) return
+
+            substate.status = STATUS_REJECTED
+            substate.error = (payload ?? error) as any
+          })
+        })
+        .addMatcher(hasRehydrationInfo, (draft, action) => {
+          const { mutations } = extractRehydrationInfo(action)!
+          for (const [key, entry] of Object.entries(mutations)) {
+            if (
+              // do not rehydrate entries that were currently in flight.
+              (entry?.status === STATUS_FULFILLED ||
+                entry?.status === STATUS_REJECTED) &&
+              // only rehydrate endpoints that were persisted using a `fixedCacheKey`
+              key !== entry?.requestId
+            ) {
+              draft[key] = entry
+            }
+          }
+        })
+    },
+  })
+
+  type CalculateProvidedByAction = UnwrapPromise<
+    | ReturnType<ReturnType<QueryThunk>>
+    | ReturnType<ReturnType<InfiniteQueryThunk<any>>>
+  >
+
+  const initialInvalidationState: InvalidationState<string> = {
+    tags: {},
+    keys: {},
+  }
+
+  const invalidationSlice = createSlice({
+    name: `${reducerPath}/invalidation`,
+    initialState: initialInvalidationState,
+    reducers: {
+      updateProvidedBy: {
+        reducer(
+          draft,
+          action: PayloadAction<
+            Array<{
+              queryCacheKey: QueryCacheKey
+              providedTags: readonly FullTagDescription<string>[]
+            }>
+          >,
+        ) {
+          for (const { queryCacheKey, providedTags } of action.payload) {
+            removeCacheKeyFromTags(draft, queryCacheKey)
+
+            for (const { type, id } of providedTags) {
+              const subscribedQueries = ((draft.tags[type] ??= {})[
+                id || '__internal_without_id'
+              ] ??= [])
+              const alreadySubscribed =
+                subscribedQueries.includes(queryCacheKey)
+              if (!alreadySubscribed) {
+                subscribedQueries.push(queryCacheKey)
+              }
+            }
+
+            // Remove readonly from the providedTags array
+            draft.keys[queryCacheKey] =
+              providedTags as FullTagDescription<string>[]
+          }
+        },
+        prepare: prepareAutoBatched<
+          Array<{
+            queryCacheKey: QueryCacheKey
+            providedTags: readonly FullTagDescription<string>[]
+          }>
+        >(),
+      },
+    },
+    extraReducers(builder) {
+      builder
+        .addCase(
+          querySlice.actions.removeQueryResult,
+          (draft, { payload: { queryCacheKey } }) => {
+            removeCacheKeyFromTags(draft, queryCacheKey)
+          },
+        )
+        .addMatcher(hasRehydrationInfo, (draft, action) => {
+          const { provided } = extractRehydrationInfo(action)!
+          for (const [type, incomingTags] of Object.entries(
+            provided.tags ?? {},
+          )) {
+            for (const [id, cacheKeys] of Object.entries(incomingTags)) {
+              const subscribedQueries = ((draft.tags[type] ??= {})[
+                id || '__internal_without_id'
+              ] ??= [])
+              for (const queryCacheKey of cacheKeys) {
+                const alreadySubscribed =
+                  subscribedQueries.includes(queryCacheKey)
+                if (!alreadySubscribed) {
+                  subscribedQueries.push(queryCacheKey)
+                }
+                draft.keys[queryCacheKey] = provided.keys[queryCacheKey]
+              }
+            }
+          }
+        })
+        .addMatcher(
+          isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)),
+          (draft, action) => {
+            writeProvidedTagsForQueries(draft, [action])
+          },
+        )
+        .addMatcher(
+          querySlice.actions.cacheEntriesUpserted.match,
+          (draft, action) => {
+            const mockActions: CalculateProvidedByAction[] = action.payload.map(
+              ({ queryDescription, value }) => {
+                return {
+                  type: 'UNKNOWN',
+                  payload: value,
+                  meta: {
+                    requestStatus: 'fulfilled',
+                    requestId: 'UNKNOWN',
+                    arg: queryDescription,
+                  },
+                }
+              },
+            )
+            writeProvidedTagsForQueries(draft, mockActions)
+          },
+        )
+    },
+  })
+
+  function removeCacheKeyFromTags(
+    draft: InvalidationState<any>,
+    queryCacheKey: QueryCacheKey,
+  ) {
+    const existingTags = getCurrent(draft.keys[queryCacheKey] ?? [])
+
+    // Delete this cache key from any existing tags that may have provided it
+    for (const tag of existingTags) {
+      const tagType = tag.type
+      const tagId = tag.id ?? '__internal_without_id'
+      const tagSubscriptions = draft.tags[tagType]?.[tagId]
+
+      if (tagSubscriptions) {
+        draft.tags[tagType][tagId] = getCurrent(tagSubscriptions).filter(
+          (qc) => qc !== queryCacheKey,
+        )
+      }
+    }
+
+    delete draft.keys[queryCacheKey]
+  }
+
+  function writeProvidedTagsForQueries(
+    draft: InvalidationState<string>,
+    actions: CalculateProvidedByAction[],
+  ) {
+    const providedByEntries = actions.map((action) => {
+      const providedTags = calculateProvidedByThunk(
+        action,
+        'providesTags',
+        definitions,
+        assertTagType,
+      )
+      const { queryCacheKey } = action.meta.arg
+      return { queryCacheKey, providedTags }
+    })
+
+    invalidationSlice.caseReducers.updateProvidedBy(
+      draft,
+      invalidationSlice.actions.updateProvidedBy(providedByEntries),
+    )
+  }
+
+  // Dummy slice to generate actions
+  const subscriptionSlice = createSlice({
+    name: `${reducerPath}/subscriptions`,
+    initialState: initialState as SubscriptionState,
+    reducers: {
+      updateSubscriptionOptions(
+        d,
+        a: PayloadAction<
+          {
+            endpointName: string
+            requestId: string
+            options: Subscribers[number]
+          } & QuerySubstateIdentifier
+        >,
+      ) {
+        // Dummy
+      },
+      unsubscribeQueryResult(
+        d,
+        a: PayloadAction<{ requestId: string } & QuerySubstateIdentifier>,
+      ) {
+        // Dummy
+      },
+      internal_getRTKQSubscriptions() {},
+    },
+  })
+
+  const internalSubscriptionsSlice = createSlice({
+    name: `${reducerPath}/internalSubscriptions`,
+    initialState: initialState as SubscriptionState,
+    reducers: {
+      subscriptionsUpdated: {
+        reducer(state, action: PayloadAction<Patch[]>) {
+          return applyPatches(state, action.payload)
+        },
+        prepare: prepareAutoBatched<Patch[]>(),
+      },
+    },
+  })
+
+  const configSlice = createSlice({
+    name: `${reducerPath}/config`,
+    initialState: {
+      online: isOnline(),
+      focused: isDocumentVisible(),
+      middlewareRegistered: false,
+      ...config,
+    } as ConfigState<string>,
+    reducers: {
+      middlewareRegistered(state, { payload }: PayloadAction<string>) {
+        state.middlewareRegistered =
+          state.middlewareRegistered === 'conflict' || apiUid !== payload
+            ? 'conflict'
+            : true
+      },
+    },
+    extraReducers: (builder) => {
+      builder
+        .addCase(onOnline, (state) => {
+          state.online = true
+        })
+        .addCase(onOffline, (state) => {
+          state.online = false
+        })
+        .addCase(onFocus, (state) => {
+          state.focused = true
+        })
+        .addCase(onFocusLost, (state) => {
+          state.focused = false
+        })
+        // update the state to be a new object to be picked up as a "state change"
+        // by redux-persist's `autoMergeLevel2`
+        .addMatcher(hasRehydrationInfo, (draft) => ({ ...draft }))
+    },
+  })
+
+  const combinedReducer = combineReducers({
+    queries: querySlice.reducer,
+    mutations: mutationSlice.reducer,
+    provided: invalidationSlice.reducer,
+    subscriptions: internalSubscriptionsSlice.reducer,
+    config: configSlice.reducer,
+  })
+
+  const reducer: typeof combinedReducer = (state, action) =>
+    combinedReducer(resetApiState.match(action) ? undefined : state, action)
+
+  const actions = {
+    ...configSlice.actions,
+    ...querySlice.actions,
+    ...subscriptionSlice.actions,
+    ...internalSubscriptionsSlice.actions,
+    ...mutationSlice.actions,
+    ...invalidationSlice.actions,
+    resetApiState,
+  }
+
+  return { reducer, actions }
+}
+export type SliceActions = ReturnType<typeof buildSlice>['actions']
Index: node_modules/@reduxjs/toolkit/src/query/core/buildThunks.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/buildThunks.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/buildThunks.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1124 @@
+import type {
+  AsyncThunk,
+  AsyncThunkPayloadCreator,
+  Draft,
+  ThunkAction,
+  ThunkDispatch,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import type { Patch } from 'immer'
+import { isDraftable, produceWithPatches } from '../utils/immerImports'
+import type { Api, ApiContext } from '../apiTypes'
+import type {
+  BaseQueryError,
+  BaseQueryFn,
+  QueryReturnValue,
+} from '../baseQueryTypes'
+import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
+import type {
+  AssertTagTypes,
+  EndpointDefinition,
+  EndpointDefinitions,
+  InfiniteQueryArgFrom,
+  InfiniteQueryCombinedArg,
+  InfiniteQueryDefinition,
+  MutationDefinition,
+  PageParamFrom,
+  QueryArgFrom,
+  QueryDefinition,
+  ResultDescription,
+  ResultTypeFrom,
+  SchemaFailureConverter,
+  SchemaFailureHandler,
+  SchemaFailureInfo,
+  SchemaType,
+} from '../endpointDefinitions'
+import {
+  calculateProvidedBy,
+  ENDPOINT_QUERY,
+  isInfiniteQueryDefinition,
+  isQueryDefinition,
+} from '../endpointDefinitions'
+import { HandledError } from '../HandledError'
+import type { UnwrapPromise } from '../tsHelpers'
+import type {
+  RootState,
+  QueryKeys,
+  QuerySubstateIdentifier,
+  InfiniteData,
+  InfiniteQueryConfigOptions,
+  QueryCacheKey,
+  InfiniteQueryDirection,
+  InfiniteQueryKeys,
+} from './apiState'
+import { QueryStatus, STATUS_UNINITIALIZED } from './apiState'
+import type {
+  InfiniteQueryActionCreatorResult,
+  QueryActionCreatorResult,
+  StartInfiniteQueryActionCreatorOptions,
+  StartQueryActionCreatorOptions,
+} from './buildInitiate'
+import { forceQueryFnSymbol, isUpsertQuery } from './buildInitiate'
+import type { AllSelectors } from './buildSelectors'
+import type { ApiEndpointQuery, PrefetchOptions } from './module'
+import {
+  createAsyncThunk,
+  isAllOf,
+  isFulfilled,
+  isPending,
+  isRejected,
+  isRejectedWithValue,
+  SHOULD_AUTOBATCH,
+} from './rtkImports'
+import {
+  parseWithSchema,
+  NamedSchemaError,
+  shouldSkip,
+} from '../standardSchema'
+
+export type BuildThunksApiEndpointQuery<
+  Definition extends QueryDefinition<any, any, any, any, any>,
+> = Matchers<QueryThunk, Definition>
+
+export type BuildThunksApiEndpointInfiniteQuery<
+  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = Matchers<InfiniteQueryThunk<any>, Definition>
+
+export type BuildThunksApiEndpointMutation<
+  Definition extends MutationDefinition<any, any, any, any, any>,
+> = Matchers<MutationThunk, Definition>
+
+type EndpointThunk<
+  Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>,
+  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 & { originalArgs: QueryArg },
+          ATConfig & { rejectValue: BaseQueryError<BaseQueryFn> }
+        >
+      : never
+    : Definition extends InfiniteQueryDefinition<
+          infer QueryArg,
+          infer PageParam,
+          infer BaseQueryFn,
+          any,
+          infer ResultType
+        >
+      ? Thunk extends AsyncThunk<unknown, infer ATArg, infer ATConfig>
+        ? AsyncThunk<
+            InfiniteData<ResultType, PageParam>,
+            ATArg & { originalArgs: QueryArg },
+            ATConfig & { rejectValue: BaseQueryError<BaseQueryFn> }
+          >
+        : never
+      : never
+
+export type PendingAction<
+  Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>,
+  Definition extends EndpointDefinition<any, any, any, any>,
+> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>
+
+export type FulfilledAction<
+  Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>,
+  Definition extends EndpointDefinition<any, any, any, any>,
+> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>
+
+export type RejectedAction<
+  Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>,
+  Definition extends EndpointDefinition<any, any, any, any>,
+> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>
+
+export type Matcher<M> = (value: any) => value is M
+
+export interface Matchers<
+  Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>,
+  Definition extends EndpointDefinition<any, any, any, any>,
+> {
+  matchPending: Matcher<PendingAction<Thunk, Definition>>
+  matchFulfilled: Matcher<FulfilledAction<Thunk, Definition>>
+  matchRejected: Matcher<RejectedAction<Thunk, Definition>>
+}
+
+export type QueryThunkArg = QuerySubstateIdentifier &
+  StartQueryActionCreatorOptions & {
+    type: 'query'
+    originalArgs: unknown
+    endpointName: string
+  }
+
+export type InfiniteQueryThunkArg<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = QuerySubstateIdentifier &
+  StartInfiniteQueryActionCreatorOptions<D> & {
+    type: `query`
+    originalArgs: unknown
+    endpointName: string
+    param: unknown
+    direction?: InfiniteQueryDirection
+    refetchCachedPages?: boolean
+  }
+
+type MutationThunkArg = {
+  type: 'mutation'
+  originalArgs: unknown
+  endpointName: string
+  track?: boolean
+  fixedCacheKey?: string
+}
+
+export type ThunkResult = unknown
+
+export type ThunkApiMetaConfig = {
+  pendingMeta: { startedTimeStamp: number; [SHOULD_AUTOBATCH]: true }
+  fulfilledMeta: {
+    fulfilledTimeStamp: number
+    baseQueryMeta: unknown
+    [SHOULD_AUTOBATCH]: true
+  }
+  rejectedMeta: { baseQueryMeta: unknown; [SHOULD_AUTOBATCH]: true }
+}
+export type QueryThunk = AsyncThunk<
+  ThunkResult,
+  QueryThunkArg,
+  ThunkApiMetaConfig
+>
+export type InfiniteQueryThunk<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = AsyncThunk<ThunkResult, InfiniteQueryThunkArg<D>, ThunkApiMetaConfig>
+export type MutationThunk = AsyncThunk<
+  ThunkResult,
+  MutationThunkArg,
+  ThunkApiMetaConfig
+>
+
+function defaultTransformResponse(baseQueryReturnValue: unknown) {
+  return baseQueryReturnValue
+}
+
+export type MaybeDrafted<T> = T | Draft<T>
+export type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>
+export type UpsertRecipe<T> = (
+  data: MaybeDrafted<T> | undefined,
+) => void | MaybeDrafted<T>
+
+export 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>
+
+export type AllQueryKeys<Definitions extends EndpointDefinitions> =
+  | QueryKeys<Definitions>
+  | InfiniteQueryKeys<Definitions>
+
+export 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
+
+export 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
+
+export 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>
+
+export 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>
+
+export 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
+>
+
+/**
+ * An object returned from dispatching a `api.util.updateQueryData` call.
+ */
+export type PatchCollection = {
+  /**
+   * An `immer` Patch describing the cache update.
+   */
+  patches: Patch[]
+  /**
+   * An `immer` Patch to revert the cache update.
+   */
+  inversePatches: Patch[]
+  /**
+   * A function that will undo the cache update.
+   */
+  undo: () => void
+}
+
+type TransformCallback = (
+  baseQueryReturnValue: unknown,
+  meta: unknown,
+  arg: unknown,
+) => any
+
+export const addShouldAutoBatch = <T extends Record<string, any>>(
+  arg: T = {} as T,
+): T & { [SHOULD_AUTOBATCH]: true } => {
+  return { ...arg, [SHOULD_AUTOBATCH]: true }
+}
+
+export function buildThunks<
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string,
+  Definitions extends EndpointDefinitions,
+>({
+  reducerPath,
+  baseQuery,
+  context: { endpointDefinitions },
+  serializeQueryArgs,
+  api,
+  assertTagType,
+  selectors,
+  onSchemaFailure,
+  catchSchemaFailure: globalCatchSchemaFailure,
+  skipSchemaValidation: globalSkipSchemaValidation,
+}: {
+  baseQuery: BaseQuery
+  reducerPath: ReducerPath
+  context: ApiContext<Definitions>
+  serializeQueryArgs: InternalSerializeQueryArgs
+  api: Api<BaseQuery, Definitions, ReducerPath, any>
+  assertTagType: AssertTagTypes
+  selectors: AllSelectors
+  onSchemaFailure: SchemaFailureHandler | undefined
+  catchSchemaFailure: SchemaFailureConverter<BaseQuery> | undefined
+  skipSchemaValidation: boolean | SchemaType[] | undefined
+}) {
+  type State = RootState<any, string, ReducerPath>
+
+  const patchQueryData: PatchQueryDataThunk<EndpointDefinitions, State> =
+    (endpointName, arg, patches, updateProvided) => (dispatch, getState) => {
+      const endpointDefinition = endpointDefinitions[endpointName]
+
+      const queryCacheKey = serializeQueryArgs({
+        queryArgs: arg,
+        endpointDefinition,
+        endpointName,
+      })
+
+      dispatch(
+        api.internalActions.queryResultPatched({ queryCacheKey, patches }),
+      )
+
+      if (!updateProvided) {
+        return
+      }
+
+      const newValue = api.endpoints[endpointName].select(arg)(
+        // Work around TS 4.1 mismatch
+        getState() as RootState<any, any, any>,
+      )
+
+      const providedTags = calculateProvidedBy(
+        endpointDefinition.providesTags,
+        newValue.data,
+        undefined,
+        arg,
+        {},
+        assertTagType,
+      )
+
+      dispatch(
+        api.internalActions.updateProvidedBy([{ queryCacheKey, providedTags }]),
+      )
+    }
+
+  function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {
+    const newItems = [item, ...items]
+    return max && newItems.length > max ? newItems.slice(0, -1) : newItems
+  }
+
+  function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {
+    const newItems = [...items, item]
+    return max && newItems.length > max ? newItems.slice(1) : newItems
+  }
+
+  const updateQueryData: UpdateQueryDataThunk<EndpointDefinitions, State> =
+    (endpointName, arg, updateRecipe, updateProvided = true) =>
+    (dispatch, getState) => {
+      const endpointDefinition = api.endpoints[endpointName]
+
+      const currentState = endpointDefinition.select(arg)(
+        // Work around TS 4.1 mismatch
+        getState() as RootState<any, any, any>,
+      )
+
+      const ret: PatchCollection = {
+        patches: [],
+        inversePatches: [],
+        undo: () =>
+          dispatch(
+            api.util.patchQueryData(
+              endpointName,
+              arg,
+              ret.inversePatches,
+              updateProvided,
+            ),
+          ),
+      }
+      if (currentState.status === STATUS_UNINITIALIZED) {
+        return ret
+      }
+      let newValue
+      if ('data' in currentState) {
+        if (isDraftable(currentState.data)) {
+          const [value, patches, inversePatches] = produceWithPatches(
+            currentState.data,
+            updateRecipe,
+          )
+          ret.patches.push(...patches)
+          ret.inversePatches.push(...inversePatches)
+          newValue = value
+        } else {
+          newValue = updateRecipe(currentState.data)
+          ret.patches.push({ op: 'replace', path: [], value: newValue })
+          ret.inversePatches.push({
+            op: 'replace',
+            path: [],
+            value: currentState.data,
+          })
+        }
+      }
+
+      if (ret.patches.length === 0) {
+        return ret
+      }
+
+      dispatch(
+        api.util.patchQueryData(endpointName, arg, ret.patches, updateProvided),
+      )
+
+      return ret
+    }
+
+  const upsertQueryData: UpsertQueryDataThunk<Definitions, State> =
+    (endpointName, arg, value) => (dispatch) => {
+      type EndpointName = typeof endpointName
+      const res = dispatch(
+        (
+          api.endpoints[endpointName] as ApiEndpointQuery<
+            QueryDefinition<any, any, any, any, any>,
+            Definitions
+          >
+        ).initiate(arg, {
+          subscribe: false,
+          forceRefetch: true,
+          [forceQueryFnSymbol]: () => ({ data: value }),
+        }),
+      ) as UpsertThunkResult<Definitions, EndpointName>
+
+      return res
+    }
+
+  const getTransformCallbackForEndpoint = (
+    endpointDefinition: EndpointDefinition<any, any, any, any>,
+    transformFieldName: 'transformResponse' | 'transformErrorResponse',
+  ): TransformCallback => {
+    return endpointDefinition.query && endpointDefinition[transformFieldName]
+      ? (endpointDefinition[transformFieldName]! as TransformCallback)
+      : defaultTransformResponse
+  }
+
+  // The generic async payload function for all of our thunks
+  const executeEndpoint: AsyncThunkPayloadCreator<
+    ThunkResult,
+    QueryThunkArg | MutationThunkArg | InfiniteQueryThunkArg<any>,
+    ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }
+  > = async (
+    arg,
+    {
+      signal,
+      abort,
+      rejectWithValue,
+      fulfillWithValue,
+      dispatch,
+      getState,
+      extra,
+    },
+  ) => {
+    const endpointDefinition = endpointDefinitions[arg.endpointName]
+    const { metaSchema, skipSchemaValidation = globalSkipSchemaValidation } =
+      endpointDefinition
+
+    const isQuery = arg.type === ENDPOINT_QUERY
+
+    try {
+      let transformResponse: TransformCallback = defaultTransformResponse
+
+      const baseQueryApi = {
+        signal,
+        abort,
+        dispatch,
+        getState,
+        extra,
+        endpoint: arg.endpointName,
+        type: arg.type,
+        forced: isQuery ? isForcedQuery(arg, getState()) : undefined,
+        queryCacheKey: isQuery ? arg.queryCacheKey : undefined,
+      }
+
+      const forceQueryFn = isQuery ? arg[forceQueryFnSymbol] : undefined
+
+      let finalQueryReturnValue: QueryReturnValue
+
+      // Infinite query wrapper, which executes the request and returns
+      // the InfiniteData `{pages, pageParams}` structure
+      const fetchPage = async (
+        data: InfiniteData<unknown, unknown>,
+        param: unknown,
+        maxPages: number,
+        previous?: boolean,
+      ): Promise<QueryReturnValue> => {
+        // This should handle cases where there is no `getPrevPageParam`,
+        // or `getPPP` returned nullish
+        if (param == null && data.pages.length) {
+          return Promise.resolve({ data })
+        }
+
+        const finalQueryArg: InfiniteQueryCombinedArg<any, any> = {
+          queryArg: arg.originalArgs,
+          pageParam: param,
+        }
+
+        const pageResponse = await executeRequest(finalQueryArg)
+
+        const addTo = previous ? addToStart : addToEnd
+
+        return {
+          data: {
+            pages: addTo(data.pages, pageResponse.data, maxPages),
+            pageParams: addTo(data.pageParams, param, maxPages),
+          },
+          meta: pageResponse.meta,
+        }
+      }
+
+      // Wrapper for executing either `query` or `queryFn`,
+      // and handling any errors
+      async function executeRequest(
+        finalQueryArg: unknown,
+      ): Promise<QueryReturnValue> {
+        let result: QueryReturnValue
+        const { extraOptions, argSchema, rawResponseSchema, responseSchema } =
+          endpointDefinition
+
+        if (argSchema && !shouldSkip(skipSchemaValidation, 'arg')) {
+          finalQueryArg = await parseWithSchema(
+            argSchema,
+            finalQueryArg,
+            'argSchema',
+            {}, // we don't have a meta yet, so we can't pass it
+          )
+        }
+
+        if (forceQueryFn) {
+          // upsertQueryData relies on this to pass in the user-provided value
+          result = forceQueryFn()
+        } else if (endpointDefinition.query) {
+          // We should only run `transformResponse` when the endpoint has a `query` method,
+          // and we're not doing an `upsertQueryData`.
+          transformResponse = getTransformCallbackForEndpoint(
+            endpointDefinition,
+            'transformResponse',
+          )
+
+          result = await baseQuery(
+            endpointDefinition.query(finalQueryArg as any),
+            baseQueryApi,
+            extraOptions as any,
+          )
+        } else {
+          result = await endpointDefinition.queryFn(
+            finalQueryArg as any,
+            baseQueryApi,
+            extraOptions as any,
+            (arg) => baseQuery(arg, baseQueryApi, extraOptions as any),
+          )
+        }
+
+        if (
+          typeof process !== 'undefined' &&
+          process.env.NODE_ENV === 'development'
+        ) {
+          const what = endpointDefinition.query ? '`baseQuery`' : '`queryFn`'
+          let err: undefined | string
+          if (!result) {
+            err = `${what} did not return anything.`
+          } else if (typeof result !== 'object') {
+            err = `${what} did not return an object.`
+          } else if (result.error && result.data) {
+            err = `${what} returned an object containing both \`error\` and \`result\`.`
+          } else if (result.error === undefined && result.data === undefined) {
+            err = `${what} returned an object containing neither a valid \`error\` and \`result\`. At least one of them should not be \`undefined\``
+          } else {
+            for (const key of Object.keys(result)) {
+              if (key !== 'error' && key !== 'data' && key !== 'meta') {
+                err = `The object returned by ${what} has the unknown property ${key}.`
+                break
+              }
+            }
+          }
+          if (err) {
+            console.error(
+              `Error encountered handling the endpoint ${arg.endpointName}.
+                  ${err}
+                  It needs to return an object with either the shape \`{ data: <value> }\` or \`{ error: <value> }\` that may contain an optional \`meta\` property.
+                  Object returned was:`,
+              result,
+            )
+          }
+        }
+
+        if (result.error) throw new HandledError(result.error, result.meta)
+
+        let { data } = result
+
+        if (
+          rawResponseSchema &&
+          !shouldSkip(skipSchemaValidation, 'rawResponse')
+        ) {
+          data = await parseWithSchema(
+            rawResponseSchema,
+            result.data,
+            'rawResponseSchema',
+            result.meta,
+          )
+        }
+
+        let transformedResponse = await transformResponse(
+          data,
+          result.meta,
+          finalQueryArg,
+        )
+
+        if (responseSchema && !shouldSkip(skipSchemaValidation, 'response')) {
+          transformedResponse = await parseWithSchema(
+            responseSchema,
+            transformedResponse,
+            'responseSchema',
+            result.meta,
+          )
+        }
+
+        return {
+          ...result,
+          data: transformedResponse,
+        }
+      }
+
+      if (isQuery && 'infiniteQueryOptions' in endpointDefinition) {
+        // This is an infinite query endpoint
+        const { infiniteQueryOptions } = endpointDefinition
+
+        // Runtime checks should guarantee this is a positive number if provided
+        const { maxPages = Infinity } = infiniteQueryOptions
+
+        // Priority: per-call override > endpoint config > default (true)
+        const refetchCachedPages =
+          (arg as InfiniteQueryThunkArg<any>).refetchCachedPages ??
+          infiniteQueryOptions.refetchCachedPages ??
+          true
+
+        let result: QueryReturnValue
+
+        // Start by looking up the existing InfiniteData value from state,
+        // falling back to an empty value if it doesn't exist yet
+        const blankData = { pages: [], pageParams: [] }
+        const cachedData = selectors.selectQueryEntry(
+          getState(),
+          arg.queryCacheKey,
+        )?.data as InfiniteData<unknown, unknown> | undefined
+
+        // When the arg changes or the user forces a refetch,
+        // we don't include the `direction` flag. This lets us distinguish
+        // between actually refetching with a forced query, vs just fetching
+        // the next page.
+        const isForcedQueryNeedingRefetch = // arg.forceRefetch
+          isForcedQuery(arg, getState()) &&
+          !(arg as InfiniteQueryThunkArg<any>).direction
+        const existingData = (
+          isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData
+        ) as InfiniteData<unknown, unknown>
+
+        // If the thunk specified a direction and we do have at least one page,
+        // fetch the next or previous page
+        if ('direction' in arg && arg.direction && existingData.pages.length) {
+          const previous = arg.direction === 'backward'
+          const pageParamFn = previous ? getPreviousPageParam : getNextPageParam
+          const param = pageParamFn(
+            infiniteQueryOptions,
+            existingData,
+            arg.originalArgs,
+          )
+
+          result = await fetchPage(existingData, param, maxPages, previous)
+        } else {
+          // Otherwise, fetch the first page and then any remaining pages
+
+          const { initialPageParam = infiniteQueryOptions.initialPageParam } =
+            arg as InfiniteQueryThunkArg<any>
+
+          // If we're doing a refetch, we should start from
+          // the first page we have cached.
+          // Otherwise, we should start from the initialPageParam
+          const cachedPageParams = cachedData?.pageParams ?? []
+          const firstPageParam = cachedPageParams[0] ?? initialPageParam
+          const totalPages = cachedPageParams.length
+
+          // Fetch first page
+          result = await fetchPage(existingData, firstPageParam, maxPages)
+
+          if (forceQueryFn) {
+            // HACK `upsertQueryData` expects the user to pass in the `{pages, pageParams}` structure,
+            // but `fetchPage` treats that as `pages[0]`. We have to manually un-nest it.
+            result = {
+              data: (result.data as InfiniteData<unknown, unknown>).pages[0],
+            } as QueryReturnValue
+          }
+
+          if (refetchCachedPages) {
+            // Fetch remaining pages
+            for (let i = 1; i < totalPages; i++) {
+              const param = getNextPageParam(
+                infiniteQueryOptions,
+                result.data as InfiniteData<unknown, unknown>,
+                arg.originalArgs,
+              )
+              result = await fetchPage(
+                result.data as InfiniteData<unknown, unknown>,
+                param,
+                maxPages,
+              )
+            }
+          }
+        }
+
+        finalQueryReturnValue = result
+      } else {
+        // Non-infinite endpoint. Just run the one request.
+        finalQueryReturnValue = await executeRequest(arg.originalArgs)
+      }
+
+      if (
+        metaSchema &&
+        !shouldSkip(skipSchemaValidation, 'meta') &&
+        finalQueryReturnValue.meta
+      ) {
+        finalQueryReturnValue.meta = await parseWithSchema(
+          metaSchema,
+          finalQueryReturnValue.meta,
+          'metaSchema',
+          finalQueryReturnValue.meta,
+        )
+      }
+
+      // console.log('Final result: ', transformedData)
+      return fulfillWithValue(
+        finalQueryReturnValue.data,
+        addShouldAutoBatch({
+          fulfilledTimeStamp: Date.now(),
+          baseQueryMeta: finalQueryReturnValue.meta,
+        }),
+      )
+    } catch (error) {
+      let caughtError = error
+      if (caughtError instanceof HandledError) {
+        let transformErrorResponse = getTransformCallbackForEndpoint(
+          endpointDefinition,
+          'transformErrorResponse',
+        )
+        const { rawErrorResponseSchema, errorResponseSchema } =
+          endpointDefinition
+
+        let { value, meta } = caughtError
+
+        try {
+          if (
+            rawErrorResponseSchema &&
+            !shouldSkip(skipSchemaValidation, 'rawErrorResponse')
+          ) {
+            value = await parseWithSchema(
+              rawErrorResponseSchema,
+              value,
+              'rawErrorResponseSchema',
+              meta,
+            )
+          }
+
+          if (metaSchema && !shouldSkip(skipSchemaValidation, 'meta')) {
+            meta = await parseWithSchema(metaSchema, meta, 'metaSchema', meta)
+          }
+          let transformedErrorResponse = await transformErrorResponse(
+            value,
+            meta,
+            arg.originalArgs,
+          )
+          if (
+            errorResponseSchema &&
+            !shouldSkip(skipSchemaValidation, 'errorResponse')
+          ) {
+            transformedErrorResponse = await parseWithSchema(
+              errorResponseSchema,
+              transformedErrorResponse,
+              'errorResponseSchema',
+              meta,
+            )
+          }
+
+          return rejectWithValue(
+            transformedErrorResponse,
+            addShouldAutoBatch({ baseQueryMeta: meta }),
+          )
+        } catch (e) {
+          caughtError = e
+        }
+      }
+      try {
+        if (caughtError instanceof NamedSchemaError) {
+          const info: SchemaFailureInfo = {
+            endpoint: arg.endpointName,
+            arg: arg.originalArgs,
+            type: arg.type,
+            queryCacheKey: isQuery ? arg.queryCacheKey : undefined,
+          }
+          endpointDefinition.onSchemaFailure?.(caughtError, info)
+          onSchemaFailure?.(caughtError, info)
+          const { catchSchemaFailure = globalCatchSchemaFailure } =
+            endpointDefinition
+          if (catchSchemaFailure) {
+            return rejectWithValue(
+              catchSchemaFailure(caughtError, info),
+              addShouldAutoBatch({ baseQueryMeta: caughtError._bqMeta }),
+            )
+          }
+        }
+      } catch (e) {
+        caughtError = e
+      }
+      if (
+        typeof process !== 'undefined' &&
+        process.env.NODE_ENV !== 'production'
+      ) {
+        console.error(
+          `An unhandled error occurred processing a request for the endpoint "${arg.endpointName}".
+In the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+          caughtError,
+        )
+      } else {
+        console.error(caughtError)
+      }
+      throw caughtError
+    }
+  }
+
+  function isForcedQuery(
+    arg: QueryThunkArg,
+    state: RootState<any, string, ReducerPath>,
+  ) {
+    const requestState = selectors.selectQueryEntry(state, arg.queryCacheKey)
+    const baseFetchOnMountOrArgChange =
+      selectors.selectConfig(state).refetchOnMountOrArgChange
+
+    const fulfilledVal = requestState?.fulfilledTimeStamp
+    const refetchVal =
+      arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange)
+
+    if (refetchVal) {
+      // Return if it's true or compare the dates because it must be a number
+      return (
+        refetchVal === true ||
+        (Number(new Date()) - Number(fulfilledVal)) / 1000 >= refetchVal
+      )
+    }
+    return false
+  }
+
+  const createQueryThunk = <
+    ThunkArgType extends QueryThunkArg | InfiniteQueryThunkArg<any>,
+  >() => {
+    const generatedQueryThunk = createAsyncThunk<
+      ThunkResult,
+      ThunkArgType,
+      ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }
+    >(`${reducerPath}/executeQuery`, executeEndpoint, {
+      getPendingMeta({ arg }) {
+        const endpointDefinition = endpointDefinitions[arg.endpointName]
+        return addShouldAutoBatch({
+          startedTimeStamp: Date.now(),
+          ...(isInfiniteQueryDefinition(endpointDefinition)
+            ? { direction: (arg as InfiniteQueryThunkArg<any>).direction }
+            : {}),
+        })
+      },
+      condition(queryThunkArg, { getState }) {
+        const state = getState()
+
+        const requestState = selectors.selectQueryEntry(
+          state,
+          queryThunkArg.queryCacheKey,
+        )
+        const fulfilledVal = requestState?.fulfilledTimeStamp
+        const currentArg = queryThunkArg.originalArgs
+        const previousArg = requestState?.originalArgs
+        const endpointDefinition =
+          endpointDefinitions[queryThunkArg.endpointName]
+        const direction = (queryThunkArg as InfiniteQueryThunkArg<any>)
+          .direction
+
+        // Order of these checks matters.
+        // In order for `upsertQueryData` to successfully run while an existing request is in flight,
+        /// we have to check for that first, otherwise `queryThunk` will bail out and not run at all.
+        if (isUpsertQuery(queryThunkArg)) {
+          return true
+        }
+
+        // Don't retry a request that's currently in-flight
+        if (requestState?.status === 'pending') {
+          return false
+        }
+
+        // if this is forced, continue
+        if (isForcedQuery(queryThunkArg, state)) {
+          return true
+        }
+
+        if (
+          isQueryDefinition(endpointDefinition) &&
+          endpointDefinition?.forceRefetch?.({
+            currentArg,
+            previousArg,
+            endpointState: requestState,
+            state,
+          })
+        ) {
+          return true
+        }
+
+        // Pull from the cache unless we explicitly force refetch or qualify based on time
+        if (fulfilledVal && !direction) {
+          // Value is cached and we didn't specify to refresh, skip it.
+          return false
+        }
+
+        return true
+      },
+      dispatchConditionRejection: true,
+    })
+    return generatedQueryThunk
+  }
+
+  const queryThunk = createQueryThunk<QueryThunkArg>()
+  const infiniteQueryThunk = createQueryThunk<InfiniteQueryThunkArg<any>>()
+
+  const mutationThunk = createAsyncThunk<
+    ThunkResult,
+    MutationThunkArg,
+    ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }
+  >(`${reducerPath}/executeMutation`, executeEndpoint, {
+    getPendingMeta() {
+      return addShouldAutoBatch({ startedTimeStamp: Date.now() })
+    },
+  })
+
+  const hasTheForce = (options: any): options is { force: boolean } =>
+    'force' in options
+  const hasMaxAge = (
+    options: any,
+  ): options is { ifOlderThan: false | number } => 'ifOlderThan' in options
+
+  const prefetch =
+    <EndpointName extends QueryKeys<Definitions>>(
+      endpointName: EndpointName,
+      arg: any,
+      options: PrefetchOptions = {},
+    ): ThunkAction<void, any, any, UnknownAction> =>
+    (dispatch: ThunkDispatch<any, any, any>, getState: () => any) => {
+      const force = hasTheForce(options) && options.force
+      const maxAge = hasMaxAge(options) && options.ifOlderThan
+
+      const queryAction = (force: boolean = true) => {
+        const options: StartQueryActionCreatorOptions = {
+          forceRefetch: force,
+          subscribe: false,
+        }
+        return (
+          api.endpoints[endpointName] as ApiEndpointQuery<any, any>
+        ).initiate(arg, options)
+      }
+      const latestStateValue = (
+        api.endpoints[endpointName] as ApiEndpointQuery<any, any>
+      ).select(arg)(getState())
+
+      if (force) {
+        dispatch(queryAction())
+      } else if (maxAge) {
+        const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp
+        if (!lastFulfilledTs) {
+          dispatch(queryAction())
+          return
+        }
+        const shouldRetrigger =
+          (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1000 >=
+          maxAge
+        if (shouldRetrigger) {
+          dispatch(queryAction())
+        }
+      } else {
+        // If prefetching with no options, just let it try
+        dispatch(queryAction(false))
+      }
+    }
+
+  function matchesEndpoint(endpointName: string) {
+    return (action: any): action is UnknownAction =>
+      action?.meta?.arg?.endpointName === endpointName
+  }
+
+  function buildMatchThunkActions<
+    Thunk extends
+      | AsyncThunk<any, QueryThunkArg, ThunkApiMetaConfig>
+      | AsyncThunk<any, MutationThunkArg, ThunkApiMetaConfig>,
+  >(thunk: Thunk, endpointName: string) {
+    return {
+      matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),
+      matchFulfilled: isAllOf(
+        isFulfilled(thunk),
+        matchesEndpoint(endpointName),
+      ),
+      matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName)),
+    } as Matchers<Thunk, any>
+  }
+
+  return {
+    queryThunk,
+    mutationThunk,
+    infiniteQueryThunk,
+    prefetch,
+    updateQueryData,
+    upsertQueryData,
+    patchQueryData,
+    buildMatchThunkActions,
+  }
+}
+
+export function getNextPageParam(
+  options: InfiniteQueryConfigOptions<unknown, unknown, unknown>,
+  { pages, pageParams }: InfiniteData<unknown, unknown>,
+  queryArg: unknown,
+): unknown | undefined {
+  const lastIndex = pages.length - 1
+  return options.getNextPageParam(
+    pages[lastIndex],
+    pages,
+    pageParams[lastIndex],
+    pageParams,
+    queryArg,
+  )
+}
+
+export function getPreviousPageParam(
+  options: InfiniteQueryConfigOptions<unknown, unknown, unknown>,
+  { pages, pageParams }: InfiniteData<unknown, unknown>,
+  queryArg: unknown,
+): unknown | undefined {
+  return options.getPreviousPageParam?.(
+    pages[0],
+    pages,
+    pageParams[0],
+    pageParams,
+    queryArg,
+  )
+}
+
+export function calculateProvidedByThunk(
+  action: UnwrapPromise<
+    | ReturnType<ReturnType<QueryThunk>>
+    | ReturnType<ReturnType<MutationThunk>>
+    | ReturnType<ReturnType<InfiniteQueryThunk<any>>>
+  >,
+  type: 'providesTags' | 'invalidatesTags',
+  endpointDefinitions: EndpointDefinitions,
+  assertTagType: AssertTagTypes,
+) {
+  return calculateProvidedBy(
+    endpointDefinitions[action.meta.arg.endpointName][
+      type
+    ] as ResultDescription<any, any, any, any, any>,
+    isFulfilled(action) ? action.payload : undefined,
+    isRejectedWithValue(action) ? action.payload : undefined,
+    action.meta.arg.originalArgs,
+    'baseQueryMeta' in action.meta ? action.meta.baseQueryMeta : undefined,
+    assertTagType,
+  )
+}
Index: node_modules/@reduxjs/toolkit/src/query/core/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,58 @@
+import { buildCreateApi } from '../createApi'
+import { coreModule } from './module'
+
+export const createApi = /* @__PURE__ */ buildCreateApi(coreModule())
+
+export { QueryStatus } from './apiState'
+export type {
+  CombinedState,
+  InfiniteData,
+  InfiniteQueryConfigOptions,
+  InfiniteQuerySubState,
+  MutationKeys,
+  QueryCacheKey,
+  QueryKeys,
+  QuerySubState,
+  RootState,
+  SubscriptionOptions,
+} from './apiState'
+export type {
+  InfiniteQueryActionCreatorResult,
+  MutationActionCreatorResult,
+  QueryActionCreatorResult,
+  StartQueryActionCreatorOptions,
+} from './buildInitiate'
+export type {
+  MutationCacheLifecycleApi,
+  MutationLifecycleApi,
+  QueryCacheLifecycleApi,
+  QueryLifecycleApi,
+  SubscriptionSelectors,
+  TypedMutationOnQueryStarted,
+  TypedQueryOnQueryStarted,
+} from './buildMiddleware/index'
+export { skipToken } from './buildSelectors'
+export type {
+  InfiniteQueryResultSelectorResult,
+  MutationResultSelectorResult,
+  QueryResultSelectorResult,
+  SkipToken,
+} from './buildSelectors'
+export type { SliceActions } from './buildSlice'
+export type {
+  PatchQueryDataThunk,
+  UpdateQueryDataThunk,
+  UpsertQueryDataThunk,
+} from './buildThunks'
+export { coreModuleName } from './module'
+export type {
+  ApiEndpointInfiniteQuery,
+  ApiEndpointMutation,
+  ApiEndpointQuery,
+  CoreModule,
+  InternalActions,
+  PrefetchOptions,
+  ThunkWithReturnValue,
+} from './module'
+export { setupListeners } from './setupListeners'
+export { buildCreateApi, coreModule }
Index: node_modules/@reduxjs/toolkit/src/query/core/module.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/module.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/module.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,727 @@
+/**
+ * Note: this file should import all other files for type discovery and declaration merging
+ */
+import type {
+  ActionCreatorWithPayload,
+  Dispatch,
+  Middleware,
+  Reducer,
+  ThunkAction,
+  ThunkDispatch,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import { enablePatches } from '../utils/immerImports'
+import type { Api, Module } from '../apiTypes'
+import type { BaseQueryFn } from '../baseQueryTypes'
+import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'
+import type {
+  AssertTagTypes,
+  EndpointDefinitions,
+  InfiniteQueryDefinition,
+  MutationDefinition,
+  QueryArgFrom,
+  QueryArgFromAnyQuery,
+  QueryDefinition,
+  TagDescription,
+} from '../endpointDefinitions'
+import {
+  isInfiniteQueryDefinition,
+  isMutationDefinition,
+  isQueryDefinition,
+} from '../endpointDefinitions'
+import { assertCast, safeAssign } from '../tsHelpers'
+import type {
+  CombinedState,
+  MutationKeys,
+  QueryKeys,
+  RootState,
+} from './apiState'
+import type {
+  BuildInitiateApiEndpointMutation,
+  BuildInitiateApiEndpointQuery,
+  MutationActionCreatorResult,
+  QueryActionCreatorResult,
+  InfiniteQueryActionCreatorResult,
+  BuildInitiateApiEndpointInfiniteQuery,
+} from './buildInitiate'
+import { buildInitiate } from './buildInitiate'
+import type {
+  ReferenceCacheCollection,
+  ReferenceCacheLifecycle,
+  ReferenceQueryLifecycle,
+} from './buildMiddleware'
+import { buildMiddleware } from './buildMiddleware'
+import type {
+  BuildSelectorsApiEndpointInfiniteQuery,
+  BuildSelectorsApiEndpointMutation,
+  BuildSelectorsApiEndpointQuery,
+} from './buildSelectors'
+import { buildSelectors } from './buildSelectors'
+import type { SliceActions, UpsertEntries } from './buildSlice'
+import { buildSlice } from './buildSlice'
+import type {
+  AllQueryKeys,
+  BuildThunksApiEndpointInfiniteQuery,
+  BuildThunksApiEndpointMutation,
+  BuildThunksApiEndpointQuery,
+  PatchQueryDataThunk,
+  QueryArgFromAnyQueryDefinition,
+  UpdateQueryDataThunk,
+  UpsertQueryDataThunk,
+} from './buildThunks'
+import { buildThunks } from './buildThunks'
+import { createSelector as _createSelector } from './rtkImports'
+import { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners'
+import type { InternalMiddlewareState } from './buildMiddleware/types'
+import { getOrInsertComputed } from '../utils'
+import type { CreateSelectorFunction } from 'reselect'
+
+/**
+ * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_
+ * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value
+ *
+ * @overloadSummary
+ * `force`
+ * - 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.
+ */
+export type PrefetchOptions =
+  | {
+      ifOlderThan?: false | number
+    }
+  | { force?: boolean }
+
+export const coreModuleName = /* @__PURE__ */ Symbol()
+export type CoreModule =
+  | typeof coreModuleName
+  | ReferenceCacheLifecycle
+  | ReferenceQueryLifecycle
+  | ReferenceCacheCollection
+
+export type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>
+
+export interface ApiModules<
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  BaseQuery extends BaseQueryFn,
+  Definitions extends EndpointDefinitions,
+  ReducerPath extends string,
+  TagTypes extends string,
+> {
+  [coreModuleName]: {
+    /**
+     * This api's reducer should be mounted at `store[api.reducerPath]`.
+     *
+     * @example
+     * ```ts
+     * configureStore({
+     *   reducer: {
+     *     [api.reducerPath]: api.reducer,
+     *   },
+     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
+     * })
+     * ```
+     */
+    reducerPath: ReducerPath
+    /**
+     * Internal actions not part of the public API. Note: These are subject to change at any given time.
+     */
+    internalActions: InternalActions
+    /**
+     *  A standard redux reducer that enables core functionality. Make sure it's included in your store.
+     *
+     * @example
+     * ```ts
+     * configureStore({
+     *   reducer: {
+     *     [api.reducerPath]: api.reducer,
+     *   },
+     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
+     * })
+     * ```
+     */
+    reducer: Reducer<
+      CombinedState<Definitions, TagTypes, ReducerPath>,
+      UnknownAction
+    >
+    /**
+     * 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.
+     *
+     * @example
+     * ```ts
+     * configureStore({
+     *   reducer: {
+     *     [api.reducerPath]: api.reducer,
+     *   },
+     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
+     * })
+     * ```
+     */
+    middleware: Middleware<
+      {},
+      RootState<Definitions, string, ReducerPath>,
+      ThunkDispatch<any, any, UnknownAction>
+    >
+    /**
+     * A collection of utility thunks for various situations.
+     */
+    util: {
+      /**
+       * A thunk that (if dispatched) will return a specific running query, identified
+       * by `endpointName` and `arg`.
+       * If that query is not running, dispatching the thunk will result in `undefined`.
+       *
+       * Can be used to await a specific query triggered in any way,
+       * including via hook calls or manually dispatching `initiate` actions.
+       *
+       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
+       */
+      getRunningQueryThunk<EndpointName extends AllQueryKeys<Definitions>>(
+        endpointName: EndpointName,
+        arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>,
+      ): ThunkWithReturnValue<
+        | QueryActionCreatorResult<
+            Definitions[EndpointName] & { type: 'query' }
+          >
+        | InfiniteQueryActionCreatorResult<
+            Definitions[EndpointName] & { type: 'infinitequery' }
+          >
+        | undefined
+      >
+
+      /**
+       * A thunk that (if dispatched) will return a specific running mutation, identified
+       * by `endpointName` and `fixedCacheKey` or `requestId`.
+       * If that mutation is not running, dispatching the thunk will result in `undefined`.
+       *
+       * Can be used to await a specific mutation triggered in any way,
+       * including via hook trigger functions or manually dispatching `initiate` actions.
+       *
+       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
+       */
+      getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(
+        endpointName: EndpointName,
+        fixedCacheKeyOrRequestId: string,
+      ): ThunkWithReturnValue<
+        | MutationActionCreatorResult<
+            Definitions[EndpointName] & { type: 'mutation' }
+          >
+        | undefined
+      >
+
+      /**
+       * A thunk that (if dispatched) will return all running queries.
+       *
+       * Useful for SSR scenarios to await all running queries triggered in any way,
+       * including via hook calls or manually dispatching `initiate` actions.
+       *
+       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
+       */
+      getRunningQueriesThunk(): ThunkWithReturnValue<
+        Array<
+          QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>
+        >
+      >
+
+      /**
+       * A thunk that (if dispatched) will return all running mutations.
+       *
+       * Useful for SSR scenarios to await all running mutations triggered in any way,
+       * including via hook calls or manually dispatching `initiate` actions.
+       *
+       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
+       */
+      getRunningMutationsThunk(): ThunkWithReturnValue<
+        Array<MutationActionCreatorResult<any>>
+      >
+
+      /**
+       * A Redux thunk that can be used to manually trigger pre-fetching of data.
+       *
+       * 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.
+       *
+       * 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.
+       *
+       * @example
+       *
+       * ```ts no-transpile
+       * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))
+       * ```
+       */
+      prefetch<EndpointName extends QueryKeys<Definitions>>(
+        endpointName: EndpointName,
+        arg: QueryArgFrom<Definitions[EndpointName]>,
+        options?: PrefetchOptions,
+      ): ThunkAction<void, any, any, UnknownAction>
+      /**
+       * 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.
+       *
+       * 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.
+       *
+       * 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).
+       *
+       * 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.
+       *
+       * 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.
+       *
+       * @example
+       *
+       * ```ts
+       * const patchCollection = dispatch(
+       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
+       *     draftPosts.push({ id: 1, name: 'Teddy' })
+       *   })
+       * )
+       * ```
+       */
+      updateQueryData: UpdateQueryDataThunk<
+        Definitions,
+        RootState<Definitions, string, ReducerPath>
+      >
+
+      /**
+       * A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.
+       *
+       * 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.
+       *
+       * 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.
+       *
+       * The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.
+       *
+       * 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.
+       *
+       * @example
+       *
+       * ```ts
+       * await dispatch(
+       *   api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: "Hello!"})
+       * )
+       * ```
+       */
+      upsertQueryData: UpsertQueryDataThunk<
+        Definitions,
+        RootState<Definitions, string, ReducerPath>
+      >
+      /**
+       * 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.
+       *
+       * 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`.
+       *
+       * 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.
+       *
+       * 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.
+       *
+       * @example
+       * ```ts
+       * const patchCollection = dispatch(
+       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
+       *     draftPosts.push({ id: 1, name: 'Teddy' })
+       *   })
+       * )
+       *
+       * // later
+       * dispatch(
+       *   api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)
+       * )
+       *
+       * // or
+       * patchCollection.undo()
+       * ```
+       */
+      patchQueryData: PatchQueryDataThunk<
+        Definitions,
+        RootState<Definitions, string, ReducerPath>
+      >
+
+      /**
+       * 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'.
+       *
+       * @example
+       *
+       * ```ts
+       * dispatch(api.util.resetApiState())
+       * ```
+       */
+      resetApiState: SliceActions['resetApiState']
+
+      upsertQueryEntries: UpsertEntries<Definitions>
+
+      /**
+       * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).
+       *
+       * 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.
+       *
+       * 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.
+       *
+       * 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:
+       *
+       * - `[TagType]`
+       * - `[{ type: TagType }]`
+       * - `[{ type: TagType, id: number | string }]`
+       *
+       * @example
+       *
+       * ```ts
+       * dispatch(api.util.invalidateTags(['Post']))
+       * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))
+       * dispatch(
+       *   api.util.invalidateTags([
+       *     { type: 'Post', id: 1 },
+       *     { type: 'Post', id: 'LIST' },
+       *   ])
+       * )
+       * ```
+       */
+      invalidateTags: ActionCreatorWithPayload<
+        Array<TagDescription<TagTypes> | null | undefined>,
+        string
+      >
+
+      /**
+       * A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.
+       *
+       * 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.
+       */
+      selectInvalidatedBy: (
+        state: RootState<Definitions, string, ReducerPath>,
+        tags: ReadonlyArray<TagDescription<TagTypes> | null | undefined>,
+      ) => Array<{
+        endpointName: string
+        originalArgs: any
+        queryCacheKey: string
+      }>
+
+      /**
+       * A function to select all arguments currently cached for a given endpoint.
+       *
+       * 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.
+       */
+      selectCachedArgsForQuery: <QueryName extends AllQueryKeys<Definitions>>(
+        state: RootState<Definitions, string, ReducerPath>,
+        queryName: QueryName,
+      ) => Array<QueryArgFromAnyQuery<Definitions[QueryName]>>
+    }
+    /**
+     * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.
+     */
+    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
+    }
+  }
+}
+
+export interface ApiEndpointQuery<
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  Definition extends QueryDefinition<any, any, any, any, any>,
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  Definitions extends EndpointDefinitions,
+> extends BuildThunksApiEndpointQuery<Definition>,
+    BuildInitiateApiEndpointQuery<Definition>,
+    BuildSelectorsApiEndpointQuery<Definition, Definitions> {
+  name: string
+  /**
+   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
+   */
+  Types: NonNullable<Definition['Types']>
+}
+
+export interface ApiEndpointInfiniteQuery<
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  Definitions extends EndpointDefinitions,
+> extends BuildThunksApiEndpointInfiniteQuery<Definition>,
+    BuildInitiateApiEndpointInfiniteQuery<Definition>,
+    BuildSelectorsApiEndpointInfiniteQuery<Definition, Definitions> {
+  name: string
+  /**
+   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
+   */
+  Types: NonNullable<Definition['Types']>
+}
+
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+export interface ApiEndpointMutation<
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  Definition extends MutationDefinition<any, any, any, any, any>,
+  // eslint-disable-next-line @typescript-eslint/no-unused-vars
+  Definitions extends EndpointDefinitions,
+> extends BuildThunksApiEndpointMutation<Definition>,
+    BuildInitiateApiEndpointMutation<Definition>,
+    BuildSelectorsApiEndpointMutation<Definition, Definitions> {
+  name: string
+  /**
+   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
+   */
+  Types: NonNullable<Definition['Types']>
+}
+
+export type ListenerActions = {
+  /**
+   * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior
+   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners
+   */
+  onOnline: typeof onOnline
+  onOffline: typeof onOffline
+  /**
+   * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior
+   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners
+   */
+  onFocus: typeof onFocus
+  onFocusLost: typeof onFocusLost
+}
+
+export type InternalActions = SliceActions & ListenerActions
+
+export interface CoreModuleOptions {
+  /**
+   * A selector creator (usually from `reselect`, or matching the same signature)
+   */
+  createSelector?: CreateSelectorFunction<any, any, any>
+}
+
+/**
+ * Creates a module containing the basic redux logic for use with `buildCreateApi`.
+ *
+ * @example
+ * ```ts
+ * const createBaseApi = buildCreateApi(coreModule());
+ * ```
+ */
+export const coreModule = ({
+  createSelector = _createSelector,
+}: CoreModuleOptions = {}): Module<CoreModule> => ({
+  name: coreModuleName,
+  init(
+    api,
+    {
+      baseQuery,
+      tagTypes,
+      reducerPath,
+      serializeQueryArgs,
+      keepUnusedDataFor,
+      refetchOnMountOrArgChange,
+      refetchOnFocus,
+      refetchOnReconnect,
+      invalidationBehavior,
+      onSchemaFailure,
+      catchSchemaFailure,
+      skipSchemaValidation,
+    },
+    context,
+  ) {
+    enablePatches()
+
+    assertCast<InternalSerializeQueryArgs>(serializeQueryArgs)
+
+    const assertTagType: AssertTagTypes = (tag) => {
+      if (
+        typeof process !== 'undefined' &&
+        process.env.NODE_ENV === 'development'
+      ) {
+        if (!tagTypes.includes(tag.type as any)) {
+          console.error(
+            `Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`,
+          )
+        }
+      }
+      return tag
+    }
+
+    Object.assign(api, {
+      reducerPath,
+      endpoints: {},
+      internalActions: {
+        onOnline,
+        onOffline,
+        onFocus,
+        onFocusLost,
+      },
+      util: {},
+    })
+
+    const selectors = buildSelectors({
+      serializeQueryArgs: serializeQueryArgs as any,
+      reducerPath,
+      createSelector,
+    })
+
+    const {
+      selectInvalidatedBy,
+      selectCachedArgsForQuery,
+      buildQuerySelector,
+      buildInfiniteQuerySelector,
+      buildMutationSelector,
+    } = selectors
+
+    safeAssign(api.util, { selectInvalidatedBy, selectCachedArgsForQuery })
+
+    const {
+      queryThunk,
+      infiniteQueryThunk,
+      mutationThunk,
+      patchQueryData,
+      updateQueryData,
+      upsertQueryData,
+      prefetch,
+      buildMatchThunkActions,
+    } = buildThunks({
+      baseQuery,
+      reducerPath,
+      context,
+      api,
+      serializeQueryArgs,
+      assertTagType,
+      selectors,
+      onSchemaFailure,
+      catchSchemaFailure,
+      skipSchemaValidation,
+    })
+
+    const { reducer, actions: sliceActions } = buildSlice({
+      context,
+      queryThunk,
+      infiniteQueryThunk,
+      mutationThunk,
+      serializeQueryArgs,
+      reducerPath,
+      assertTagType,
+      config: {
+        refetchOnFocus,
+        refetchOnReconnect,
+        refetchOnMountOrArgChange,
+        keepUnusedDataFor,
+        reducerPath,
+        invalidationBehavior,
+      },
+    })
+
+    safeAssign(api.util, {
+      patchQueryData,
+      updateQueryData,
+      upsertQueryData,
+      prefetch,
+      resetApiState: sliceActions.resetApiState,
+      upsertQueryEntries: sliceActions.cacheEntriesUpserted as any,
+    })
+    safeAssign(api.internalActions, sliceActions)
+
+    const internalStateMap = new WeakMap<Dispatch, InternalMiddlewareState>()
+
+    const getInternalState = (dispatch: Dispatch) => {
+      const state = getOrInsertComputed(internalStateMap, dispatch, () => ({
+        currentSubscriptions: new Map(),
+        currentPolls: new Map(),
+        runningQueries: new Map(),
+        runningMutations: new Map(),
+      }))
+
+      return state
+    }
+
+    const {
+      buildInitiateQuery,
+      buildInitiateInfiniteQuery,
+      buildInitiateMutation,
+      getRunningMutationThunk,
+      getRunningMutationsThunk,
+      getRunningQueriesThunk,
+      getRunningQueryThunk,
+    } = buildInitiate({
+      queryThunk,
+      mutationThunk,
+      infiniteQueryThunk,
+      api,
+      serializeQueryArgs: serializeQueryArgs as any,
+      context,
+      getInternalState,
+    })
+
+    safeAssign(api.util, {
+      getRunningMutationThunk,
+      getRunningMutationsThunk,
+      getRunningQueryThunk,
+      getRunningQueriesThunk,
+    })
+
+    const { middleware, actions: middlewareActions } = buildMiddleware({
+      reducerPath,
+      context,
+      queryThunk,
+      mutationThunk,
+      infiniteQueryThunk,
+      api,
+      assertTagType,
+      selectors,
+      getRunningQueryThunk,
+      getInternalState,
+    })
+    safeAssign(api.util, middlewareActions)
+
+    safeAssign(api, { reducer: reducer as any, middleware })
+
+    return {
+      name: coreModuleName,
+      injectEndpoint(endpointName, definition) {
+        const anyApi = api as any as Api<
+          any,
+          Record<string, any>,
+          string,
+          string,
+          CoreModule
+        >
+        const endpoint = (anyApi.endpoints[endpointName] ??= {} as any)
+
+        if (isQueryDefinition(definition)) {
+          safeAssign(
+            endpoint,
+            {
+              name: endpointName,
+              select: buildQuerySelector(endpointName, definition),
+              initiate: buildInitiateQuery(endpointName, definition),
+            },
+            buildMatchThunkActions(queryThunk, endpointName),
+          )
+        }
+        if (isMutationDefinition(definition)) {
+          safeAssign(
+            endpoint,
+            {
+              name: endpointName,
+              select: buildMutationSelector(),
+              initiate: buildInitiateMutation(endpointName),
+            },
+            buildMatchThunkActions(mutationThunk, endpointName),
+          )
+        }
+        if (isInfiniteQueryDefinition(definition)) {
+          safeAssign(
+            endpoint,
+            {
+              name: endpointName,
+              select: buildInfiniteQuerySelector(endpointName, definition),
+              initiate: buildInitiateInfiniteQuery(endpointName, definition),
+            },
+            buildMatchThunkActions(queryThunk, endpointName),
+          )
+        }
+      },
+    }
+  },
+})
Index: node_modules/@reduxjs/toolkit/src/query/core/rtkImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/rtkImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/rtkImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,24 @@
+// This file exists to consolidate all of the imports from the `@reduxjs/toolkit` package.
+// ESBuild does not de-duplicate imports, so this file is used to ensure that each method
+// imported is only listed once, and there's only one mention of the `@reduxjs/toolkit` package.
+
+export {
+  createAction,
+  createSlice,
+  createSelector,
+  createAsyncThunk,
+  combineReducers,
+  createNextState,
+  isAnyOf,
+  isAllOf,
+  isAction,
+  isPending,
+  isRejected,
+  isFulfilled,
+  isRejectedWithValue,
+  isAsyncThunkAction,
+  prepareAutoBatched,
+  SHOULD_AUTOBATCH,
+  isPlainObject,
+  nanoid,
+} from '@reduxjs/toolkit'
Index: node_modules/@reduxjs/toolkit/src/query/core/setupListeners.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/core/setupListeners.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/core/setupListeners.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,118 @@
+import type {
+  ThunkDispatch,
+  ActionCreatorWithoutPayload, // Workaround for API-Extractor
+} from '@reduxjs/toolkit'
+import { createAction } from './rtkImports'
+
+export const INTERNAL_PREFIX = '__rtkq/'
+
+const ONLINE = 'online'
+const OFFLINE = 'offline'
+const FOCUS = 'focus'
+const FOCUSED = 'focused'
+const VISIBILITYCHANGE = 'visibilitychange'
+
+export const onFocus = /* @__PURE__ */ createAction(
+  `${INTERNAL_PREFIX}${FOCUSED}`,
+)
+export const onFocusLost = /* @__PURE__ */ createAction(
+  `${INTERNAL_PREFIX}un${FOCUSED}`,
+)
+export const onOnline = /* @__PURE__ */ createAction(
+  `${INTERNAL_PREFIX}${ONLINE}`,
+)
+export const onOffline = /* @__PURE__ */ createAction(
+  `${INTERNAL_PREFIX}${OFFLINE}`,
+)
+
+const actions = {
+  onFocus,
+  onFocusLost,
+  onOnline,
+  onOffline,
+}
+
+let initialized = false
+
+/**
+ * A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.
+ * It requires the dispatch method from your store.
+ * Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,
+ * but you have the option of providing a callback for more granular control.
+ *
+ * @example
+ * ```ts
+ * setupListeners(store.dispatch)
+ * ```
+ *
+ * @param dispatch - The dispatch method from your store
+ * @param customHandler - An optional callback for more granular control over listener behavior
+ * @returns Return value of the handler.
+ * The default handler returns an `unsubscribe` method that can be called to remove the listeners.
+ */
+export function setupListeners(
+  dispatch: ThunkDispatch<any, any, any>,
+  customHandler?: (
+    dispatch: ThunkDispatch<any, any, any>,
+    actions: {
+      onFocus: typeof onFocus
+      onFocusLost: typeof onFocusLost
+      onOnline: typeof onOnline
+      onOffline: typeof onOffline
+    },
+  ) => () => void,
+) {
+  function defaultHandler() {
+    const [handleFocus, handleFocusLost, handleOnline, handleOffline] = [
+      onFocus,
+      onFocusLost,
+      onOnline,
+      onOffline,
+    ].map((action) => () => dispatch(action()))
+
+    const handleVisibilityChange = () => {
+      if (window.document.visibilityState === 'visible') {
+        handleFocus()
+      } else {
+        handleFocusLost()
+      }
+    }
+
+    let unsubscribe = () => {
+      initialized = false
+    }
+
+    if (!initialized) {
+      if (typeof window !== 'undefined' && window.addEventListener) {
+        const handlers = {
+          [FOCUS]: handleFocus,
+          [VISIBILITYCHANGE]: handleVisibilityChange,
+          [ONLINE]: handleOnline,
+          [OFFLINE]: handleOffline,
+        }
+
+        function updateListeners(add: boolean) {
+          Object.entries(handlers).forEach(([event, handler]) => {
+            if (add) {
+              window.addEventListener(event, handler, false)
+            } else {
+              window.removeEventListener(event, handler)
+            }
+          })
+        }
+        // Handle focus events
+        updateListeners(true)
+        initialized = true
+
+        unsubscribe = () => {
+          updateListeners(false)
+          initialized = false
+        }
+      }
+    }
+
+    return unsubscribe
+  }
+
+  return customHandler ? customHandler(dispatch, actions) : defaultHandler()
+}
Index: node_modules/@reduxjs/toolkit/src/query/createApi.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/createApi.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/createApi.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,514 @@
+import {
+  getEndpointDefinition,
+  type Api,
+  type ApiContext,
+  type Module,
+  type ModuleName,
+} from './apiTypes'
+import type { CombinedState } from './core/apiState'
+import type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes'
+import type { SerializeQueryArgs } from './defaultSerializeQueryArgs'
+import { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs'
+import type {
+  EndpointBuilder,
+  EndpointDefinitions,
+  SchemaFailureConverter,
+  SchemaFailureHandler,
+  SchemaType,
+} from './endpointDefinitions'
+import {
+  DefinitionType,
+  ENDPOINT_INFINITEQUERY,
+  ENDPOINT_MUTATION,
+  ENDPOINT_QUERY,
+  isInfiniteQueryDefinition,
+  isQueryDefinition,
+} from './endpointDefinitions'
+import { nanoid } from './core/rtkImports'
+import type { UnknownAction } from '@reduxjs/toolkit'
+import type { NoInfer } from './tsHelpers'
+import { weakMapMemoize } from 'reselect'
+
+export interface CreateApiOptions<
+  BaseQuery extends BaseQueryFn,
+  Definitions extends EndpointDefinitions,
+  ReducerPath extends string = 'api',
+  TagTypes extends string = never,
+> {
+  /**
+   * 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.
+   *
+   * @example
+   *
+   * ```ts
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+   *
+   * const api = createApi({
+   *   // highlight-start
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   // highlight-end
+   *   endpoints: (build) => ({
+   *     // ...endpoints
+   *   }),
+   * })
+   * ```
+   */
+  baseQuery: BaseQuery
+  /**
+   * 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).
+   *
+   * @example
+   *
+   * ```ts
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   // highlight-start
+   *   tagTypes: ['Post', 'User'],
+   *   // highlight-end
+   *   endpoints: (build) => ({
+   *     // ...endpoints
+   *   }),
+   * })
+   * ```
+   */
+  tagTypes?: readonly TagTypes[]
+  /**
+   * 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'`.
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="apis.js"
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';
+   *
+   * const apiOne = createApi({
+   *   // highlight-start
+   *   reducerPath: 'apiOne',
+   *   // highlight-end
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (builder) => ({
+   *     // ...endpoints
+   *   }),
+   * });
+   *
+   * const apiTwo = createApi({
+   *   // highlight-start
+   *   reducerPath: 'apiTwo',
+   *   // highlight-end
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (builder) => ({
+   *     // ...endpoints
+   *   }),
+   * });
+   * ```
+   */
+  reducerPath?: ReducerPath
+  /**
+   * Accepts a custom function if you have a need to change the creation of cache keys for any reason.
+   */
+  serializeQueryArgs?: SerializeQueryArgs<unknown>
+  /**
+   * 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).
+   */
+  endpoints(
+    build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>,
+  ): Definitions
+  /**
+   * 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.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="keepUnusedDataFor example"
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   * type PostsResponse = Post[]
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPosts: build.query<PostsResponse, void>({
+   *       query: () => 'posts'
+   *     })
+   *   }),
+   *   // highlight-start
+   *   keepUnusedDataFor: 5
+   *   // highlight-end
+   * })
+   * ```
+   */
+  keepUnusedDataFor?: number
+  /**
+   * 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.
+   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
+   * - `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.
+   * - `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.
+   *
+   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
+   */
+  refetchOnMountOrArgChange?: boolean | number
+  /**
+   * 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.
+   *
+   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
+   *
+   * Note: requires [`setupListeners`](./setupListeners) to have been called.
+   */
+  refetchOnFocus?: boolean
+  /**
+   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.
+   *
+   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
+   *
+   * Note: requires [`setupListeners`](./setupListeners) to have been called.
+   */
+  refetchOnReconnect?: boolean
+  /**
+   * Defaults to `'delayed'`. This setting allows you to control when tags are invalidated after a mutation.
+   *
+   * - `'immediately'`: Queries are invalidated instantly after the mutation finished, even if they are running.
+   *   If the query provides tags that were invalidated while it ran, it won't be re-fetched.
+   * - `'delayed'`: Invalidation only happens after all queries and mutations are settled.
+   *   This ensures that queries are always invalidated correctly and automatically "batches" invalidations of concurrent mutations.
+   *   Note that if you constantly have some queries (or mutations) running, this can delay tag invalidations indefinitely.
+   */
+  invalidationBehavior?: 'delayed' | 'immediately'
+  /**
+   * A function that is passed every dispatched action. If this returns something other than `undefined`,
+   * that return value will be used to rehydrate fulfilled & errored queries.
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="next-redux-wrapper rehydration example"
+   * import type { Action, PayloadAction } from '@reduxjs/toolkit'
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * import { HYDRATE } from 'next-redux-wrapper'
+   *
+   * type RootState = any; // normally inferred from state
+   *
+   * function isHydrateAction(action: Action): action is PayloadAction<RootState> {
+   *   return action.type === HYDRATE
+   * }
+   *
+   * export const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   // highlight-start
+   *   extractRehydrationInfo(action, { reducerPath }): any {
+   *     if (isHydrateAction(action)) {
+   *       return action.payload[reducerPath]
+   *     }
+   *   },
+   *   // highlight-end
+   *   endpoints: (build) => ({
+   *     // omitted
+   *   }),
+   * })
+   * ```
+   */
+  extractRehydrationInfo?: (
+    action: UnknownAction,
+    {
+      reducerPath,
+    }: {
+      reducerPath: ReducerPath
+    },
+  ) =>
+    | undefined
+    | CombinedState<
+        NoInfer<Definitions>,
+        NoInfer<TagTypes>,
+        NoInfer<ReducerPath>
+      >
+
+  /**
+   * A function that is called when a schema validation fails.
+   *
+   * Gets called with a `NamedSchemaError` and an object containing the endpoint name, the type of the endpoint, the argument passed to the endpoint, and the query cache key (if applicable).
+   *
+   * `NamedSchemaError` has the following properties:
+   * - `issues`: an array of issues that caused the validation to fail
+   * - `value`: the value that was passed to the schema
+   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *     }),
+   *   }),
+   *   onSchemaFailure: (error, info) => {
+   *     console.error(error, info)
+   *   },
+   * })
+   * ```
+   */
+  onSchemaFailure?: SchemaFailureHandler
+
+  /**
+   * Convert a schema validation failure into an error shape matching base query errors.
+   *
+   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       responseSchema: v.object({ id: v.number(), name: v.string() }),
+   *     }),
+   *   }),
+   *   catchSchemaFailure: (error, info) => ({
+   *     status: "CUSTOM_ERROR",
+   *     error: error.schemaName + " failed validation",
+   *     data: error.issues,
+   *   }),
+   * })
+   * ```
+   */
+  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>
+
+  /**
+   * Defaults to `false`.
+   *
+   * If set to `true`, will skip schema validation for all endpoints, unless overridden by the endpoint.
+   *
+   * Can be overridden for specific schemas by passing an array of schema types to skip.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   skipSchemaValidation: process.env.NODE_ENV === "test" ? ["response"] : false, // skip schema validation for response in tests, since we'll be mocking the response
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       responseSchema: v.object({ id: v.number(), name: v.string() }),
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  skipSchemaValidation?: boolean | SchemaType[]
+}
+
+export type CreateApi<Modules extends ModuleName> = {
+  /**
+   * Creates a service to use in your application. Contains only the basic redux logic (the core module).
+   *
+   * @link https://redux-toolkit.js.org/rtk-query/api/createApi
+   */
+  <
+    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>
+}
+
+/**
+ * Builds a `createApi` method based on the provided `modules`.
+ *
+ * @link https://redux-toolkit.js.org/rtk-query/usage/customizing-create-api
+ *
+ * @example
+ * ```ts
+ * const MyContext = React.createContext<ReactReduxContextValue | null>(null);
+ * const customCreateApi = buildCreateApi(
+ *   coreModule(),
+ *   reactHooksModule({
+ *     hooks: {
+ *       useDispatch: createDispatchHook(MyContext),
+ *       useSelector: createSelectorHook(MyContext),
+ *       useStore: createStoreHook(MyContext)
+ *     }
+ *   })
+ * );
+ * ```
+ *
+ * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints
+ * @returns A `createApi` method using the provided `modules`.
+ */
+export function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(
+  ...modules: Modules
+): CreateApi<Modules[number]['name']> {
+  return function baseCreateApi(options) {
+    const extractRehydrationInfo = weakMapMemoize((action: UnknownAction) =>
+      options.extractRehydrationInfo?.(action, {
+        reducerPath: (options.reducerPath ?? 'api') as any,
+      }),
+    )
+
+    const optionsWithDefaults: CreateApiOptions<any, any, any, any> = {
+      reducerPath: 'api',
+      keepUnusedDataFor: 60,
+      refetchOnMountOrArgChange: false,
+      refetchOnFocus: false,
+      refetchOnReconnect: false,
+      invalidationBehavior: 'delayed',
+      ...options,
+      extractRehydrationInfo,
+      serializeQueryArgs(queryArgsApi) {
+        let finalSerializeQueryArgs = defaultSerializeQueryArgs
+        if ('serializeQueryArgs' in queryArgsApi.endpointDefinition) {
+          const endpointSQA =
+            queryArgsApi.endpointDefinition.serializeQueryArgs!
+          finalSerializeQueryArgs = (queryArgsApi) => {
+            const initialResult = endpointSQA(queryArgsApi)
+            if (typeof initialResult === 'string') {
+              // If the user function returned a string, use it as-is
+              return initialResult
+            } else {
+              // Assume they returned an object (such as a subset of the original
+              // query args) or a primitive, and serialize it ourselves
+              return defaultSerializeQueryArgs({
+                ...queryArgsApi,
+                queryArgs: initialResult,
+              })
+            }
+          }
+        } else if (options.serializeQueryArgs) {
+          finalSerializeQueryArgs = options.serializeQueryArgs
+        }
+
+        return finalSerializeQueryArgs(queryArgsApi)
+      },
+      tagTypes: [...(options.tagTypes || [])],
+    }
+
+    const context: ApiContext<EndpointDefinitions> = {
+      endpointDefinitions: {},
+      batch(fn) {
+        // placeholder "batch" method to be overridden by plugins, for example with React.unstable_batchedUpdate
+        fn()
+      },
+      apiUid: nanoid(),
+      extractRehydrationInfo,
+      hasRehydrationInfo: weakMapMemoize(
+        (action) => extractRehydrationInfo(action) != null,
+      ),
+    }
+
+    const api = {
+      injectEndpoints,
+      enhanceEndpoints({ addTagTypes, endpoints }) {
+        if (addTagTypes) {
+          for (const eT of addTagTypes) {
+            if (!optionsWithDefaults.tagTypes!.includes(eT as any)) {
+              ;(optionsWithDefaults.tagTypes as any[]).push(eT)
+            }
+          }
+        }
+        if (endpoints) {
+          for (const [endpointName, partialDefinition] of Object.entries(
+            endpoints,
+          )) {
+            if (typeof partialDefinition === 'function') {
+              partialDefinition(getEndpointDefinition(context, endpointName))
+            } else {
+              Object.assign(
+                getEndpointDefinition(context, endpointName) || {},
+                partialDefinition,
+              )
+            }
+          }
+        }
+        return api
+      },
+    } as Api<BaseQueryFn, {}, string, string, Modules[number]['name']>
+
+    const initializedModules = modules.map((m) =>
+      m.init(api as any, optionsWithDefaults as any, context),
+    )
+
+    function injectEndpoints(
+      inject: Parameters<typeof api.injectEndpoints>[0],
+    ) {
+      const evaluatedEndpoints = inject.endpoints({
+        query: (x) => ({ ...x, type: ENDPOINT_QUERY }) as any,
+        mutation: (x) => ({ ...x, type: ENDPOINT_MUTATION }) as any,
+        infiniteQuery: (x) => ({ ...x, type: ENDPOINT_INFINITEQUERY }) as any,
+      })
+
+      for (const [endpointName, definition] of Object.entries(
+        evaluatedEndpoints,
+      )) {
+        if (
+          inject.overrideExisting !== true &&
+          endpointName in context.endpointDefinitions
+        ) {
+          if (inject.overrideExisting === 'throw') {
+            throw new Error(
+              `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``,
+            )
+          } else if (
+            typeof process !== 'undefined' &&
+            process.env.NODE_ENV === 'development'
+          ) {
+            console.error(
+              `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``,
+            )
+          }
+
+          continue
+        }
+
+        if (
+          typeof process !== 'undefined' &&
+          process.env.NODE_ENV === 'development'
+        ) {
+          if (isInfiniteQueryDefinition(definition)) {
+            const { infiniteQueryOptions } = definition
+            const { maxPages, getPreviousPageParam } = infiniteQueryOptions
+
+            if (typeof maxPages === 'number') {
+              if (maxPages < 1) {
+                throw new Error(
+                  `maxPages for endpoint '${endpointName}' must be a number greater than 0`,
+                )
+              }
+
+              if (typeof getPreviousPageParam !== 'function') {
+                throw new Error(
+                  `getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`,
+                )
+              }
+            }
+          }
+        }
+
+        context.endpointDefinitions[endpointName] = definition
+        for (const m of initializedModules) {
+          m.injectEndpoint(endpointName, definition)
+        }
+      }
+
+      return api as any
+    }
+
+    return api.injectEndpoints({ endpoints: options.endpoints as any })
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/defaultSerializeQueryArgs.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/defaultSerializeQueryArgs.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/defaultSerializeQueryArgs.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,52 @@
+import type { QueryCacheKey } from './core/apiState'
+import type { EndpointDefinition } from './endpointDefinitions'
+import { isPlainObject } from './core/rtkImports'
+
+const cache: WeakMap<any, string> | undefined = WeakMap
+  ? new WeakMap()
+  : undefined
+
+export const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({
+  endpointName,
+  queryArgs,
+}) => {
+  let serialized = ''
+
+  const cached = cache?.get(queryArgs)
+
+  if (typeof cached === 'string') {
+    serialized = cached
+  } else {
+    const stringified = JSON.stringify(queryArgs, (key, value) => {
+      // Handle bigints
+      value = typeof value === 'bigint' ? { $bigint: value.toString() } : value
+      // Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })
+      value = isPlainObject(value)
+        ? Object.keys(value)
+            .sort()
+            .reduce<any>((acc, key) => {
+              acc[key] = (value as any)[key]
+              return acc
+            }, {})
+        : value
+      return value
+    })
+    if (isPlainObject(queryArgs)) {
+      cache?.set(queryArgs, stringified)
+    }
+    serialized = stringified
+  }
+  return `${endpointName}(${serialized})`
+}
+
+export type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {
+  queryArgs: QueryArgs
+  endpointDefinition: EndpointDefinition<any, any, any, any>
+  endpointName: string
+}) => ReturnType
+
+export type InternalSerializeQueryArgs = (_: {
+  queryArgs: any
+  endpointDefinition: EndpointDefinition<any, any, any, any>
+  endpointName: string
+}) => QueryCacheKey
Index: node_modules/@reduxjs/toolkit/src/query/endpointDefinitions.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/endpointDefinitions.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/endpointDefinitions.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1605 @@
+import type { Api } from '@reduxjs/toolkit/query'
+import type { StandardSchemaV1 } from '@standard-schema/spec'
+import type {
+  BaseQueryApi,
+  BaseQueryArg,
+  BaseQueryError,
+  BaseQueryExtraOptions,
+  BaseQueryFn,
+  BaseQueryMeta,
+  BaseQueryResult,
+  QueryReturnValue,
+} from './baseQueryTypes'
+import type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection'
+import type {
+  CacheLifecycleInfiniteQueryExtraOptions,
+  CacheLifecycleMutationExtraOptions,
+  CacheLifecycleQueryExtraOptions,
+} from './core/buildMiddleware/cacheLifecycle'
+import type {
+  QueryLifecycleInfiniteQueryExtraOptions,
+  QueryLifecycleMutationExtraOptions,
+  QueryLifecycleQueryExtraOptions,
+} from './core/buildMiddleware/queryLifecycle'
+import type {
+  InfiniteData,
+  InfiniteQueryConfigOptions,
+  QuerySubState,
+  RootState,
+} from './core/index'
+import type { SerializeQueryArgs } from './defaultSerializeQueryArgs'
+import type { NEVER } from './fakeBaseQuery'
+import type {
+  CastAny,
+  HasRequiredProps,
+  MaybePromise,
+  NonUndefined,
+  OmitFromUnion,
+  UnwrapPromise,
+} from './tsHelpers'
+import { isNotNullish } from './utils'
+import type { NamedSchemaError } from './standardSchema'
+import { filterMap } from './utils/filterMap'
+
+const rawResultType = /* @__PURE__ */ Symbol()
+const resultType = /* @__PURE__ */ Symbol()
+const baseQuery = /* @__PURE__ */ Symbol()
+
+export interface SchemaFailureInfo {
+  endpoint: string
+  arg: any
+  type: 'query' | 'mutation'
+  queryCacheKey?: string
+}
+
+export type SchemaFailureHandler = (
+  error: NamedSchemaError,
+  info: SchemaFailureInfo,
+) => void
+
+export type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (
+  error: NamedSchemaError,
+  info: SchemaFailureInfo,
+) => BaseQueryError<BaseQuery>
+
+export type EndpointDefinitionWithQuery<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  RawResultType extends BaseQueryResult<BaseQuery>,
+> = {
+  /**
+   * `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.
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="query example"
+   *
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   * type PostsResponse = Post[]
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   tagTypes: ['Post'],
+   *   endpoints: (build) => ({
+   *     getPosts: build.query<PostsResponse, void>({
+   *       // highlight-start
+   *       query: () => 'posts',
+   *       // highlight-end
+   *     }),
+   *     addPost: build.mutation<Post, Partial<Post>>({
+   *      // highlight-start
+   *      query: (body) => ({
+   *        url: `posts`,
+   *        method: 'POST',
+   *        body,
+   *      }),
+   *      // highlight-end
+   *      invalidatesTags: [{ type: 'Post', id: 'LIST' }],
+   *    }),
+   *   })
+   * })
+   * ```
+   */
+  query(arg: QueryArg): BaseQueryArg<BaseQuery>
+  queryFn?: never
+  /**
+   * A function to manipulate the data returned by a query or mutation.
+   */
+  transformResponse?(
+    baseQueryReturnValue: RawResultType,
+    meta: BaseQueryMeta<BaseQuery>,
+    arg: QueryArg,
+  ): ResultType | Promise<ResultType>
+  /**
+   * A function to manipulate the data returned by a failed query or mutation.
+   */
+  transformErrorResponse?(
+    baseQueryReturnValue: BaseQueryError<BaseQuery>,
+    meta: BaseQueryMeta<BaseQuery>,
+    arg: QueryArg,
+  ): unknown
+
+  /**
+   * A schema for the result *before* it's passed to `transformResponse`.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const postSchema = v.object({ id: v.number(), name: v.string() })
+   * type Post = v.InferOutput<typeof postSchema>
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPostName: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       rawResponseSchema: postSchema,
+   *       transformResponse: (post) => post.name,
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  rawResponseSchema?: StandardSchemaV1<RawResultType>
+
+  /**
+   * A schema for the error object returned by the `query` or `queryFn`, *before* it's passed to `transformErrorResponse`.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   * import {customBaseQuery, baseQueryErrorSchema} from "./customBaseQuery"
+   *
+   * const api = createApi({
+   *   baseQuery: customBaseQuery,
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       rawErrorResponseSchema: baseQueryErrorSchema,
+   *       transformErrorResponse: (error) => error.data,
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  rawErrorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>
+}
+
+export type EndpointDefinitionWithQueryFn<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+> = {
+  /**
+   * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Basic queryFn example"
+   *
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   * type PostsResponse = Post[]
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPosts: build.query<PostsResponse, void>({
+   *       query: () => 'posts',
+   *     }),
+   *     flipCoin: build.query<'heads' | 'tails', void>({
+   *       // highlight-start
+   *       queryFn(arg, queryApi, extraOptions, baseQuery) {
+   *         const randomVal = Math.random()
+   *         if (randomVal < 0.45) {
+   *           return { data: 'heads' }
+   *         }
+   *         if (randomVal < 0.9) {
+   *           return { data: 'tails' }
+   *         }
+   *         return { error: { status: 500, statusText: 'Internal Server Error', data: "Coin landed on its edge!" } }
+   *       }
+   *       // highlight-end
+   *     })
+   *   })
+   * })
+   * ```
+   */
+  queryFn(
+    arg: QueryArg,
+    api: BaseQueryApi,
+    extraOptions: BaseQueryExtraOptions<BaseQuery>,
+    baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>,
+  ): MaybePromise<
+    QueryReturnValue<
+      ResultType,
+      BaseQueryError<BaseQuery>,
+      BaseQueryMeta<BaseQuery>
+    >
+  >
+  query?: never
+  transformResponse?: never
+  transformErrorResponse?: never
+  rawResponseSchema?: never
+  rawErrorResponseSchema?: never
+}
+
+type BaseEndpointTypes<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  RawResultType,
+> = {
+  QueryArg: QueryArg
+  BaseQuery: BaseQuery
+  ResultType: ResultType
+  RawResultType: RawResultType
+}
+
+export type SchemaType =
+  | 'arg'
+  | 'rawResponse'
+  | 'response'
+  | 'rawErrorResponse'
+  | 'errorResponse'
+  | 'meta'
+
+interface CommonEndpointDefinition<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+> {
+  /**
+   * A schema for the arguments to be passed to the `query` or `queryFn`.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       argSchema: v.object({ id: v.number() }),
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  argSchema?: StandardSchemaV1<QueryArg>
+
+  /**
+   * A schema for the result (including `transformResponse` if provided).
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const postSchema = v.object({ id: v.number(), name: v.string() })
+   * type Post = v.InferOutput<typeof postSchema>
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       responseSchema: postSchema,
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  responseSchema?: StandardSchemaV1<ResultType>
+
+  /**
+   * A schema for the error object returned by the `query` or `queryFn` (including `transformErrorResponse` if provided).
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   * import { customBaseQuery, baseQueryErrorSchema } from "./customBaseQuery"
+   *
+   * const api = createApi({
+   *   baseQuery: customBaseQuery,
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       errorResponseSchema: baseQueryErrorSchema,
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  errorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>
+
+  /**
+   * A schema for the `meta` property returned by the `query` or `queryFn`.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   * import { customBaseQuery, baseQueryMetaSchema } from "./customBaseQuery"
+   *
+   * const api = createApi({
+   *   baseQuery: customBaseQuery,
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       metaSchema: baseQueryMetaSchema,
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  metaSchema?: StandardSchemaV1<BaseQueryMeta<BaseQuery>>
+
+  /**
+   * Defaults to `true`.
+   *
+   * Most apps should leave this setting on. The only time it can be a performance issue
+   * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and
+   * you're unable to paginate it.
+   *
+   * For details of how this works, please see the below. When it is set to `false`,
+   * every request will cause subscribed components to rerender, even when the data has not changed.
+   *
+   * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing
+   */
+  structuralSharing?: boolean
+
+  /**
+   * A function that is called when a schema validation fails.
+   *
+   * Gets called with a `NamedSchemaError` and an object containing the endpoint name, the type of the endpoint, the argument passed to the endpoint, and the query cache key (if applicable).
+   *
+   * `NamedSchemaError` has the following properties:
+   * - `issues`: an array of issues that caused the validation to fail
+   * - `value`: the value that was passed to the schema
+   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       onSchemaFailure: (error, info) => {
+   *         console.error(error, info)
+   *       },
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  onSchemaFailure?: SchemaFailureHandler
+
+  /**
+   * Convert a schema validation failure into an error shape matching base query errors.
+   *
+   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       responseSchema: v.object({ id: v.number(), name: v.string() }),
+   *       catchSchemaFailure: (error, info) => ({
+   *         status: "CUSTOM_ERROR",
+   *         error: error.schemaName + " failed validation",
+   *         data: error.issues,
+   *       }),
+   *     }),
+   *   }),
+   * })
+   * ```
+   */
+  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>
+
+  /**
+   * Defaults to `false`.
+   *
+   * If set to `true`, will skip schema validation for this endpoint.
+   * Overrides the global setting.
+   *
+   * Can be overridden for specific schemas by passing an array of schema types to skip.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta no-transpile
+   * import { createApi } from '@reduxjs/toolkit/query/react'
+   * import * as v from "valibot"
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   endpoints: (build) => ({
+   *     getPost: build.query<Post, { id: number }>({
+   *       query: ({ id }) => `/post/${id}`,
+   *       responseSchema: v.object({ id: v.number(), name: v.string() }),
+   *       skipSchemaValidation: process.env.NODE_ENV === "test" ? ["response"] : false, // skip schema validation for response in tests, since we'll be mocking the response
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  skipSchemaValidation?: boolean | SchemaType[]
+}
+
+export type BaseEndpointDefinition<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ResultType,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> = (
+  | ([CastAny<BaseQueryResult<BaseQuery>, {}>] extends [NEVER]
+      ? never
+      : EndpointDefinitionWithQuery<
+          QueryArg,
+          BaseQuery,
+          ResultType,
+          RawResultType
+        >)
+  | EndpointDefinitionWithQueryFn<QueryArg, BaseQuery, ResultType>
+) &
+  CommonEndpointDefinition<QueryArg, BaseQuery, ResultType> & {
+    /* phantom type */
+    [rawResultType]?: RawResultType
+    /* phantom type */
+    [resultType]?: ResultType
+    /* phantom type */
+    [baseQuery]?: BaseQuery
+  } & HasRequiredProps<
+    BaseQueryExtraOptions<BaseQuery>,
+    { extraOptions: BaseQueryExtraOptions<BaseQuery> },
+    { extraOptions?: BaseQueryExtraOptions<BaseQuery> }
+  >
+
+// NOTE As with QueryStatus in `apiState.ts`, don't use this for real comparisons
+// at runtime, use the string constants defined below.
+export enum DefinitionType {
+  query = 'query',
+  mutation = 'mutation',
+  infinitequery = 'infinitequery',
+}
+
+export const ENDPOINT_QUERY = DefinitionType.query
+export const ENDPOINT_MUTATION = DefinitionType.mutation
+export const ENDPOINT_INFINITEQUERY = DefinitionType.infinitequery
+
+type TagDescriptionArray<TagTypes extends string> = ReadonlyArray<
+  TagDescription<TagTypes> | undefined | null
+>
+
+export type GetResultDescriptionFn<
+  TagTypes extends string,
+  ResultType,
+  QueryArg,
+  ErrorType,
+  MetaType,
+> = (
+  result: ResultType | undefined,
+  error: ErrorType | undefined,
+  arg: QueryArg,
+  meta: MetaType,
+) => TagDescriptionArray<TagTypes>
+
+export type FullTagDescription<TagType> = {
+  type: TagType
+  id?: number | string
+}
+export type TagDescription<TagType> = TagType | FullTagDescription<TagType>
+
+/**
+ * @public
+ */
+export type ResultDescription<
+  TagTypes extends string,
+  ResultType,
+  QueryArg,
+  ErrorType,
+  MetaType,
+> =
+  | TagDescriptionArray<TagTypes>
+  | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>
+
+type QueryTypes<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ResultType,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {
+  /**
+   * The endpoint definition type. To be used with some internal generic types.
+   * @example
+   * ```ts
+   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...
+   * ```
+   */
+  QueryDefinition: QueryDefinition<
+    QueryArg,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath
+  >
+  TagTypes: TagTypes
+  ReducerPath: ReducerPath
+}
+
+/**
+ * @public
+ */
+export interface QueryExtraOptions<
+  TagTypes extends string,
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> extends CacheLifecycleQueryExtraOptions<
+      ResultType,
+      QueryArg,
+      BaseQuery,
+      ReducerPath
+    >,
+    QueryLifecycleQueryExtraOptions<
+      ResultType,
+      QueryArg,
+      BaseQuery,
+      ReducerPath
+    >,
+    CacheCollectionQueryExtraOptions {
+  type: DefinitionType.query
+
+  /**
+   * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.
+   * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.
+   * 1.  `['Post']` - equivalent to `2`
+   * 2.  `[{ type: 'Post' }]` - equivalent to `1`
+   * 3.  `[{ type: 'Post', id: 1 }]`
+   * 4.  `(result, error, arg) => ['Post']` - equivalent to `5`
+   * 5.  `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`
+   * 6.  `(result, error, arg) => [{ type: 'Post', id: 1 }]`
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="providesTags example"
+   *
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   * type PostsResponse = Post[]
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   tagTypes: ['Posts'],
+   *   endpoints: (build) => ({
+   *     getPosts: build.query<PostsResponse, void>({
+   *       query: () => 'posts',
+   *       // highlight-start
+   *       providesTags: (result) =>
+   *         result
+   *           ? [
+   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),
+   *               { type: 'Posts', id: 'LIST' },
+   *             ]
+   *           : [{ type: 'Posts', id: 'LIST' }],
+   *       // highlight-end
+   *     })
+   *   })
+   * })
+   * ```
+   */
+  providesTags?: ResultDescription<
+    TagTypes,
+    ResultType,
+    QueryArg,
+    BaseQueryError<BaseQuery>,
+    BaseQueryMeta<BaseQuery>
+  >
+  /**
+   * Not to be used. A query should not invalidate tags in the cache.
+   */
+  invalidatesTags?: never
+
+  /**
+   * Can be provided to return a custom cache key value based on the query arguments.
+   *
+   * 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.
+   *
+   * 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.
+   *
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="serializeQueryArgs : exclude value"
+   *
+   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   *
+   * interface MyApiClient {
+   *   fetchPost: (id: string) => Promise<Post>
+   * }
+   *
+   * createApi({
+   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *  endpoints: (build) => ({
+   *    // Example: an endpoint with an API client passed in as an argument,
+   *    // but only the item ID should be used as the cache key
+   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({
+   *      queryFn: async ({ id, client }) => {
+   *        const post = await client.fetchPost(id)
+   *        return { data: post }
+   *      },
+   *      // highlight-start
+   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {
+   *        const { id } = queryArgs
+   *        // This can return a string, an object, a number, or a boolean.
+   *        // If it returns an object, number or boolean, that value
+   *        // will be serialized automatically via `defaultSerializeQueryArgs`
+   *        return { id } // omit `client` from the cache key
+   *
+   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:
+   *        // return defaultSerializeQueryArgs({
+   *        //   endpointName,
+   *        //   queryArgs: { id },
+   *        //   endpointDefinition
+   *        // })
+   *        // Or  create and return a string yourself:
+   *        // return `getPost(${id})`
+   *      },
+   *      // highlight-end
+   *    }),
+   *  }),
+   *})
+   * ```
+   */
+  serializeQueryArgs?: SerializeQueryArgs<
+    QueryArg,
+    string | number | boolean | Record<any, any>
+  >
+
+  /**
+   * Can be provided to merge an incoming response value into the current cache data.
+   * If supplied, no automatic structural sharing will be applied - it's up to
+   * you to update the cache appropriately.
+   *
+   * Since RTKQ normally replaces cache entries with the new response, you will usually
+   * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep
+   * an existing cache entry so that it can be updated.
+   *
+   * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,
+   * or return a new value, but _not_ both at once.
+   *
+   * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,
+   * the cache entry will just save the response data directly.
+   *
+   * Useful if you don't want a new request to completely override the current cache value,
+   * maybe because you have manually updated it from another source and don't want those
+   * updates to get lost.
+   *
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="merge: pagination"
+   *
+   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   *
+   * createApi({
+   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *  endpoints: (build) => ({
+   *    listItems: build.query<string[], number>({
+   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,
+   *     // Only have one cache entry because the arg always maps to one string
+   *     serializeQueryArgs: ({ endpointName }) => {
+   *       return endpointName
+   *      },
+   *      // Always merge incoming data to the cache entry
+   *      merge: (currentCache, newItems) => {
+   *        currentCache.push(...newItems)
+   *      },
+   *      // Refetch when the page arg changes
+   *      forceRefetch({ currentArg, previousArg }) {
+   *        return currentArg !== previousArg
+   *      },
+   *    }),
+   *  }),
+   *})
+   * ```
+   */
+  merge?(
+    currentCacheData: ResultType,
+    responseData: ResultType,
+    otherArgs: {
+      arg: QueryArg
+      baseQueryMeta: BaseQueryMeta<BaseQuery>
+      requestId: string
+      fulfilledTimeStamp: number
+    },
+  ): ResultType | void
+
+  /**
+   * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.
+   * This is primarily useful for "infinite scroll" / pagination use cases where
+   * RTKQ is keeping a single cache entry that is added to over time, in combination
+   * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback
+   * set to add incoming data to the cache entry each time.
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="forceRefresh: pagination"
+   *
+   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   *
+   * createApi({
+   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *  endpoints: (build) => ({
+   *    listItems: build.query<string[], number>({
+   *      query: (pageNumber) => `/listItems?page=${pageNumber}`,
+   *     // Only have one cache entry because the arg always maps to one string
+   *     serializeQueryArgs: ({ endpointName }) => {
+   *       return endpointName
+   *      },
+   *      // Always merge incoming data to the cache entry
+   *      merge: (currentCache, newItems) => {
+   *        currentCache.push(...newItems)
+   *      },
+   *      // Refetch when the page arg changes
+   *      forceRefetch({ currentArg, previousArg }) {
+   *        return currentArg !== previousArg
+   *      },
+   *    }),
+   *  }),
+   *})
+   * ```
+   */
+  forceRefetch?(params: {
+    currentArg: QueryArg | undefined
+    previousArg: QueryArg | undefined
+    state: RootState<any, any, string>
+    endpointState?: QuerySubState<any>
+  }): boolean
+
+  /**
+   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
+   */
+  Types?: QueryTypes<
+    QueryArg,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath,
+    RawResultType
+  >
+}
+
+export type QueryDefinition<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ResultType,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, RawResultType> &
+  QueryExtraOptions<
+    TagTypes,
+    ResultType,
+    QueryArg,
+    BaseQuery,
+    ReducerPath,
+    RawResultType
+  >
+
+export type InfiniteQueryTypes<
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ResultType,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {
+  /**
+   * The endpoint definition type. To be used with some internal generic types.
+   * @example
+   * ```ts
+   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...
+   * ```
+   */
+  InfiniteQueryDefinition: InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath
+  >
+  TagTypes: TagTypes
+  ReducerPath: ReducerPath
+}
+
+export interface InfiniteQueryExtraOptions<
+  TagTypes extends string,
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> extends CacheLifecycleInfiniteQueryExtraOptions<
+      InfiniteData<ResultType, PageParam>,
+      QueryArg,
+      BaseQuery,
+      ReducerPath
+    >,
+    QueryLifecycleInfiniteQueryExtraOptions<
+      InfiniteData<ResultType, PageParam>,
+      QueryArg,
+      BaseQuery,
+      ReducerPath
+    >,
+    CacheCollectionQueryExtraOptions {
+  type: DefinitionType.infinitequery
+
+  providesTags?: ResultDescription<
+    TagTypes,
+    InfiniteData<ResultType, PageParam>,
+    QueryArg,
+    BaseQueryError<BaseQuery>,
+    BaseQueryMeta<BaseQuery>
+  >
+  /**
+   * Not to be used. A query should not invalidate tags in the cache.
+   */
+  invalidatesTags?: never
+
+  /**
+   * Required options to configure the infinite query behavior.
+   * `initialPageParam` and `getNextPageParam` are required, to
+   * ensure the infinite query can properly fetch the next page of data.
+   * `initialPageParam` may be specified when using the
+   * endpoint, to override the default value.
+   * `maxPages` and `getPreviousPageParam` are both optional.
+   * 
+   * @example
+   * 
+   * ```ts
+   * // codeblock-meta title="infiniteQueryOptions example"
+   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
+   * 
+   * type Pokemon = {
+   *   id: string
+   *   name: string
+   * }
+   * 
+   * const pokemonApi = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+   *   endpoints: (build) => ({
+   *     getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({
+   *       infiniteQueryOptions: {
+   *         initialPageParam: 0,
+   *         maxPages: 3,
+   *         getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>
+   *           lastPageParam + 1,
+   *         getPreviousPageParam: (
+   *           firstPage,
+   *           allPages,
+   *           firstPageParam,
+   *           allPageParams,
+   *         ) => {
+   *           return firstPageParam > 0 ? firstPageParam - 1 : undefined
+   *         },
+   *       },
+   *       query({pageParam}) {
+   *         return `https://example.com/listItems?page=${pageParam}`
+   *       },
+   *     }),
+   *   }),
+   * })
+   
+   * ```
+   */
+  infiniteQueryOptions: InfiniteQueryConfigOptions<
+    ResultType,
+    PageParam,
+    QueryArg
+  >
+
+  /**
+   * Can be provided to return a custom cache key value based on the query arguments.
+   *
+   * 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.
+   *
+   * 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.
+   *
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="serializeQueryArgs : exclude value"
+   *
+   * import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   *
+   * interface MyApiClient {
+   *   fetchPost: (id: string) => Promise<Post>
+   * }
+   *
+   * createApi({
+   *  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *  endpoints: (build) => ({
+   *    // Example: an endpoint with an API client passed in as an argument,
+   *    // but only the item ID should be used as the cache key
+   *    getPost: build.query<Post, { id: string; client: MyApiClient }>({
+   *      queryFn: async ({ id, client }) => {
+   *        const post = await client.fetchPost(id)
+   *        return { data: post }
+   *      },
+   *      // highlight-start
+   *      serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {
+   *        const { id } = queryArgs
+   *        // This can return a string, an object, a number, or a boolean.
+   *        // If it returns an object, number or boolean, that value
+   *        // will be serialized automatically via `defaultSerializeQueryArgs`
+   *        return { id } // omit `client` from the cache key
+   *
+   *        // Alternately, you can use `defaultSerializeQueryArgs` yourself:
+   *        // return defaultSerializeQueryArgs({
+   *        //   endpointName,
+   *        //   queryArgs: { id },
+   *        //   endpointDefinition
+   *        // })
+   *        // Or  create and return a string yourself:
+   *        // return `getPost(${id})`
+   *      },
+   *      // highlight-end
+   *    }),
+   *  }),
+   *})
+   * ```
+   */
+  serializeQueryArgs?: SerializeQueryArgs<
+    QueryArg,
+    string | number | boolean | Record<any, any>
+  >
+
+  /**
+   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
+   */
+  Types?: InfiniteQueryTypes<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath,
+    RawResultType
+  >
+}
+
+export type InfiniteQueryDefinition<
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ResultType,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> =
+  // Infinite query endpoints receive `{queryArg, pageParam}`
+  BaseEndpointDefinition<
+    InfiniteQueryCombinedArg<QueryArg, PageParam>,
+    BaseQuery,
+    ResultType,
+    RawResultType
+  > &
+    InfiniteQueryExtraOptions<
+      TagTypes,
+      ResultType,
+      QueryArg,
+      PageParam,
+      BaseQuery,
+      ReducerPath,
+      RawResultType
+    >
+
+type MutationTypes<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ResultType,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {
+  /**
+   * The endpoint definition type. To be used with some internal generic types.
+   * @example
+   * ```ts
+   * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...
+   * ```
+   */
+  MutationDefinition: MutationDefinition<
+    QueryArg,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath
+  >
+  TagTypes: TagTypes
+  ReducerPath: ReducerPath
+}
+
+/**
+ * @public
+ */
+export interface MutationExtraOptions<
+  TagTypes extends string,
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> extends CacheLifecycleMutationExtraOptions<
+      ResultType,
+      QueryArg,
+      BaseQuery,
+      ReducerPath
+    >,
+    QueryLifecycleMutationExtraOptions<
+      ResultType,
+      QueryArg,
+      BaseQuery,
+      ReducerPath
+    > {
+  type: DefinitionType.mutation
+
+  /**
+   * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.
+   * Expects the same shapes as `providesTags`.
+   *
+   * @example
+   *
+   * ```ts
+   * // codeblock-meta title="invalidatesTags example"
+   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+   * interface Post {
+   *   id: number
+   *   name: string
+   * }
+   * type PostsResponse = Post[]
+   *
+   * const api = createApi({
+   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+   *   tagTypes: ['Posts'],
+   *   endpoints: (build) => ({
+   *     getPosts: build.query<PostsResponse, void>({
+   *       query: () => 'posts',
+   *       providesTags: (result) =>
+   *         result
+   *           ? [
+   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),
+   *               { type: 'Posts', id: 'LIST' },
+   *             ]
+   *           : [{ type: 'Posts', id: 'LIST' }],
+   *     }),
+   *     addPost: build.mutation<Post, Partial<Post>>({
+   *       query(body) {
+   *         return {
+   *           url: `posts`,
+   *           method: 'POST',
+   *           body,
+   *         }
+   *       },
+   *       // highlight-start
+   *       invalidatesTags: [{ type: 'Posts', id: 'LIST' }],
+   *       // highlight-end
+   *     }),
+   *   })
+   * })
+   * ```
+   */
+  invalidatesTags?: ResultDescription<
+    TagTypes,
+    ResultType,
+    QueryArg,
+    BaseQueryError<BaseQuery>,
+    BaseQueryMeta<BaseQuery>
+  >
+  /**
+   * Not to be used. A mutation should not provide tags to the cache.
+   */
+  providesTags?: never
+
+  /**
+   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
+   */
+  Types?: MutationTypes<
+    QueryArg,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath,
+    RawResultType
+  >
+}
+
+export type MutationDefinition<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ResultType,
+  ReducerPath extends string = string,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, RawResultType> &
+  MutationExtraOptions<
+    TagTypes,
+    ResultType,
+    QueryArg,
+    BaseQuery,
+    ReducerPath,
+    RawResultType
+  >
+
+export type EndpointDefinition<
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ResultType,
+  ReducerPath extends string = string,
+  PageParam = any,
+  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+> =
+  | QueryDefinition<
+      QueryArg,
+      BaseQuery,
+      TagTypes,
+      ResultType,
+      ReducerPath,
+      RawResultType
+    >
+  | MutationDefinition<
+      QueryArg,
+      BaseQuery,
+      TagTypes,
+      ResultType,
+      ReducerPath,
+      RawResultType
+    >
+  | InfiniteQueryDefinition<
+      QueryArg,
+      PageParam,
+      BaseQuery,
+      TagTypes,
+      ResultType,
+      ReducerPath,
+      RawResultType
+    >
+
+export type EndpointDefinitions = Record<
+  string,
+  EndpointDefinition<any, any, any, any, any, any, any>
+>
+
+export function isQueryDefinition(
+  e: EndpointDefinition<any, any, any, any, any, any, any>,
+): e is QueryDefinition<any, any, any, any, any, any> {
+  return e.type === ENDPOINT_QUERY
+}
+
+export function isMutationDefinition(
+  e: EndpointDefinition<any, any, any, any, any, any, any>,
+): e is MutationDefinition<any, any, any, any, any, any> {
+  return e.type === ENDPOINT_MUTATION
+}
+
+export function isInfiniteQueryDefinition(
+  e: EndpointDefinition<any, any, any, any, any, any, any>,
+): e is InfiniteQueryDefinition<any, any, any, any, any, any, any> {
+  return e.type === ENDPOINT_INFINITEQUERY
+}
+
+export function isAnyQueryDefinition(
+  e: EndpointDefinition<any, any, any, any>,
+): e is
+  | QueryDefinition<any, any, any, any>
+  | InfiniteQueryDefinition<any, any, any, any, any> {
+  return isQueryDefinition(e) || isInfiniteQueryDefinition(e)
+}
+
+export type EndpointBuilder<
+  BaseQuery extends BaseQueryFn,
+  TagTypes extends string,
+  ReducerPath extends string,
+> = {
+  /**
+   * An endpoint definition that retrieves data, and may provide tags to the cache.
+   *
+   * @example
+   * ```js
+   * // codeblock-meta title="Example of all query endpoint options"
+   * const api = createApi({
+   *  baseQuery,
+   *  endpoints: (build) => ({
+   *    getPost: build.query({
+   *      query: (id) => ({ url: `post/${id}` }),
+   *      // Pick out data and prevent nested properties in a hook or selector
+   *      transformResponse: (response) => response.data,
+   *      // Pick out error and prevent nested properties in a hook or selector
+   *      transformErrorResponse: (response) => response.error,
+   *      // `result` is the server response
+   *      providesTags: (result, error, id) => [{ type: 'Post', id }],
+   *      // trigger side effects or optimistic updates
+   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},
+   *      // handle subscriptions etc
+   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},
+   *    }),
+   *  }),
+   *});
+   *```
+   */
+  query<
+    ResultType,
+    QueryArg,
+    RawResultType extends
+      BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+  >(
+    definition: OmitFromUnion<
+      QueryDefinition<
+        QueryArg,
+        BaseQuery,
+        TagTypes,
+        ResultType,
+        ReducerPath,
+        RawResultType
+      >,
+      'type'
+    >,
+  ): QueryDefinition<
+    QueryArg,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath,
+    RawResultType
+  >
+
+  /**
+   * An endpoint definition that alters data on the server or will possibly invalidate the cache.
+   *
+   * @example
+   * ```js
+   * // codeblock-meta title="Example of all mutation endpoint options"
+   * const api = createApi({
+   *   baseQuery,
+   *   endpoints: (build) => ({
+   *     updatePost: build.mutation({
+   *       query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),
+   *       // Pick out data and prevent nested properties in a hook or selector
+   *       transformResponse: (response) => response.data,
+   *       // Pick out error and prevent nested properties in a hook or selector
+   *       transformErrorResponse: (response) => response.error,
+   *       // `result` is the server response
+   *       invalidatesTags: (result, error, id) => [{ type: 'Post', id }],
+   *      // trigger side effects or optimistic updates
+   *      onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},
+   *      // handle subscriptions etc
+   *      onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},
+   *     }),
+   *   }),
+   * });
+   * ```
+   */
+  mutation<
+    ResultType,
+    QueryArg,
+    RawResultType extends
+      BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+  >(
+    definition: OmitFromUnion<
+      MutationDefinition<
+        QueryArg,
+        BaseQuery,
+        TagTypes,
+        ResultType,
+        ReducerPath,
+        RawResultType
+      >,
+      'type'
+    >,
+  ): MutationDefinition<
+    QueryArg,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath,
+    RawResultType
+  >
+
+  infiniteQuery<
+    ResultType,
+    QueryArg,
+    PageParam,
+    RawResultType extends
+      BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,
+  >(
+    definition: OmitFromUnion<
+      InfiniteQueryDefinition<
+        QueryArg,
+        PageParam,
+        BaseQuery,
+        TagTypes,
+        ResultType,
+        ReducerPath,
+        RawResultType
+      >,
+      'type'
+    >,
+  ): InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    TagTypes,
+    ResultType,
+    ReducerPath,
+    RawResultType
+  >
+}
+
+export type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T
+
+export 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>[] {
+  const finalDescription = isFunction(description)
+    ? description(
+        result as ResultType,
+        error as undefined,
+        queryArg,
+        meta as MetaType,
+      )
+    : description
+
+  if (finalDescription) {
+    return filterMap(finalDescription, isNotNullish, (tag) =>
+      assertTagTypes(expandTagDescription(tag)),
+    )
+  }
+
+  return []
+}
+
+function isFunction<T>(t: T): t is Extract<T, Function> {
+  return typeof t === 'function'
+}
+
+export function expandTagDescription(
+  description: TagDescription<string>,
+): FullTagDescription<string> {
+  return typeof description === 'string' ? { type: description } : description
+}
+
+export type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> =
+  D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never
+
+// Just extracting `QueryArg` from `BaseEndpointDefinition`
+// doesn't sufficiently match here.
+// We need to explicitly match against `InfiniteQueryDefinition`
+export type InfiniteQueryArgFrom<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+> =
+  D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any>
+    ? QA
+    : never
+
+export type QueryArgFromAnyQuery<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+> =
+  D extends InfiniteQueryDefinition<any, any, any, any, any, any, any>
+    ? InfiniteQueryArgFrom<D>
+    : D extends QueryDefinition<any, any, any, any, any, any>
+      ? QueryArgFrom<D>
+      : never
+
+export type ResultTypeFrom<
+  D extends BaseEndpointDefinition<any, any, any, any>,
+> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown
+
+export type ReducerPathFrom<
+  D extends EndpointDefinition<any, any, any, any, any, any, any>,
+> =
+  D extends EndpointDefinition<any, any, any, any, infer RP, any, any>
+    ? RP
+    : unknown
+
+export type TagTypesFrom<
+  D extends EndpointDefinition<any, any, any, any, any, any, any>,
+> =
+  D extends EndpointDefinition<any, any, infer TT, any, any, any, any>
+    ? TT
+    : unknown
+
+export type PageParamFrom<
+  D extends InfiniteQueryDefinition<any, any, any, any, any, any, any>,
+> =
+  D extends InfiniteQueryDefinition<any, infer PP, any, any, any, any, any>
+    ? PP
+    : unknown
+
+export type InfiniteQueryCombinedArg<QueryArg, PageParam> = {
+  queryArg: QueryArg
+  pageParam: PageParam
+}
+
+export type TagTypesFromApi<T> =
+  T extends Api<any, any, any, infer TagTypes> ? TagTypes : never
+
+export type DefinitionsFromApi<T> =
+  T extends Api<any, infer Definitions, any, any> ? Definitions : never
+
+export type TransformedResponse<
+  NewDefinitions extends EndpointDefinitions,
+  K,
+  ResultType,
+> = K extends keyof NewDefinitions
+  ? NewDefinitions[K]['transformResponse'] extends undefined
+    ? ResultType
+    : UnwrapPromise<
+        ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>
+      >
+  : ResultType
+
+export 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
+
+export 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
+}
Index: node_modules/@reduxjs/toolkit/src/query/fakeBaseQuery.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/fakeBaseQuery.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/fakeBaseQuery.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,21 @@
+import type { BaseQueryFn } from './baseQueryTypes'
+
+export const _NEVER = /* @__PURE__ */ Symbol()
+export type NEVER = typeof _NEVER
+
+/**
+ * Creates a "fake" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.
+ * This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.
+ */
+export function fakeBaseQuery<ErrorType>(): BaseQueryFn<
+  void,
+  NEVER,
+  ErrorType,
+  {}
+> {
+  return function () {
+    throw new Error(
+      'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.',
+    )
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/fetchBaseQuery.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/fetchBaseQuery.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/fetchBaseQuery.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,385 @@
+import { joinUrls } from './utils'
+import { isPlainObject } from './core/rtkImports'
+import type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes'
+import type { MaybePromise, Override } from './tsHelpers'
+import { anySignal, timeoutSignal } from './utils/signals'
+
+export type ResponseHandler =
+  | 'content-type'
+  | 'json'
+  | 'text'
+  | ((response: Response) => Promise<any>)
+
+type CustomRequestInit = Override<
+  RequestInit,
+  {
+    headers?:
+      | Headers
+      | string[][]
+      | Record<string, string | undefined>
+      | undefined
+  }
+>
+
+export interface FetchArgs extends CustomRequestInit {
+  url: string
+  params?: Record<string, any>
+  body?: any
+  responseHandler?: ResponseHandler
+  validateStatus?: (response: Response, body: any) => boolean
+  /**
+   * A number in milliseconds that represents that maximum time a request can take before timing out.
+   */
+  timeout?: number
+}
+
+/**
+ * A mini-wrapper that passes arguments straight through to
+ * {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.
+ * Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.
+ */
+const defaultFetchFn: typeof fetch = (...args) => fetch(...args)
+
+const defaultValidateStatus = (response: Response) =>
+  response.status >= 200 && response.status <= 299
+
+const defaultIsJsonContentType = (headers: Headers) =>
+  /*applicat*/ /ion\/(vnd\.api\+)?json/.test(headers.get('content-type') || '')
+
+export type FetchBaseQueryError =
+  | {
+      /**
+       * * `number`:
+       *   HTTP status code
+       */
+      status: number
+      data: unknown
+    }
+  | {
+      /**
+       * * `"FETCH_ERROR"`:
+       *   An error that occurred during execution of `fetch` or the `fetchFn` callback option
+       **/
+      status: 'FETCH_ERROR'
+      data?: undefined
+      error: string
+    }
+  | {
+      /**
+       * * `"PARSING_ERROR"`:
+       *   An error happened during parsing.
+       *   Most likely a non-JSON-response was returned with the default `responseHandler` "JSON",
+       *   or an error occurred while executing a custom `responseHandler`.
+       **/
+      status: 'PARSING_ERROR'
+      originalStatus: number
+      data: string
+      error: string
+    }
+  | {
+      /**
+       * * `"TIMEOUT_ERROR"`:
+       *   Request timed out
+       **/
+      status: 'TIMEOUT_ERROR'
+      data?: undefined
+      error: string
+    }
+  | {
+      /**
+       * * `"CUSTOM_ERROR"`:
+       *   A custom error type that you can return from your `queryFn` where another error might not make sense.
+       **/
+      status: 'CUSTOM_ERROR'
+      data?: unknown
+      error: string
+    }
+
+function stripUndefined(obj: any) {
+  if (!isPlainObject(obj)) {
+    return obj
+  }
+  const copy: Record<string, any> = { ...obj }
+  for (const [k, v] of Object.entries(copy)) {
+    if (v === undefined) delete copy[k]
+  }
+  return copy
+}
+
+// Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc.
+const isJsonifiable = (body: any) =>
+  typeof body === 'object' &&
+  (isPlainObject(body) ||
+    Array.isArray(body) ||
+    typeof body.toJSON === 'function')
+
+export type FetchBaseQueryArgs = {
+  baseUrl?: string
+  prepareHeaders?: (
+    headers: Headers,
+    api: Pick<
+      BaseQueryApi,
+      'getState' | 'extra' | 'endpoint' | 'type' | 'forced'
+    > & { arg: string | FetchArgs; extraOptions: unknown },
+  ) => MaybePromise<Headers | void>
+  fetchFn?: (
+    input: RequestInfo,
+    init?: RequestInit | undefined,
+  ) => Promise<Response>
+  paramsSerializer?: (params: Record<string, any>) => string
+  /**
+   * 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
+   * in a predicate function for your given api to get the same automatic stringifying behavior
+   * @example
+   * ```ts
+   * const isJsonContentType = (headers: Headers) => ["application/vnd.api+json", "application/json", "application/vnd.hal+json"].includes(headers.get("content-type")?.trim());
+   * ```
+   */
+  isJsonContentType?: (headers: Headers) => boolean
+  /**
+   * Defaults to `application/json`;
+   */
+  jsonContentType?: string
+
+  /**
+   * Custom replacer function used when calling `JSON.stringify()`;
+   */
+  jsonReplacer?: (this: any, key: string, value: any) => any
+} & RequestInit &
+  Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>
+
+export type FetchBaseQueryMeta = { request: Request; response?: Response }
+
+/**
+ * This is a very small wrapper around fetch that aims to simplify requests.
+ *
+ * @example
+ * ```ts
+ * const baseQuery = fetchBaseQuery({
+ *   baseUrl: 'https://api.your-really-great-app.com/v1/',
+ *   prepareHeaders: (headers, { getState }) => {
+ *     const token = (getState() as RootState).auth.token;
+ *     // If we have a token set in state, let's assume that we should be passing it.
+ *     if (token) {
+ *       headers.set('authorization', `Bearer ${token}`);
+ *     }
+ *     return headers;
+ *   },
+ * })
+ * ```
+ *
+ * @param {string} baseUrl
+ * The base URL for an API service.
+ * Typically in the format of https://example.com/
+ *
+ * @param {(headers: Headers, api: { getState: () => unknown; arg: string | FetchArgs; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders
+ * An optional function that can be used to inject headers on requests.
+ * Provides a Headers object, most of the `BaseQueryApi` (`dispatch` is not available), and the arg passed into the query function.
+ * Useful for setting authentication or headers that need to be set conditionally.
+ *
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/Headers
+ *
+ * @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn
+ * Accepts a custom `fetch` function if you do not want to use the default on the window.
+ * Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`
+ *
+ * @param {(params: Record<string, unknown>) => string} paramsSerializer
+ * An optional function that can be used to stringify querystring parameters.
+ *
+ * @param {(headers: Headers) => boolean} isJsonContentType
+ * An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`
+ *
+ * @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`.
+ *
+ * @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.
+ *
+ * @param {number} timeout
+ * A number in milliseconds that represents the maximum time a request can take before timing out.
+ */
+
+export function fetchBaseQuery({
+  baseUrl,
+  prepareHeaders = (x) => x,
+  fetchFn = defaultFetchFn,
+  paramsSerializer,
+  isJsonContentType = defaultIsJsonContentType,
+  jsonContentType = 'application/json',
+  jsonReplacer,
+  timeout: defaultTimeout,
+  responseHandler: globalResponseHandler,
+  validateStatus: globalValidateStatus,
+  ...baseFetchOptions
+}: FetchBaseQueryArgs = {}): BaseQueryFn<
+  string | FetchArgs,
+  unknown,
+  FetchBaseQueryError,
+  {},
+  FetchBaseQueryMeta
+> {
+  if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {
+    console.warn(
+      'Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.',
+    )
+  }
+  return async (arg, api, extraOptions) => {
+    const { getState, extra, endpoint, forced, type } = api
+    let meta: FetchBaseQueryMeta | undefined
+    let {
+      url,
+      headers = new Headers(baseFetchOptions.headers),
+      params = undefined,
+      responseHandler = globalResponseHandler ?? ('json' as const),
+      validateStatus = globalValidateStatus ?? defaultValidateStatus,
+      timeout = defaultTimeout,
+      ...rest
+    } = typeof arg == 'string' ? { url: arg } : arg
+
+    let config: RequestInit = {
+      ...baseFetchOptions,
+      signal: timeout
+        ? anySignal(api.signal, timeoutSignal(timeout))
+        : api.signal,
+      ...rest,
+    }
+
+    headers = new Headers(stripUndefined(headers))
+    config.headers =
+      (await prepareHeaders(headers, {
+        getState,
+        arg,
+        extra,
+        endpoint,
+        forced,
+        type,
+        extraOptions,
+      })) || headers
+
+    const bodyIsJsonifiable = isJsonifiable(config.body)
+
+    // Remove content-type for non-jsonifiable bodies to let the browser set it automatically
+    // Exception: keep content-type for string bodies as they might be intentional (text/plain, text/html, etc.)
+    if (
+      config.body != null &&
+      !bodyIsJsonifiable &&
+      typeof config.body !== 'string'
+    ) {
+      config.headers.delete('content-type')
+    }
+
+    if (!config.headers.has('content-type') && bodyIsJsonifiable) {
+      config.headers.set('content-type', jsonContentType)
+    }
+
+    if (bodyIsJsonifiable && isJsonContentType(config.headers)) {
+      config.body = JSON.stringify(config.body, jsonReplacer)
+    }
+
+    // Set Accept header based on responseHandler if not already set
+    if (!config.headers.has('accept')) {
+      if (responseHandler === 'json') {
+        config.headers.set('accept', 'application/json')
+      } else if (responseHandler === 'text') {
+        config.headers.set('accept', 'text/plain, text/html, */*')
+      }
+      // For 'content-type' responseHandler, don't set Accept (let server decide)
+    }
+
+    if (params) {
+      const divider = ~url.indexOf('?') ? '&' : '?'
+      const query = paramsSerializer
+        ? paramsSerializer(params)
+        : new URLSearchParams(stripUndefined(params))
+      url += divider + query
+    }
+
+    url = joinUrls(baseUrl, url)
+
+    const request = new Request(url, config)
+    const requestClone = new Request(url, config)
+    meta = { request: requestClone }
+
+    let response
+    try {
+      response = await fetchFn(request)
+    } catch (e) {
+      return {
+        error: {
+          status:
+            (e instanceof Error ||
+              (typeof DOMException !== 'undefined' &&
+                e instanceof DOMException)) &&
+            e.name === 'TimeoutError'
+              ? 'TIMEOUT_ERROR'
+              : 'FETCH_ERROR',
+          error: String(e),
+        },
+        meta,
+      }
+    }
+    const responseClone = response.clone()
+
+    meta.response = responseClone
+
+    let resultData: any
+    let responseText: string = ''
+    try {
+      let handleResponseError
+      await Promise.all([
+        handleResponse(response, responseHandler).then(
+          (r) => (resultData = r),
+          (e) => (handleResponseError = e),
+        ),
+        // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182
+        // we *have* to "use up" both streams at the same time or they will stop running in node-fetch scenarios
+        responseClone.text().then(
+          (r) => (responseText = r),
+          () => {},
+        ),
+      ])
+      if (handleResponseError) throw handleResponseError
+    } catch (e) {
+      return {
+        error: {
+          status: 'PARSING_ERROR',
+          originalStatus: response.status,
+          data: responseText,
+          error: String(e),
+        },
+        meta,
+      }
+    }
+
+    return validateStatus(response, resultData)
+      ? {
+          data: resultData,
+          meta,
+        }
+      : {
+          error: {
+            status: response.status,
+            data: resultData,
+          },
+          meta,
+        }
+  }
+
+  async function handleResponse(
+    response: Response,
+    responseHandler: ResponseHandler,
+  ) {
+    if (typeof responseHandler === 'function') {
+      return responseHandler(response)
+    }
+
+    if (responseHandler === 'content-type') {
+      responseHandler = isJsonContentType(response.headers) ? 'json' : 'text'
+    }
+
+    if (responseHandler === 'json') {
+      const text = await response.text()
+      return text.length ? JSON.parse(text) : null
+    }
+
+    return response.text()
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,106 @@
+// This must remain here so that the `mangleErrors.cjs` build script
+// does not have to import this into each source file it rewrites.
+import { formatProdErrorMessage } from '@reduxjs/toolkit'
+
+export type {
+  CombinedState,
+  QueryCacheKey,
+  QueryKeys,
+  QuerySubState,
+  RootState,
+  SubscriptionOptions,
+} from './core/apiState'
+export { QueryStatus } from './core/apiState'
+export type { Api, ApiContext, Module } from './apiTypes'
+
+export type {
+  BaseQueryApi,
+  BaseQueryArg,
+  BaseQueryEnhancer,
+  BaseQueryError,
+  BaseQueryExtraOptions,
+  BaseQueryFn,
+  BaseQueryMeta,
+  BaseQueryResult,
+  QueryReturnValue,
+} from './baseQueryTypes'
+export type {
+  BaseEndpointDefinition,
+  EndpointDefinitions,
+  EndpointDefinition,
+  EndpointBuilder,
+  QueryDefinition,
+  MutationDefinition,
+  MutationExtraOptions,
+  InfiniteQueryArgFrom,
+  InfiniteQueryDefinition,
+  InfiniteQueryExtraOptions,
+  PageParamFrom,
+  TagDescription,
+  QueryArgFrom,
+  QueryExtraOptions,
+  ResultTypeFrom,
+  DefinitionType,
+  DefinitionsFromApi,
+  OverrideResultType,
+  ResultDescription,
+  TagTypesFromApi,
+  UpdateDefinitions,
+  SchemaFailureHandler,
+  SchemaFailureConverter,
+  SchemaFailureInfo,
+  SchemaType,
+} from './endpointDefinitions'
+export { fetchBaseQuery } from './fetchBaseQuery'
+export type {
+  FetchBaseQueryArgs,
+  FetchBaseQueryError,
+  FetchBaseQueryMeta,
+  FetchArgs,
+} from './fetchBaseQuery'
+export { retry } from './retry'
+export type { RetryOptions } from './retry'
+export { setupListeners } from './core/setupListeners'
+export { skipToken } from './core/buildSelectors'
+export type {
+  QueryResultSelectorResult,
+  MutationResultSelectorResult,
+  SkipToken,
+} from './core/buildSelectors'
+export type {
+  QueryActionCreatorResult,
+  MutationActionCreatorResult,
+  StartQueryActionCreatorOptions,
+} from './core/buildInitiate'
+export type { CreateApi, CreateApiOptions } from './createApi'
+export { buildCreateApi } from './createApi'
+export { _NEVER, fakeBaseQuery } from './fakeBaseQuery'
+export { copyWithStructuralSharing } from './utils/copyWithStructuralSharing'
+export { createApi, coreModule, coreModuleName } from './core/index'
+export type {
+  InfiniteData,
+  InfiniteQueryActionCreatorResult,
+  InfiniteQueryConfigOptions,
+  InfiniteQueryResultSelectorResult,
+  InfiniteQuerySubState,
+  TypedMutationOnQueryStarted,
+  TypedQueryOnQueryStarted,
+} from './core/index'
+export type {
+  ApiEndpointMutation,
+  ApiEndpointQuery,
+  ApiEndpointInfiniteQuery,
+  ApiModules,
+  CoreModule,
+  PrefetchOptions,
+} from './core/module'
+export { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs'
+export type { SerializeQueryArgs } from './defaultSerializeQueryArgs'
+
+export type {
+  Id as TSHelpersId,
+  NoInfer as TSHelpersNoInfer,
+  Override as TSHelpersOverride,
+} from './tsHelpers'
+
+export { NamedSchemaError } from './standardSchema'
Index: node_modules/@reduxjs/toolkit/src/query/react/ApiProvider.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/ApiProvider.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/ApiProvider.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,69 @@
+import { configureStore } from '@reduxjs/toolkit'
+import type { Context } from 'react'
+import { useContext, useEffect } from './reactImports'
+import * as React from 'react'
+import type { ReactReduxContextValue } from 'react-redux'
+import { Provider, ReactReduxContext } from './reactReduxImports'
+import { setupListeners } from './rtkqImports'
+import type { Api } from '@reduxjs/toolkit/query'
+
+/**
+ * Can be used as a `Provider` if you **do not already have a Redux store**.
+ *
+ * @example
+ * ```tsx
+ * // codeblock-meta no-transpile title="Basic usage - wrap your App with ApiProvider"
+ * import * as React from 'react';
+ * import { ApiProvider } from '@reduxjs/toolkit/query/react';
+ * import { Pokemon } from './features/Pokemon';
+ *
+ * function App() {
+ *   return (
+ *     <ApiProvider api={api}>
+ *       <Pokemon />
+ *     </ApiProvider>
+ *   );
+ * }
+ * ```
+ *
+ * @remarks
+ * Using this together with an existing redux store, both will
+ * conflict with each other - please use the traditional redux setup
+ * in that case.
+ */
+export function ApiProvider(props: {
+  children: any
+  api: Api<any, {}, any, any>
+  setupListeners?: Parameters<typeof setupListeners>[1] | false
+  context?: Context<ReactReduxContextValue | null>
+}) {
+  const context = props.context || ReactReduxContext
+  const existingContext = useContext(context)
+  if (existingContext) {
+    throw new Error(
+      'Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.',
+    )
+  }
+  const [store] = React.useState(() =>
+    configureStore({
+      reducer: {
+        [props.api.reducerPath]: props.api.reducer,
+      },
+      middleware: (gDM) => gDM().concat(props.api.middleware),
+    }),
+  )
+  // Adds the event listeners for online/offline/focus/etc
+  useEffect(
+    (): undefined | (() => void) =>
+      props.setupListeners === false
+        ? undefined
+        : setupListeners(store.dispatch, props.setupListeners),
+    [props.setupListeners, store.dispatch],
+  )
+
+  return (
+    <Provider store={store} context={context}>
+      {props.children}
+    </Provider>
+  )
+}
Index: node_modules/@reduxjs/toolkit/src/query/react/buildHooks.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/buildHooks.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/buildHooks.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2258 @@
+import type {
+  Selector,
+  ThunkAction,
+  ThunkDispatch,
+  UnknownAction,
+} from '@reduxjs/toolkit'
+import type {
+  Api,
+  ApiContext,
+  ApiEndpointInfiniteQuery,
+  ApiEndpointMutation,
+  ApiEndpointQuery,
+  BaseQueryFn,
+  CoreModule,
+  EndpointDefinitions,
+  InfiniteQueryActionCreatorResult,
+  InfiniteQueryArgFrom,
+  InfiniteQueryDefinition,
+  InfiniteQueryResultSelectorResult,
+  InfiniteQuerySubState,
+  MutationActionCreatorResult,
+  MutationDefinition,
+  MutationResultSelectorResult,
+  PageParamFrom,
+  PrefetchOptions,
+  QueryActionCreatorResult,
+  QueryArgFrom,
+  QueryCacheKey,
+  QueryDefinition,
+  QueryKeys,
+  QueryResultSelectorResult,
+  QuerySubState,
+  ResultTypeFrom,
+  RootState,
+  SerializeQueryArgs,
+  SkipToken,
+  SubscriptionOptions,
+  TSHelpersId,
+  TSHelpersNoInfer,
+  TSHelpersOverride,
+} from '@reduxjs/toolkit/query'
+import { QueryStatus, skipToken } from './rtkqImports'
+import type { DependencyList } from 'react'
+import {
+  useCallback,
+  useDebugValue,
+  useEffect,
+  useLayoutEffect,
+  useMemo,
+  useRef,
+  useState,
+} from './reactImports'
+import { shallowEqual } from './reactReduxImports'
+
+import type { SubscriptionSelectors } from '../core/buildMiddleware/index'
+import type { InfiniteData, InfiniteQueryConfigOptions } from '../core/index'
+import type { UninitializedValue } from './constants'
+import { UNINITIALIZED_VALUE } from './constants'
+import type { ReactHooksModuleOptions } from './module'
+import { useStableQueryArgs } from './useSerializedStableValue'
+import { useShallowStableValue } from './useShallowStableValue'
+import type { InfiniteQueryDirection } from '../core/apiState'
+import { isInfiniteQueryDefinition } from '../endpointDefinitions'
+import type { StartInfiniteQueryActionCreator } from '../core/buildInitiate'
+
+// Copy-pasted from React-Redux
+const canUseDOM = () =>
+  !!(
+    typeof window !== 'undefined' &&
+    typeof window.document !== 'undefined' &&
+    typeof window.document.createElement !== 'undefined'
+  )
+
+const isDOM = /* @__PURE__ */ canUseDOM()
+
+// Under React Native, we know that we always want to use useLayoutEffect
+
+const isRunningInReactNative = () =>
+  typeof navigator !== 'undefined' && navigator.product === 'ReactNative'
+
+const isReactNative = /* @__PURE__ */ isRunningInReactNative()
+
+const getUseIsomorphicLayoutEffect = () =>
+  isDOM || isReactNative ? useLayoutEffect : useEffect
+
+export const useIsomorphicLayoutEffect =
+  /* @__PURE__ */ getUseIsomorphicLayoutEffect()
+
+export type QueryHooks<
+  Definition extends QueryDefinition<any, any, any, any, any>,
+> = {
+  useQuery: UseQuery<Definition>
+  useLazyQuery: UseLazyQuery<Definition>
+  useQuerySubscription: UseQuerySubscription<Definition>
+  useLazyQuerySubscription: UseLazyQuerySubscription<Definition>
+  useQueryState: UseQueryState<Definition>
+}
+
+export type InfiniteQueryHooks<
+  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = {
+  useInfiniteQuery: UseInfiniteQuery<Definition>
+  useInfiniteQuerySubscription: UseInfiniteQuerySubscription<Definition>
+  useInfiniteQueryState: UseInfiniteQueryState<Definition>
+}
+
+export type MutationHooks<
+  Definition extends MutationDefinition<any, any, any, any, any>,
+> = {
+  useMutation: UseMutation<Definition>
+}
+
+/**
+ * A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
+ *
+ * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.
+ *
+ * This hook combines the functionality of both [`useQueryState`](#usequerystate) and [`useQuerySubscription`](#usequerysubscription) together, and is intended to be used in the majority of situations.
+ *
+ * #### Features
+ *
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
+ * - Returns the latest request status and cached data from the Redux store
+ * - Re-renders as the request status changes and data becomes available
+ */
+export type UseQuery<D extends QueryDefinition<any, any, any, any>> = <
+  R extends Record<string, any> = UseQueryStateDefaultResult<D>,
+>(
+  arg: QueryArgFrom<D> | SkipToken,
+  options?: UseQuerySubscriptionOptions & UseQueryStateOptions<D, R>,
+) => UseQueryHookResult<D, R>
+
+export type TypedUseQuery<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = UseQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>
+
+export type UseQueryHookResult<
+  D extends QueryDefinition<any, any, any, any>,
+  R = UseQueryStateDefaultResult<D>,
+> = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>
+
+/**
+ * Helper type to manually type the result
+ * of the `useQuery` hook in userland code.
+ */
+export type TypedUseQueryHookResult<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  R = UseQueryStateDefaultResult<
+    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+  >,
+> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> &
+  TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>
+
+export type UseQuerySubscriptionOptions = SubscriptionOptions & {
+  /**
+   * Prevents a query from automatically running.
+   *
+   * @remarks
+   * When `skip` is true (or `skipToken` is passed in as `arg`):
+   *
+   * - **If the query has cached data:**
+   *   * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
+   *   * The query will have a status of `uninitialized`
+   *   * If `skip: false` is set after the initial load, the cached result will be used
+   * - **If the query does not have cached data:**
+   *   * The query will have a status of `uninitialized`
+   *   * The query will not exist in the state when viewed with the dev tools
+   *   * The query will not automatically fetch on mount
+   *   * The query will not automatically run when additional components with the same query are added that do run
+   *
+   * @example
+   * ```tsx
+   * // codeblock-meta no-transpile title="Skip example"
+   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
+   *   const { data, error, status } = useGetPokemonByNameQuery(name, {
+   *     skip,
+   *   });
+   *
+   *   return (
+   *     <div>
+   *       {name} - {status}
+   *     </div>
+   *   );
+   * };
+   * ```
+   */
+  skip?: boolean
+  /**
+   * 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.
+   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
+   * - `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.
+   * - `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.
+   *
+   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
+   */
+  refetchOnMountOrArgChange?: boolean | number
+}
+
+/**
+ * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.
+ *
+ * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.
+ *
+ * Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).
+ *
+ * #### Features
+ *
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
+ */
+export type UseQuerySubscription<
+  D extends QueryDefinition<any, any, any, any>,
+> = (
+  arg: QueryArgFrom<D> | SkipToken,
+  options?: UseQuerySubscriptionOptions,
+) => UseQuerySubscriptionResult<D>
+
+export type TypedUseQuerySubscription<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = UseQuerySubscription<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+export type UseQuerySubscriptionResult<
+  D extends QueryDefinition<any, any, any, any>,
+> = Pick<QueryActionCreatorResult<D>, 'refetch'>
+
+/**
+ * Helper type to manually type the result
+ * of the `useQuerySubscription` hook in userland code.
+ */
+export type TypedUseQuerySubscriptionResult<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = UseQuerySubscriptionResult<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+export type UseLazyQueryLastPromiseInfo<
+  D extends QueryDefinition<any, any, any, any>,
+> = {
+  lastArg: QueryArgFrom<D>
+}
+
+/**
+ * A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.
+ *
+ * This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).
+ *
+ * #### Features
+ *
+ * - Manual control over firing a request to retrieve data
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
+ * - Returns the latest request status and cached data from the Redux store
+ * - Re-renders as the request status changes and data becomes available
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
+ *
+ * #### Note
+ *
+ * When the trigger function returned from a LazyQuery is called, it always initiates a new request to the server even if there is cached data. Set `preferCacheValue`(the second argument to the function) as `true` if you want it to immediately return a cached value if one exists.
+ */
+export type UseLazyQuery<D extends QueryDefinition<any, any, any, any>> = <
+  R extends Record<string, any> = UseQueryStateDefaultResult<D>,
+>(
+  options?: SubscriptionOptions & Omit<UseQueryStateOptions<D, R>, 'skip'>,
+) => [
+  LazyQueryTrigger<D>,
+  UseLazyQueryStateResult<D, R>,
+  UseLazyQueryLastPromiseInfo<D>,
+]
+
+export type TypedUseLazyQuery<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = UseLazyQuery<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+export type UseLazyQueryStateResult<
+  D extends QueryDefinition<any, any, any, any>,
+  R = UseQueryStateDefaultResult<D>,
+> = UseQueryStateResult<D, R> & {
+  /**
+   * Resets the hook state to its initial `uninitialized` state.
+   * This will also remove the last result from the cache.
+   */
+  reset: () => void
+}
+
+/**
+ * Helper type to manually type the result
+ * of the `useLazyQuery` hook in userland code.
+ */
+export type TypedUseLazyQueryStateResult<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  R = UseQueryStateDefaultResult<
+    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+  >,
+> = UseLazyQueryStateResult<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>,
+  R
+>
+
+export type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {
+  /**
+   * Triggers a lazy query.
+   *
+   * By default, this will start a new request even if there is already a value in the cache.
+   * If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.
+   *
+   * @remarks
+   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Using .unwrap with async await"
+   * try {
+   *   const payload = await getUserById(1).unwrap();
+   *   console.log('fulfilled', payload)
+   * } catch (error) {
+   *   console.error('rejected', error);
+   * }
+   * ```
+   */
+  (
+    arg: QueryArgFrom<D>,
+    preferCacheValue?: boolean,
+  ): QueryActionCreatorResult<D>
+}
+
+export type TypedLazyQueryTrigger<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = LazyQueryTrigger<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+/**
+ * A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.
+ *
+ * Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).
+ *
+ * #### Features
+ *
+ * - Manual control over firing a request to retrieve data
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
+ */
+export type UseLazyQuerySubscription<
+  D extends QueryDefinition<any, any, any, any>,
+> = (
+  options?: SubscriptionOptions,
+) => readonly [
+  LazyQueryTrigger<D>,
+  QueryArgFrom<D> | UninitializedValue,
+  { reset: () => void },
+]
+
+export type TypedUseLazyQuerySubscription<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = UseLazyQuerySubscription<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+/**
+ * @internal
+ */
+export type QueryStateSelector<
+  R extends Record<string, any>,
+  D extends QueryDefinition<any, any, any, any>,
+> = (state: UseQueryStateDefaultResult<D>) => R
+
+/**
+ * Provides a way to define a strongly-typed version of
+ * {@linkcode QueryStateSelector} for use with a specific query.
+ * This is useful for scenarios where you want to create a "pre-typed"
+ * {@linkcode UseQueryStateOptions.selectFromResult | selectFromResult}
+ * function.
+ *
+ * @example
+ * <caption>#### __Create a strongly-typed `selectFromResult` selector function__</caption>
+ *
+ * ```tsx
+ * import type { TypedQueryStateSelector } from '@reduxjs/toolkit/query/react'
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+ *
+ * type Post = {
+ *   id: number
+ *   title: string
+ * }
+ *
+ * type PostsApiResponse = {
+ *   posts: Post[]
+ *   total: number
+ *   skip: number
+ *   limit: number
+ * }
+ *
+ * type QueryArgument = number | undefined
+ *
+ * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
+ *
+ * type SelectedResult = Pick<PostsApiResponse, 'posts'>
+ *
+ * const postsApiSlice = createApi({
+ *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),
+ *   reducerPath: 'postsApi',
+ *   tagTypes: ['Posts'],
+ *   endpoints: (build) => ({
+ *     getPosts: build.query<PostsApiResponse, QueryArgument>({
+ *       query: (limit = 5) => `?limit=${limit}&select=title`,
+ *     }),
+ *   }),
+ * })
+ *
+ * const { useGetPostsQuery } = postsApiSlice
+ *
+ * function PostById({ id }: { id: number }) {
+ *   const { post } = useGetPostsQuery(undefined, {
+ *     selectFromResult: (state) => ({
+ *       post: state.data?.posts.find((post) => post.id === id),
+ *     }),
+ *   })
+ *
+ *   return <li>{post?.title}</li>
+ * }
+ *
+ * const EMPTY_ARRAY: Post[] = []
+ *
+ * const typedSelectFromResult: TypedQueryStateSelector<
+ *   PostsApiResponse,
+ *   QueryArgument,
+ *   BaseQueryFunction,
+ *   SelectedResult
+ * > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })
+ *
+ * function PostsList() {
+ *   const { posts } = useGetPostsQuery(undefined, {
+ *     selectFromResult: typedSelectFromResult,
+ *   })
+ *
+ *   return (
+ *     <div>
+ *       <ul>
+ *         {posts.map((post) => (
+ *           <PostById key={post.id} id={post.id} />
+ *         ))}
+ *       </ul>
+ *     </div>
+ *   )
+ * }
+ * ```
+ *
+ * @template ResultType - The type of the result `data` returned by the query.
+ * @template QueryArgumentType - The type of the argument passed into the query.
+ * @template BaseQueryFunctionType - The type of the base query function being used.
+ * @template SelectedResultType - The type of the selected result returned by the __`selectFromResult`__ function.
+ *
+ * @since 2.3.0
+ * @public
+ */
+export type TypedQueryStateSelector<
+  ResultType,
+  QueryArgumentType,
+  BaseQueryFunctionType extends BaseQueryFn,
+  SelectedResultType extends Record<string, any> = UseQueryStateDefaultResult<
+    QueryDefinition<
+      QueryArgumentType,
+      BaseQueryFunctionType,
+      string,
+      ResultType,
+      string
+    >
+  >,
+> = QueryStateSelector<
+  SelectedResultType,
+  QueryDefinition<
+    QueryArgumentType,
+    BaseQueryFunctionType,
+    string,
+    ResultType,
+    string
+  >
+>
+
+/**
+ * A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
+ *
+ * Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).
+ *
+ * #### Features
+ *
+ * - Returns the latest request status and cached data from the Redux store
+ * - Re-renders as the request status changes and data becomes available
+ */
+export type UseQueryState<D extends QueryDefinition<any, any, any, any>> = <
+  R extends Record<string, any> = UseQueryStateDefaultResult<D>,
+>(
+  arg: QueryArgFrom<D> | SkipToken,
+  options?: UseQueryStateOptions<D, R>,
+) => UseQueryStateResult<D, R>
+
+export type TypedUseQueryState<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = UseQueryState<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+/**
+ * @internal
+ */
+export type UseQueryStateOptions<
+  D extends QueryDefinition<any, any, any, any>,
+  R extends Record<string, any>,
+> = {
+  /**
+   * Prevents a query from automatically running.
+   *
+   * @remarks
+   * When skip is true:
+   *
+   * - **If the query has cached data:**
+   *   * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
+   *   * The query will have a status of `uninitialized`
+   *   * If `skip: false` is set after skipping the initial load, the cached result will be used
+   * - **If the query does not have cached data:**
+   *   * The query will have a status of `uninitialized`
+   *   * The query will not exist in the state when viewed with the dev tools
+   *   * The query will not automatically fetch on mount
+   *   * The query will not automatically run when additional components with the same query are added that do run
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Skip example"
+   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
+   *   const { data, error, status } = useGetPokemonByNameQuery(name, {
+   *     skip,
+   *   });
+   *
+   *   return (
+   *     <div>
+   *       {name} - {status}
+   *     </div>
+   *   );
+   * };
+   * ```
+   */
+  skip?: boolean
+  /**
+   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.
+   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.
+   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Using selectFromResult to extract a single result"
+   * function PostsList() {
+   *   const { data: posts } = api.useGetPostsQuery();
+   *
+   *   return (
+   *     <ul>
+   *       {posts?.data?.map((post) => (
+   *         <PostById key={post.id} id={post.id} />
+   *       ))}
+   *     </ul>
+   *   );
+   * }
+   *
+   * function PostById({ id }: { id: number }) {
+   *   // Will select the post with the given id, and will only rerender if the given posts data changes
+   *   const { post } = api.useGetPostsQuery(undefined, {
+   *     selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),
+   *   });
+   *
+   *   return <li>{post?.name}</li>;
+   * }
+   * ```
+   */
+  selectFromResult?: QueryStateSelector<R, D>
+}
+
+/**
+ * Provides a way to define a "pre-typed" version of
+ * {@linkcode UseQueryStateOptions} with specific options for a given query.
+ * This is particularly useful for setting default query behaviors such as
+ * refetching strategies, which can be overridden as needed.
+ *
+ * @example
+ * <caption>#### __Create a `useQuery` hook with default options__</caption>
+ *
+ * ```ts
+ * import type {
+ *   SubscriptionOptions,
+ *   TypedUseQueryStateOptions,
+ * } from '@reduxjs/toolkit/query/react'
+ * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+ *
+ * type Post = {
+ *   id: number
+ *   name: string
+ * }
+ *
+ * const api = createApi({
+ *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),
+ *   tagTypes: ['Post'],
+ *   endpoints: (build) => ({
+ *     getPosts: build.query<Post[], void>({
+ *       query: () => 'posts',
+ *     }),
+ *   }),
+ * })
+ *
+ * const { useGetPostsQuery } = api
+ *
+ * export const useGetPostsQueryWithDefaults = <
+ *   SelectedResult extends Record<string, any>,
+ * >(
+ *   overrideOptions: TypedUseQueryStateOptions<
+ *     Post[],
+ *     void,
+ *     ReturnType<typeof fetchBaseQuery>,
+ *     SelectedResult
+ *   > &
+ *     SubscriptionOptions,
+ * ) =>
+ *   useGetPostsQuery(undefined, {
+ *     // Insert default options here
+ *
+ *     refetchOnMountOrArgChange: true,
+ *     refetchOnFocus: true,
+ *     ...overrideOptions,
+ *   })
+ * ```
+ *
+ * @template ResultType - The type of the result `data` returned by the query.
+ * @template QueryArg - The type of the argument passed into the query.
+ * @template BaseQuery - The type of the base query function being used.
+ * @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.
+ *
+ * @since 2.2.8
+ * @public
+ */
+export type TypedUseQueryStateOptions<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  SelectedResult extends Record<string, any> = UseQueryStateDefaultResult<
+    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+  >,
+> = UseQueryStateOptions<
+  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>,
+  SelectedResult
+>
+
+export type UseQueryStateResult<
+  _ extends QueryDefinition<any, any, any, any>,
+  R,
+> = TSHelpersNoInfer<R>
+
+/**
+ * Helper type to manually type the result
+ * of the `useQueryState` hook in userland code.
+ */
+export type TypedUseQueryStateResult<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  R = UseQueryStateDefaultResult<
+    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>
+  >,
+> = TSHelpersNoInfer<R>
+
+type UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> =
+  QuerySubState<D> & {
+    /**
+     * Where `data` tries to hold data as much as possible, also re-using
+     * data from the last arguments passed into the hook, this property
+     * will always contain the received data from the query, for the current query arguments.
+     */
+    currentData?: ResultTypeFrom<D>
+    /**
+     * Query has not started yet.
+     */
+    isUninitialized: false
+    /**
+     * Query is currently loading for the first time. No data yet.
+     */
+    isLoading: false
+    /**
+     * Query is currently fetching, but might have data from an earlier request.
+     */
+    isFetching: false
+    /**
+     * Query has data from a successful load.
+     */
+    isSuccess: false
+    /**
+     * Query is currently in "error" state.
+     */
+    isError: false
+  }
+
+type UseQueryStateUninitialized<D extends QueryDefinition<any, any, any, any>> =
+  TSHelpersOverride<
+    Extract<UseQueryStateBaseResult<D>, { status: QueryStatus.uninitialized }>,
+    { isUninitialized: true }
+  >
+
+type UseQueryStateLoading<D extends QueryDefinition<any, any, any, any>> =
+  TSHelpersOverride<
+    UseQueryStateBaseResult<D>,
+    { isLoading: true; isFetching: boolean; data: undefined }
+  >
+
+type UseQueryStateSuccessFetching<
+  D extends QueryDefinition<any, any, any, any>,
+> = TSHelpersOverride<
+  UseQueryStateBaseResult<D>,
+  {
+    isSuccess: true
+    isFetching: true
+    error: undefined
+  } & {
+    data: ResultTypeFrom<D>
+  } & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>
+>
+
+type UseQueryStateSuccessNotFetching<
+  D extends QueryDefinition<any, any, any, any>,
+> = TSHelpersOverride<
+  UseQueryStateBaseResult<D>,
+  {
+    isSuccess: true
+    isFetching: false
+    error: undefined
+  } & {
+    data: ResultTypeFrom<D>
+    currentData: ResultTypeFrom<D>
+  } & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>
+>
+
+type UseQueryStateError<D extends QueryDefinition<any, any, any, any>> =
+  TSHelpersOverride<
+    UseQueryStateBaseResult<D>,
+    { isError: true } & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>
+  >
+
+type UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> =
+  TSHelpersId<
+    | UseQueryStateUninitialized<D>
+    | UseQueryStateLoading<D>
+    | UseQueryStateSuccessFetching<D>
+    | UseQueryStateSuccessNotFetching<D>
+    | UseQueryStateError<D>
+  > & {
+    /**
+     * @deprecated Included for completeness, but discouraged.
+     * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
+     * and `isUninitialized` flags instead
+     */
+    status: QueryStatus
+  }
+
+export type LazyInfiniteQueryTrigger<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = {
+  /**
+   * Triggers a lazy query.
+   *
+   * By default, this will start a new request even if there is already a value in the cache.
+   * If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.
+   *
+   * @remarks
+   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Using .unwrap with async await"
+   * try {
+   *   const payload = await getUserById(1).unwrap();
+   *   console.log('fulfilled', payload)
+   * } catch (error) {
+   *   console.error('rejected', error);
+   * }
+   * ```
+   */
+  (
+    arg: QueryArgFrom<D>,
+    direction: InfiniteQueryDirection,
+  ): InfiniteQueryActionCreatorResult<D>
+}
+
+export type TypedLazyInfiniteQueryTrigger<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+> = LazyInfiniteQueryTrigger<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >
+>
+
+export type UseInfiniteQuerySubscriptionOptions<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = SubscriptionOptions & {
+  /**
+   * Prevents a query from automatically running.
+   *
+   * @remarks
+   * When `skip` is true (or `skipToken` is passed in as `arg`):
+   *
+   * - **If the query has cached data:**
+   *   * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
+   *   * The query will have a status of `uninitialized`
+   *   * If `skip: false` is set after the initial load, the cached result will be used
+   * - **If the query does not have cached data:**
+   *   * The query will have a status of `uninitialized`
+   *   * The query will not exist in the state when viewed with the dev tools
+   *   * The query will not automatically fetch on mount
+   *   * The query will not automatically run when additional components with the same query are added that do run
+   *
+   * @example
+   * ```tsx
+   * // codeblock-meta no-transpile title="Skip example"
+   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
+   *   const { data, error, status } = useGetPokemonByNameQuery(name, {
+   *     skip,
+   *   });
+   *
+   *   return (
+   *     <div>
+   *       {name} - {status}
+   *     </div>
+   *   );
+   * };
+   * ```
+   */
+  skip?: boolean
+  /**
+   * 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.
+   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
+   * - `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.
+   * - `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.
+   *
+   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
+   */
+  refetchOnMountOrArgChange?: boolean | number
+  initialPageParam?: PageParamFrom<D>
+  /**
+   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched
+   * (due to tag invalidation, polling, arg change configuration, or manual refetching),
+   * RTK Query will try to sequentially refetch all pages currently in the cache.
+   * When `false` only the first page will be refetched.
+   *
+   * This option applies to all automatic refetches for this subscription (polling, tag invalidation, etc.).
+   * It can be overridden on a per-call basis using the `refetch()` method.
+   */
+  refetchCachedPages?: boolean
+}
+
+export type TypedUseInfiniteQuerySubscription<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+> = UseInfiniteQuerySubscription<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >
+>
+
+export type UseInfiniteQuerySubscriptionResult<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = {
+  refetch: (
+    options?: Pick<
+      UseInfiniteQuerySubscriptionOptions<D>,
+      'refetchCachedPages'
+    >,
+  ) => InfiniteQueryActionCreatorResult<D>
+  trigger: LazyInfiniteQueryTrigger<D>
+  fetchNextPage: () => InfiniteQueryActionCreatorResult<D>
+  fetchPreviousPage: () => InfiniteQueryActionCreatorResult<D>
+}
+
+/**
+ * Helper type to manually type the result
+ * of the `useQuerySubscription` hook in userland code.
+ */
+export type TypedUseInfiniteQuerySubscriptionResult<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+> = UseInfiniteQuerySubscriptionResult<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >
+>
+
+export type InfiniteQueryStateSelector<
+  R extends Record<string, any>,
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = (state: UseInfiniteQueryStateDefaultResult<D>) => R
+
+export type TypedInfiniteQueryStateSelector<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+  SelectedResult extends Record<
+    string,
+    any
+  > = UseInfiniteQueryStateDefaultResult<
+    InfiniteQueryDefinition<
+      QueryArg,
+      PageParam,
+      BaseQuery,
+      string,
+      ResultType,
+      string
+    >
+  >,
+> = InfiniteQueryStateSelector<
+  SelectedResult,
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >
+>
+
+/**
+ * A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.  Additionally, it will cache multiple "pages" worth of responses within a single cache entry, and allows fetching more pages forwards and backwards from the current cached pages.
+ *
+ * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.
+ *
+ *  The `data` field will be a `{pages: Data[], pageParams: PageParam[]}` structure containing all fetched page responses and the corresponding page param values for each page. You may use this to render individual pages, combine all pages into a single infinite list, or other display logic as needed.
+ *
+ * This hook combines the functionality of both [`useInfiniteQueryState`](#useinfinitequerystate) and [`useInfiniteQuerySubscription`](#useinfinitequerysubscription) together, and is intended to be used in the majority of situations.
+ *
+ * As with normal query hooks, `skipToken` is a valid argument that will skip the query from executing.
+ *
+ * By default, the initial request will use the `initialPageParam` value that was defined on the infinite query endpoint. If you want to start from a different value, you can pass `initialPageParam` as part of the hook options to override that initial request value.
+ *
+ * Use the returned `fetchNextPage` and `fetchPreviousPage` methods on the hook result object to trigger fetches forwards and backwards. These will always calculate the next or previous page param based on the current cached pages and the provided `getNext/PreviousPageParam` callbacks defined in the endpoint.
+ *
+ *
+ * #### Features
+ *
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
+ * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
+ * - Returns the latest request status and cached data from the Redux store
+ * - Re-renders as the request status changes and data becomes available
+ */
+export type UseInfiniteQuery<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = <R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>>(
+  arg: InfiniteQueryArgFrom<D> | SkipToken,
+  options?: UseInfiniteQuerySubscriptionOptions<D> &
+    UseInfiniteQueryStateOptions<D, R>,
+) => UseInfiniteQueryHookResult<D, R> &
+  Pick<
+    UseInfiniteQuerySubscriptionResult<D>,
+    'fetchNextPage' | 'fetchPreviousPage'
+  >
+
+export type TypedUseInfiniteQuery<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+> = UseInfiniteQuery<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >
+>
+
+/**
+ * A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
+ *
+ * Note that this hook does not trigger fetching new data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQuerySubscription`](#useinfinitequerysubscription).
+ *
+ * #### Features
+ *
+ * - Returns the latest request status and cached data from the Redux store
+ * - Re-renders as the request status changes and data becomes available
+ */
+export type UseInfiniteQueryState<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = <R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>>(
+  arg: InfiniteQueryArgFrom<D> | SkipToken,
+  options?: UseInfiniteQueryStateOptions<D, R>,
+) => UseInfiniteQueryStateResult<D, R>
+
+export type TypedUseInfiniteQueryState<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+> = UseInfiniteQueryState<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >
+>
+
+/**
+ * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data. Additionally, it will cache multiple "pages" worth of responses within a single cache entry, and allows fetching more pages forwards and backwards from the current cached pages.
+ *
+ * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.
+ *
+ * Note that this hook does not return a request status or cached data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQueryState`](#useinfinitequerystate).
+ *
+ * #### Features
+ *
+ * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
+ * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards
+ * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
+ */
+export type UseInfiniteQuerySubscription<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = (
+  arg: InfiniteQueryArgFrom<D> | SkipToken,
+  options?: UseInfiniteQuerySubscriptionOptions<D>,
+) => UseInfiniteQuerySubscriptionResult<D>
+
+export type UseInfiniteQueryHookResult<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+  R = UseInfiniteQueryStateDefaultResult<D>,
+> = UseInfiniteQueryStateResult<D, R> &
+  Pick<
+    UseInfiniteQuerySubscriptionResult<D>,
+    'refetch' | 'fetchNextPage' | 'fetchPreviousPage'
+  >
+
+export type TypedUseInfiniteQueryHookResult<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+  R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<
+    InfiniteQueryDefinition<
+      QueryArg,
+      PageParam,
+      BaseQuery,
+      string,
+      ResultType,
+      string
+    >
+  >,
+> = UseInfiniteQueryHookResult<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >,
+  R
+>
+
+export type UseInfiniteQueryStateOptions<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+  R extends Record<string, any>,
+> = {
+  /**
+   * Prevents a query from automatically running.
+   *
+   * @remarks
+   * When skip is true:
+   *
+   * - **If the query has cached data:**
+   *   * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
+   *   * The query will have a status of `uninitialized`
+   *   * If `skip: false` is set after skipping the initial load, the cached result will be used
+   * - **If the query does not have cached data:**
+   *   * The query will have a status of `uninitialized`
+   *   * The query will not exist in the state when viewed with the dev tools
+   *   * The query will not automatically fetch on mount
+   *   * The query will not automatically run when additional components with the same query are added that do run
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Skip example"
+   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
+   *   const { data, error, status } = useGetPokemonByNameQuery(name, {
+   *     skip,
+   *   });
+   *
+   *   return (
+   *     <div>
+   *       {name} - {status}
+   *     </div>
+   *   );
+   * };
+   * ```
+   */
+  skip?: boolean
+  /**
+   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.
+   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.
+   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
+   * Note that this should always return an object (not a primitive), as RTKQ adds fields to the return value.
+   *
+   * @example
+   * ```ts
+   * // codeblock-meta title="Using selectFromResult to extract a single result"
+   * function PostsList() {
+   *   const { data: posts } = api.useGetPostsQuery();
+   *
+   *   return (
+   *     <ul>
+   *       {posts?.data?.map((post) => (
+   *         <PostById key={post.id} id={post.id} />
+   *       ))}
+   *     </ul>
+   *   );
+   * }
+   *
+   * function PostById({ id }: { id: number }) {
+   *   // Will select the post with the given id, and will only rerender if the given posts data changes
+   *   const { post } = api.useGetPostsQuery(undefined, {
+   *     selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),
+   *   });
+   *
+   *   return <li>{post?.name}</li>;
+   * }
+   * ```
+   */
+  selectFromResult?: InfiniteQueryStateSelector<R, D>
+}
+
+export type TypedUseInfiniteQueryStateOptions<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+  SelectedResult extends Record<
+    string,
+    any
+  > = UseInfiniteQueryStateDefaultResult<
+    InfiniteQueryDefinition<
+      QueryArg,
+      PageParam,
+      BaseQuery,
+      string,
+      ResultType,
+      string
+    >
+  >,
+> = UseInfiniteQueryStateOptions<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >,
+  SelectedResult
+>
+
+export type UseInfiniteQueryStateResult<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+  R = UseInfiniteQueryStateDefaultResult<D>,
+> = TSHelpersNoInfer<R>
+
+export type TypedUseInfiniteQueryStateResult<
+  ResultType,
+  QueryArg,
+  PageParam,
+  BaseQuery extends BaseQueryFn,
+  R = UseInfiniteQueryStateDefaultResult<
+    InfiniteQueryDefinition<
+      QueryArg,
+      PageParam,
+      BaseQuery,
+      string,
+      ResultType,
+      string
+    >
+  >,
+> = UseInfiniteQueryStateResult<
+  InfiniteQueryDefinition<
+    QueryArg,
+    PageParam,
+    BaseQuery,
+    string,
+    ResultType,
+    string
+  >,
+  R
+>
+
+type UseInfiniteQueryStateBaseResult<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = InfiniteQuerySubState<D> & {
+  /**
+   * Where `data` tries to hold data as much as possible, also re-using
+   * data from the last arguments passed into the hook, this property
+   * will always contain the received data from the query, for the current query arguments.
+   */
+  currentData?: InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>
+  /**
+   * Query has not started yet.
+   */
+  isUninitialized: false
+  /**
+   * Query is currently loading for the first time. No data yet.
+   */
+  isLoading: false
+  /**
+   * Query is currently fetching, but might have data from an earlier request.
+   */
+  isFetching: false
+  /**
+   * Query has data from a successful load.
+   */
+  isSuccess: false
+  /**
+   * Query is currently in "error" state.
+   */
+  isError: false
+  hasNextPage: boolean
+  hasPreviousPage: boolean
+  isFetchingNextPage: boolean
+  isFetchingPreviousPage: boolean
+}
+
+type UseInfiniteQueryStateDefaultResult<
+  D extends InfiniteQueryDefinition<any, any, any, any, any>,
+> = TSHelpersId<
+  | TSHelpersOverride<
+      Extract<
+        UseInfiniteQueryStateBaseResult<D>,
+        { status: QueryStatus.uninitialized }
+      >,
+      { isUninitialized: true }
+    >
+  | TSHelpersOverride<
+      UseInfiniteQueryStateBaseResult<D>,
+      | { isLoading: true; isFetching: boolean; data: undefined }
+      | ({
+          isSuccess: true
+          isFetching: true
+          error: undefined
+        } & Required<
+          Pick<
+            UseInfiniteQueryStateBaseResult<D>,
+            'data' | 'fulfilledTimeStamp'
+          >
+        >)
+      | ({
+          isSuccess: true
+          isFetching: false
+          error: undefined
+        } & Required<
+          Pick<
+            UseInfiniteQueryStateBaseResult<D>,
+            'data' | 'fulfilledTimeStamp' | 'currentData'
+          >
+        >)
+      | ({ isError: true } & Required<
+          Pick<UseInfiniteQueryStateBaseResult<D>, 'error'>
+        >)
+    >
+> & {
+  /**
+   * @deprecated Included for completeness, but discouraged.
+   * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
+   * and `isUninitialized` flags instead
+   */
+  status: QueryStatus
+}
+
+export type MutationStateSelector<
+  R extends Record<string, any>,
+  D extends MutationDefinition<any, any, any, any>,
+> = (state: MutationResultSelectorResult<D>) => R
+
+export type UseMutationStateOptions<
+  D extends MutationDefinition<any, any, any, any>,
+  R extends Record<string, any>,
+> = {
+  selectFromResult?: MutationStateSelector<R, D>
+  fixedCacheKey?: string
+}
+
+export type UseMutationStateResult<
+  D extends MutationDefinition<any, any, any, any>,
+  R,
+> = TSHelpersNoInfer<R> & {
+  originalArgs?: QueryArgFrom<D>
+  /**
+   * Resets the hook state to its initial `uninitialized` state.
+   * This will also remove the last result from the cache.
+   */
+  reset: () => void
+}
+
+/**
+ * Helper type to manually type the result
+ * of the `useMutation` hook in userland code.
+ */
+export type TypedUseMutationResult<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+  R = MutationResultSelectorResult<
+    MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>
+  >,
+> = UseMutationStateResult<
+  MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>,
+  R
+>
+
+/**
+ * A React hook that lets you trigger an update request for a given endpoint, and subscribes the component to read the request status from the Redux store. The component will re-render as the loading status changes.
+ *
+ * #### Features
+ *
+ * - Manual control over firing a request to alter data on the server or possibly invalidate the cache
+ * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
+ * - Returns the latest request status and cached data from the Redux store
+ * - Re-renders as the request status changes and data becomes available
+ */
+export type UseMutation<D extends MutationDefinition<any, any, any, any>> = <
+  R extends Record<string, any> = MutationResultSelectorResult<D>,
+>(
+  options?: UseMutationStateOptions<D, R>,
+) => readonly [MutationTrigger<D>, UseMutationStateResult<D, R>]
+
+export type TypedUseMutation<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = UseMutation<
+  MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+export type MutationTrigger<D extends MutationDefinition<any, any, any, any>> =
+  {
+    /**
+     * Triggers the mutation and returns a Promise.
+     * @remarks
+     * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
+     *
+     * @example
+     * ```ts
+     * // codeblock-meta title="Using .unwrap with async await"
+     * try {
+     *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
+     *   console.log('fulfilled', payload)
+     * } catch (error) {
+     *   console.error('rejected', error);
+     * }
+     * ```
+     */
+    (arg: QueryArgFrom<D>): MutationActionCreatorResult<D>
+  }
+
+export type TypedMutationTrigger<
+  ResultType,
+  QueryArg,
+  BaseQuery extends BaseQueryFn,
+> = MutationTrigger<
+  MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>
+>
+
+/**
+ * Wrapper around `defaultQueryStateSelector` to be used in `useQuery`.
+ * We want the initial render to already come back with
+ * `{ isUninitialized: false, isFetching: true, isLoading: true }`
+ * to prevent that the library user has to do an additional check for `isUninitialized`/
+ */
+const noPendingQueryStateSelector: QueryStateSelector<any, any> = (
+  selected,
+) => {
+  if (selected.isUninitialized) {
+    return {
+      ...selected,
+      isUninitialized: false,
+      isFetching: true,
+      isLoading: selected.data !== undefined ? false : true,
+      // This is the one place where we still have to use `QueryStatus` as an enum,
+      // since it's the only reference in the React package and not in the core.
+      status: QueryStatus.pending,
+    } as any
+  }
+  return selected
+}
+
+function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {
+  const ret: any = {}
+  keys.forEach((key) => {
+    ret[key] = obj[key]
+  })
+  return ret
+}
+
+const COMMON_HOOK_DEBUG_FIELDS = [
+  'data',
+  'status',
+  'isLoading',
+  'isSuccess',
+  'isError',
+  'error',
+] as const
+
+type GenericPrefetchThunk = (
+  endpointName: any,
+  arg: any,
+  options: PrefetchOptions,
+) => ThunkAction<void, any, any, UnknownAction>
+
+/**
+ *
+ * @param opts.api - An API with defined endpoints to create hooks for
+ * @param opts.moduleOptions.batch - The version of the `batchedUpdates` function to be used
+ * @param opts.moduleOptions.useDispatch - The version of the `useDispatch` hook to be used
+ * @param opts.moduleOptions.useSelector - The version of the `useSelector` hook to be used
+ * @returns An object containing functions to generate hooks based on an endpoint
+ */
+export function buildHooks<Definitions extends EndpointDefinitions>({
+  api,
+  moduleOptions: {
+    batch,
+    hooks: { useDispatch, useSelector, useStore },
+    unstable__sideEffectsInRender,
+    createSelector,
+  },
+  serializeQueryArgs,
+  context,
+}: {
+  api: Api<any, Definitions, any, any, CoreModule>
+  moduleOptions: Required<ReactHooksModuleOptions>
+  serializeQueryArgs: SerializeQueryArgs<any>
+  context: ApiContext<Definitions>
+}) {
+  const usePossiblyImmediateEffect: (
+    effect: () => void | undefined,
+    deps?: DependencyList,
+  ) => void = unstable__sideEffectsInRender ? (cb) => cb() : useEffect
+
+  type UnsubscribePromiseRef = React.RefObject<
+    { unsubscribe?: () => void } | undefined
+  >
+
+  const unsubscribePromiseRef = (ref: UnsubscribePromiseRef) =>
+    ref.current?.unsubscribe?.()
+
+  const endpointDefinitions = context.endpointDefinitions
+
+  return {
+    buildQueryHooks,
+    buildInfiniteQueryHooks,
+    buildMutationHook,
+    usePrefetch,
+  }
+
+  function queryStatePreSelector(
+    currentState: QueryResultSelectorResult<any>,
+    lastResult: UseQueryStateDefaultResult<any> | undefined,
+    queryArgs: any,
+  ): UseQueryStateDefaultResult<any> {
+    // if we had a last result and the current result is uninitialized,
+    // we might have called `api.util.resetApiState`
+    // in this case, reset the hook
+    if (lastResult?.endpointName && currentState.isUninitialized) {
+      const { endpointName } = lastResult
+      const endpointDefinition = endpointDefinitions[endpointName]
+      if (
+        queryArgs !== skipToken &&
+        serializeQueryArgs({
+          queryArgs: lastResult.originalArgs,
+          endpointDefinition,
+          endpointName,
+        }) ===
+          serializeQueryArgs({
+            queryArgs,
+            endpointDefinition,
+            endpointName,
+          })
+      )
+        lastResult = undefined
+    }
+
+    // data is the last known good request result we have tracked - or if none has been tracked yet the last good result for the current args
+    let data = currentState.isSuccess ? currentState.data : lastResult?.data
+    if (data === undefined) data = currentState.data
+
+    const hasData = data !== undefined
+
+    // isFetching = true any time a request is in flight
+    const isFetching = currentState.isLoading
+
+    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)
+    const isLoading =
+      (!lastResult || lastResult.isLoading || lastResult.isUninitialized) &&
+      !hasData &&
+      isFetching
+
+    // isSuccess = true when data is present and we're not refetching after an error.
+    // That includes cases where the _current_ item is either actively
+    // fetching or about to fetch due to an uninitialized entry.
+    const isSuccess =
+      currentState.isSuccess ||
+      (hasData &&
+        ((isFetching && !lastResult?.isError) || currentState.isUninitialized))
+
+    return {
+      ...currentState,
+      data,
+      currentData: currentState.data,
+      isFetching,
+      isLoading,
+      isSuccess,
+    } as UseQueryStateDefaultResult<any>
+  }
+
+  function infiniteQueryStatePreSelector(
+    currentState: InfiniteQueryResultSelectorResult<any>,
+    lastResult: UseInfiniteQueryStateDefaultResult<any> | undefined,
+    queryArgs: any,
+  ): UseInfiniteQueryStateDefaultResult<any> {
+    // if we had a last result and the current result is uninitialized,
+    // we might have called `api.util.resetApiState`
+    // in this case, reset the hook
+    if (lastResult?.endpointName && currentState.isUninitialized) {
+      const { endpointName } = lastResult
+      const endpointDefinition = endpointDefinitions[endpointName]
+      if (
+        queryArgs !== skipToken &&
+        serializeQueryArgs({
+          queryArgs: lastResult.originalArgs,
+          endpointDefinition,
+          endpointName,
+        }) ===
+          serializeQueryArgs({
+            queryArgs,
+            endpointDefinition,
+            endpointName,
+          })
+      )
+        lastResult = undefined
+    }
+
+    // data is the last known good request result we have tracked - or if none has been tracked yet the last good result for the current args
+    let data = currentState.isSuccess ? currentState.data : lastResult?.data
+    if (data === undefined) data = currentState.data
+
+    const hasData = data !== undefined
+
+    // isFetching = true any time a request is in flight
+    const isFetching = currentState.isLoading
+    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)
+    const isLoading =
+      (!lastResult || lastResult.isLoading || lastResult.isUninitialized) &&
+      !hasData &&
+      isFetching
+    // isSuccess = true when data is present
+    const isSuccess = currentState.isSuccess || (isFetching && hasData)
+
+    return {
+      ...currentState,
+      data,
+      currentData: currentState.data,
+      isFetching,
+      isLoading,
+      isSuccess,
+    } as UseInfiniteQueryStateDefaultResult<any>
+  }
+
+  function usePrefetch<EndpointName extends QueryKeys<Definitions>>(
+    endpointName: EndpointName,
+    defaultOptions?: PrefetchOptions,
+  ) {
+    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()
+    const stableDefaultOptions = useShallowStableValue(defaultOptions)
+
+    return useCallback(
+      (arg: any, options?: PrefetchOptions) =>
+        dispatch(
+          (api.util.prefetch as GenericPrefetchThunk)(endpointName, arg, {
+            ...stableDefaultOptions,
+            ...options,
+          }),
+        ),
+      [endpointName, dispatch, stableDefaultOptions],
+    )
+  }
+
+  function useQuerySubscriptionCommonImpl<
+    T extends
+      | QueryActionCreatorResult<any>
+      | InfiniteQueryActionCreatorResult<any>,
+  >(
+    endpointName: string,
+    arg: unknown | SkipToken,
+    {
+      refetchOnReconnect,
+      refetchOnFocus,
+      refetchOnMountOrArgChange,
+      skip = false,
+      pollingInterval = 0,
+      skipPollingIfUnfocused = false,
+      ...rest
+    }: UseQuerySubscriptionOptions = {},
+  ) {
+    const { initiate } = api.endpoints[endpointName] as ApiEndpointQuery<
+      QueryDefinition<any, any, any, any, any>,
+      Definitions
+    >
+    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()
+
+    // TODO: Change this to `useRef<SubscriptionSelectors>(undefined)` after upgrading to React 19.
+    const subscriptionSelectorsRef = useRef<SubscriptionSelectors | undefined>(
+      undefined,
+    )
+
+    if (!subscriptionSelectorsRef.current) {
+      const returnedValue = dispatch(
+        api.internalActions.internal_getRTKQSubscriptions(),
+      )
+
+      if (process.env.NODE_ENV !== 'production') {
+        if (
+          typeof returnedValue !== 'object' ||
+          typeof returnedValue?.type === 'string'
+        ) {
+          throw new Error(
+            `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
+    You must add the middleware for RTK-Query to function correctly!`,
+          )
+        }
+      }
+
+      subscriptionSelectorsRef.current =
+        returnedValue as unknown as SubscriptionSelectors
+    }
+    const stableArg = useStableQueryArgs(skip ? skipToken : arg)
+    const stableSubscriptionOptions = useShallowStableValue({
+      refetchOnReconnect,
+      refetchOnFocus,
+      pollingInterval,
+      skipPollingIfUnfocused,
+    })
+
+    const initialPageParam = (rest as UseInfiniteQuerySubscriptionOptions<any>)
+      .initialPageParam
+    const stableInitialPageParam = useShallowStableValue(initialPageParam)
+
+    const refetchCachedPages = (
+      rest as UseInfiniteQuerySubscriptionOptions<any>
+    ).refetchCachedPages
+    const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages)
+
+    /**
+     * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.
+     */
+    const promiseRef = useRef<T | undefined>(undefined)
+
+    let { queryCacheKey, requestId } = promiseRef.current || {}
+
+    // HACK We've saved the middleware subscription lookup callbacks into a ref,
+    // so we can directly check here if the subscription exists for this query.
+    let currentRenderHasSubscription = false
+    if (queryCacheKey && requestId) {
+      currentRenderHasSubscription =
+        subscriptionSelectorsRef.current.isRequestSubscribed(
+          queryCacheKey,
+          requestId,
+        )
+    }
+
+    const subscriptionRemoved =
+      !currentRenderHasSubscription && promiseRef.current !== undefined
+
+    usePossiblyImmediateEffect((): void | undefined => {
+      if (subscriptionRemoved) {
+        promiseRef.current = undefined
+      }
+    }, [subscriptionRemoved])
+
+    usePossiblyImmediateEffect((): void | undefined => {
+      const lastPromise = promiseRef.current
+      if (
+        typeof process !== 'undefined' &&
+        process.env.NODE_ENV === 'removeMeOnCompilation'
+      ) {
+        // this is only present to enforce the rule of hooks to keep `isSubscribed` in the dependency array
+        console.log(subscriptionRemoved)
+      }
+
+      if (stableArg === skipToken) {
+        lastPromise?.unsubscribe()
+        promiseRef.current = undefined
+        return
+      }
+
+      const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions
+
+      if (!lastPromise || lastPromise.arg !== stableArg) {
+        lastPromise?.unsubscribe()
+        const promise = dispatch(
+          initiate(stableArg, {
+            subscriptionOptions: stableSubscriptionOptions,
+            forceRefetch: refetchOnMountOrArgChange,
+            ...(isInfiniteQueryDefinition(endpointDefinitions[endpointName])
+              ? {
+                  initialPageParam: stableInitialPageParam,
+                  refetchCachedPages: stableRefetchCachedPages,
+                }
+              : {}),
+          }),
+        )
+
+        promiseRef.current = promise as T
+      } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
+        lastPromise.updateSubscriptionOptions(stableSubscriptionOptions)
+      }
+    }, [
+      dispatch,
+      initiate,
+      refetchOnMountOrArgChange,
+      stableArg,
+      stableSubscriptionOptions,
+      subscriptionRemoved,
+      stableInitialPageParam,
+      stableRefetchCachedPages,
+      endpointName,
+    ])
+
+    return [promiseRef, dispatch, initiate, stableSubscriptionOptions] as const
+  }
+
+  function buildUseQueryState(
+    endpointName: string,
+    preSelector:
+      | typeof queryStatePreSelector
+      | typeof infiniteQueryStatePreSelector,
+  ) {
+    const useQueryState = (
+      arg: any,
+      {
+        skip = false,
+        selectFromResult,
+      }:
+        | UseQueryStateOptions<any, any>
+        | UseInfiniteQueryStateOptions<any, any> = {},
+    ) => {
+      const { select } = api.endpoints[endpointName] as ApiEndpointQuery<
+        QueryDefinition<any, any, any, any, any>,
+        Definitions
+      >
+      const stableArg = useStableQueryArgs(skip ? skipToken : arg)
+
+      type ApiRootState = Parameters<ReturnType<typeof select>>[0]
+
+      const lastValue = useRef<any>(undefined)
+
+      const selectDefaultResult: Selector<ApiRootState, any, [any]> = useMemo(
+        () =>
+          // Normally ts-ignores are bad and should be avoided, but we're
+          // already casting this selector to be `Selector<any>` anyway,
+          // so the inconsistencies don't matter here
+          // @ts-ignore
+          createSelector(
+            [
+              // @ts-ignore
+              select(stableArg),
+              (_: ApiRootState, lastResult: any) => lastResult,
+              (_: ApiRootState) => stableArg,
+            ],
+            preSelector,
+            {
+              memoizeOptions: {
+                resultEqualityCheck: shallowEqual,
+              },
+            },
+          ),
+        [select, stableArg],
+      )
+
+      const querySelector: Selector<ApiRootState, any, [any]> = useMemo(
+        () =>
+          selectFromResult
+            ? createSelector([selectDefaultResult], selectFromResult, {
+                devModeChecks: { identityFunctionCheck: 'never' },
+              })
+            : selectDefaultResult,
+        [selectDefaultResult, selectFromResult],
+      )
+
+      const currentState = useSelector(
+        (state: RootState<Definitions, any, any>) =>
+          querySelector(state, lastValue.current),
+        shallowEqual,
+      )
+
+      const store = useStore<RootState<Definitions, any, any>>()
+      const newLastValue = selectDefaultResult(
+        store.getState(),
+        lastValue.current,
+      )
+      useIsomorphicLayoutEffect(() => {
+        lastValue.current = newLastValue
+      }, [newLastValue])
+
+      return currentState
+    }
+
+    return useQueryState
+  }
+
+  function usePromiseRefUnsubscribeOnUnmount(
+    promiseRef: UnsubscribePromiseRef,
+  ) {
+    useEffect(() => {
+      return () => {
+        unsubscribePromiseRef(promiseRef)
+        // eslint-disable-next-line react-hooks/exhaustive-deps
+        ;(promiseRef.current as any) = undefined
+      }
+    }, [promiseRef])
+  }
+
+  function refetchOrErrorIfUnmounted<
+    T extends
+      | QueryActionCreatorResult<any>
+      | InfiniteQueryActionCreatorResult<any>,
+  >(promiseRef: React.RefObject<T | undefined>): T {
+    if (!promiseRef.current)
+      throw new Error('Cannot refetch a query that has not been started yet.')
+    return promiseRef.current.refetch() as T
+  }
+
+  function buildQueryHooks(endpointName: string): QueryHooks<any> {
+    const useQuerySubscription: UseQuerySubscription<any> = (
+      arg: any,
+      options = {},
+    ) => {
+      const [promiseRef] = useQuerySubscriptionCommonImpl<
+        QueryActionCreatorResult<any>
+      >(endpointName, arg, options)
+
+      usePromiseRefUnsubscribeOnUnmount(promiseRef)
+
+      return useMemo(
+        () => ({
+          /**
+           * A method to manually refetch data for the query
+           */
+          refetch: () => refetchOrErrorIfUnmounted(promiseRef),
+        }),
+        [promiseRef],
+      )
+    }
+
+    const useLazyQuerySubscription: UseLazyQuerySubscription<any> = ({
+      refetchOnReconnect,
+      refetchOnFocus,
+      pollingInterval = 0,
+      skipPollingIfUnfocused = false,
+    } = {}) => {
+      const { initiate } = api.endpoints[endpointName] as ApiEndpointQuery<
+        QueryDefinition<any, any, any, any, any>,
+        Definitions
+      >
+      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()
+
+      const [arg, setArg] = useState<any>(UNINITIALIZED_VALUE)
+
+      // TODO: Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.
+      /**
+       * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.
+       */
+      const promiseRef = useRef<QueryActionCreatorResult<any> | undefined>(
+        undefined,
+      )
+
+      const stableSubscriptionOptions = useShallowStableValue({
+        refetchOnReconnect,
+        refetchOnFocus,
+        pollingInterval,
+        skipPollingIfUnfocused,
+      })
+
+      usePossiblyImmediateEffect(() => {
+        const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions
+
+        if (stableSubscriptionOptions !== lastSubscriptionOptions) {
+          promiseRef.current?.updateSubscriptionOptions(
+            stableSubscriptionOptions,
+          )
+        }
+      }, [stableSubscriptionOptions])
+
+      const subscriptionOptionsRef = useRef(stableSubscriptionOptions)
+      usePossiblyImmediateEffect(() => {
+        subscriptionOptionsRef.current = stableSubscriptionOptions
+      }, [stableSubscriptionOptions])
+
+      const trigger = useCallback(
+        function (arg: any, preferCacheValue = false) {
+          let promise: QueryActionCreatorResult<any>
+
+          batch(() => {
+            unsubscribePromiseRef(promiseRef)
+
+            promiseRef.current = promise = dispatch(
+              initiate(arg, {
+                subscriptionOptions: subscriptionOptionsRef.current,
+                forceRefetch: !preferCacheValue,
+              }),
+            )
+
+            setArg(arg)
+          })
+
+          return promise!
+        },
+        [dispatch, initiate],
+      )
+
+      const reset = useCallback(() => {
+        if (promiseRef.current?.queryCacheKey) {
+          dispatch(
+            api.internalActions.removeQueryResult({
+              queryCacheKey: promiseRef.current?.queryCacheKey as QueryCacheKey,
+            }),
+          )
+        }
+      }, [dispatch])
+
+      /* cleanup on unmount */
+      useEffect(() => {
+        return () => {
+          unsubscribePromiseRef(promiseRef)
+        }
+      }, [])
+
+      /* if "cleanup on unmount" was triggered from a fast refresh, we want to reinstate the query */
+      useEffect(() => {
+        if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
+          trigger(arg, true)
+        }
+      }, [arg, trigger])
+
+      return useMemo(
+        () => [trigger, arg, { reset }] as const,
+        [trigger, arg, reset],
+      )
+    }
+
+    const useQueryState: UseQueryState<any> = buildUseQueryState(
+      endpointName,
+      queryStatePreSelector,
+    )
+
+    return {
+      useQueryState,
+      useQuerySubscription,
+      useLazyQuerySubscription,
+      useLazyQuery(options) {
+        const [trigger, arg, { reset }] = useLazyQuerySubscription(options)
+        const queryStateResults = useQueryState(arg, {
+          ...options,
+          skip: arg === UNINITIALIZED_VALUE,
+        })
+
+        const info = useMemo(() => ({ lastArg: arg }), [arg])
+        return useMemo(
+          () => [trigger, { ...queryStateResults, reset }, info],
+          [trigger, queryStateResults, reset, info],
+        )
+      },
+      useQuery(arg, options) {
+        const querySubscriptionResults = useQuerySubscription(arg, options)
+        const queryStateResults = useQueryState(arg, {
+          selectFromResult:
+            arg === skipToken || options?.skip
+              ? undefined
+              : noPendingQueryStateSelector,
+          ...options,
+        })
+
+        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS)
+        useDebugValue(debugValue)
+
+        return useMemo(
+          () => ({ ...queryStateResults, ...querySubscriptionResults }),
+          [queryStateResults, querySubscriptionResults],
+        )
+      },
+    }
+  }
+
+  function buildInfiniteQueryHooks(
+    endpointName: string,
+  ): InfiniteQueryHooks<any> {
+    const useInfiniteQuerySubscription: UseInfiniteQuerySubscription<any> = (
+      arg: any,
+      options = {},
+    ) => {
+      const [promiseRef, dispatch, initiate, stableSubscriptionOptions] =
+        useQuerySubscriptionCommonImpl<InfiniteQueryActionCreatorResult<any>>(
+          endpointName,
+          arg,
+          options,
+        )
+
+      const subscriptionOptionsRef = useRef(stableSubscriptionOptions)
+      usePossiblyImmediateEffect(() => {
+        subscriptionOptionsRef.current = stableSubscriptionOptions
+      }, [stableSubscriptionOptions])
+
+      // Extract and stabilize the hook-level refetchCachedPages option
+      const hookRefetchCachedPages = (
+        options as UseInfiniteQuerySubscriptionOptions<any>
+      ).refetchCachedPages
+      const stableHookRefetchCachedPages = useShallowStableValue(
+        hookRefetchCachedPages,
+      )
+
+      const trigger: LazyInfiniteQueryTrigger<any> = useCallback(
+        function (arg: unknown, direction: 'forward' | 'backward') {
+          let promise: InfiniteQueryActionCreatorResult<any>
+
+          batch(() => {
+            unsubscribePromiseRef(promiseRef)
+
+            promiseRef.current = promise = dispatch(
+              (initiate as StartInfiniteQueryActionCreator<any>)(arg, {
+                subscriptionOptions: subscriptionOptionsRef.current,
+                direction,
+              }),
+            )
+          })
+
+          return promise!
+        },
+        [promiseRef, dispatch, initiate],
+      )
+
+      usePromiseRefUnsubscribeOnUnmount(promiseRef)
+
+      const stableArg = useStableQueryArgs(options.skip ? skipToken : arg)
+
+      const refetch = useCallback(
+        (
+          options?: Pick<
+            UseInfiniteQuerySubscriptionOptions<any>,
+            'refetchCachedPages'
+          >,
+        ) => {
+          if (!promiseRef.current)
+            throw new Error(
+              'Cannot refetch a query that has not been started yet.',
+            )
+          // Merge per-call options with hook-level default
+          const mergedOptions = {
+            refetchCachedPages:
+              options?.refetchCachedPages ?? stableHookRefetchCachedPages,
+          }
+          return promiseRef.current.refetch(mergedOptions)
+        },
+        [promiseRef, stableHookRefetchCachedPages],
+      )
+
+      return useMemo(() => {
+        const fetchNextPage = () => {
+          return trigger(stableArg, 'forward')
+        }
+
+        const fetchPreviousPage = () => {
+          return trigger(stableArg, 'backward')
+        }
+
+        return {
+          trigger,
+          /**
+           * A method to manually refetch data for the query
+           */
+          refetch,
+          fetchNextPage,
+          fetchPreviousPage,
+        }
+      }, [refetch, trigger, stableArg])
+    }
+
+    const useInfiniteQueryState: UseInfiniteQueryState<any> =
+      buildUseQueryState(endpointName, infiniteQueryStatePreSelector)
+
+    return {
+      useInfiniteQueryState,
+      useInfiniteQuerySubscription,
+      useInfiniteQuery(arg, options) {
+        const { refetch, fetchNextPage, fetchPreviousPage } =
+          useInfiniteQuerySubscription(arg, options)
+        const queryStateResults = useInfiniteQueryState(arg, {
+          selectFromResult:
+            arg === skipToken || options?.skip
+              ? undefined
+              : noPendingQueryStateSelector,
+          ...options,
+        })
+
+        const debugValue = pick(
+          queryStateResults,
+          ...COMMON_HOOK_DEBUG_FIELDS,
+          'hasNextPage',
+          'hasPreviousPage',
+        )
+        useDebugValue(debugValue)
+
+        return useMemo(
+          () => ({
+            ...queryStateResults,
+            fetchNextPage,
+            fetchPreviousPage,
+            refetch,
+          }),
+          [queryStateResults, fetchNextPage, fetchPreviousPage, refetch],
+        )
+      },
+    }
+  }
+
+  function buildMutationHook(name: string): UseMutation<any> {
+    return ({ selectFromResult, fixedCacheKey } = {}) => {
+      const { select, initiate } = api.endpoints[name] as ApiEndpointMutation<
+        MutationDefinition<any, any, any, any, any>,
+        Definitions
+      >
+      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()
+      const [promise, setPromise] = useState<MutationActionCreatorResult<any>>()
+
+      useEffect(
+        () => () => {
+          if (!promise?.arg.fixedCacheKey) {
+            promise?.reset()
+          }
+        },
+        [promise],
+      )
+
+      const triggerMutation = useCallback(
+        function (arg: Parameters<typeof initiate>['0']) {
+          const promise = dispatch(initiate(arg, { fixedCacheKey }))
+          setPromise(promise)
+          return promise
+        },
+        [dispatch, initiate, fixedCacheKey],
+      )
+
+      const { requestId } = promise || {}
+      const selectDefaultResult = useMemo(
+        () => select({ fixedCacheKey, requestId: promise?.requestId }),
+        [fixedCacheKey, promise, select],
+      )
+      const mutationSelector = useMemo(
+        (): Selector<RootState<Definitions, any, any>, any> =>
+          selectFromResult
+            ? createSelector([selectDefaultResult], selectFromResult)
+            : selectDefaultResult,
+        [selectFromResult, selectDefaultResult],
+      )
+
+      const currentState = useSelector(mutationSelector, shallowEqual)
+      const originalArgs =
+        fixedCacheKey == null ? promise?.arg.originalArgs : undefined
+      const reset = useCallback(() => {
+        batch(() => {
+          if (promise) {
+            setPromise(undefined)
+          }
+          if (fixedCacheKey) {
+            dispatch(
+              api.internalActions.removeMutationResult({
+                requestId,
+                fixedCacheKey,
+              }),
+            )
+          }
+        })
+      }, [dispatch, fixedCacheKey, promise, requestId])
+
+      const debugValue = pick(
+        currentState,
+        ...COMMON_HOOK_DEBUG_FIELDS,
+        'endpointName',
+      )
+      useDebugValue(debugValue)
+
+      const finalState = useMemo(
+        () => ({ ...currentState, originalArgs, reset }),
+        [currentState, originalArgs, reset],
+      )
+
+      return useMemo(
+        () => [triggerMutation, finalState] as const,
+        [triggerMutation, finalState],
+      )
+    }
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/react/constants.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/constants.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/constants.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,2 @@
+export const UNINITIALIZED_VALUE = Symbol()
+export type UninitializedValue = typeof UNINITIALIZED_VALUE
Index: node_modules/@reduxjs/toolkit/src/query/react/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,43 @@
+// This must remain here so that the `mangleErrors.cjs` build script
+// does not have to import this into each source file it rewrites.
+import { formatProdErrorMessage } from '@reduxjs/toolkit'
+
+import { buildCreateApi, coreModule } from './rtkqImports'
+import { reactHooksModule, reactHooksModuleName } from './module'
+
+export * from '@reduxjs/toolkit/query'
+export { ApiProvider } from './ApiProvider'
+
+const createApi = /* @__PURE__ */ buildCreateApi(
+  coreModule(),
+  reactHooksModule(),
+)
+
+export type {
+  TypedUseMutationResult,
+  TypedUseQueryHookResult,
+  TypedUseQueryStateResult,
+  TypedUseQuerySubscriptionResult,
+  TypedLazyQueryTrigger,
+  TypedUseLazyQuery,
+  TypedUseMutation,
+  TypedMutationTrigger,
+  TypedQueryStateSelector,
+  TypedUseQueryState,
+  TypedUseQuery,
+  TypedUseQuerySubscription,
+  TypedUseLazyQuerySubscription,
+  TypedUseQueryStateOptions,
+  TypedUseLazyQueryStateResult,
+  TypedUseInfiniteQuery,
+  TypedUseInfiniteQueryHookResult,
+  TypedUseInfiniteQueryStateResult,
+  TypedUseInfiniteQuerySubscriptionResult,
+  TypedUseInfiniteQueryStateOptions,
+  TypedInfiniteQueryStateSelector,
+  TypedUseInfiniteQuerySubscription,
+  TypedUseInfiniteQueryState,
+  TypedLazyInfiniteQueryTrigger,
+} from './buildHooks'
+export { UNINITIALIZED_VALUE } from './constants'
+export { createApi, reactHooksModule, reactHooksModuleName }
Index: node_modules/@reduxjs/toolkit/src/query/react/module.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/module.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/module.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,275 @@
+import type {
+  Api,
+  BaseQueryFn,
+  EndpointDefinitions,
+  InfiniteQueryDefinition,
+  Module,
+  MutationDefinition,
+  PrefetchOptions,
+  QueryArgFrom,
+  QueryDefinition,
+  QueryKeys,
+} from '@reduxjs/toolkit/query'
+import {
+  batch as rrBatch,
+  useDispatch as rrUseDispatch,
+  useSelector as rrUseSelector,
+  useStore as rrUseStore,
+} from 'react-redux'
+import type { CreateSelectorFunction } from 'reselect'
+import { createSelector as _createSelector } from 'reselect'
+import {
+  isInfiniteQueryDefinition,
+  isMutationDefinition,
+  isQueryDefinition,
+} from '../endpointDefinitions'
+import { safeAssign } from '../tsHelpers'
+import { capitalize, countObjectKeys } from '../utils'
+import type {
+  InfiniteQueryHooks,
+  MutationHooks,
+  QueryHooks,
+} from './buildHooks'
+import { buildHooks } from './buildHooks'
+import type { HooksWithUniqueNames } from './namedHooks'
+
+export const reactHooksModuleName = /* @__PURE__ */ Symbol()
+export type ReactHooksModule = typeof reactHooksModuleName
+
+declare module '@reduxjs/toolkit/query' {
+  export interface ApiModules<
+    // eslint-disable-next-line @typescript-eslint/no-unused-vars
+    BaseQuery extends BaseQueryFn,
+    Definitions extends EndpointDefinitions,
+    // eslint-disable-next-line @typescript-eslint/no-unused-vars
+    ReducerPath extends string,
+    // eslint-disable-next-line @typescript-eslint/no-unused-vars
+    TagTypes extends string,
+  > {
+    [reactHooksModuleName]: {
+      /**
+       *  Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.
+       */
+      endpoints: {
+        [K in keyof Definitions]: Definitions[K] extends QueryDefinition<
+          any,
+          any,
+          any,
+          any,
+          any
+        >
+          ? QueryHooks<Definitions[K]>
+          : Definitions[K] extends MutationDefinition<any, any, any, any, any>
+            ? MutationHooks<Definitions[K]>
+            : Definitions[K] extends InfiniteQueryDefinition<
+                  any,
+                  any,
+                  any,
+                  any,
+                  any
+                >
+              ? InfiniteQueryHooks<Definitions[K]>
+              : never
+      }
+      /**
+       * A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.
+       */
+      usePrefetch<EndpointName extends QueryKeys<Definitions>>(
+        endpointName: EndpointName,
+        options?: PrefetchOptions,
+      ): (
+        arg: QueryArgFrom<Definitions[EndpointName]>,
+        options?: PrefetchOptions,
+      ) => void
+    } & HooksWithUniqueNames<Definitions>
+  }
+}
+
+type RR = typeof import('react-redux')
+
+export interface ReactHooksModuleOptions {
+  /**
+   * The hooks from React Redux to be used
+   */
+  hooks?: {
+    /**
+     * The version of the `useDispatch` hook to be used
+     */
+    useDispatch: RR['useDispatch']
+    /**
+     * The version of the `useSelector` hook to be used
+     */
+    useSelector: RR['useSelector']
+    /**
+     * The version of the `useStore` hook to be used
+     */
+    useStore: RR['useStore']
+  }
+  /**
+   * The version of the `batchedUpdates` function to be used
+   */
+  batch?: RR['batch']
+  /**
+   * Enables performing asynchronous tasks immediately within a render.
+   *
+   * @example
+   *
+   * ```ts
+   * import {
+   *   buildCreateApi,
+   *   coreModule,
+   *   reactHooksModule
+   * } from '@reduxjs/toolkit/query/react'
+   *
+   * const createApi = buildCreateApi(
+   *   coreModule(),
+   *   reactHooksModule({ unstable__sideEffectsInRender: true })
+   * )
+   * ```
+   */
+  unstable__sideEffectsInRender?: boolean
+  /**
+   * A selector creator (usually from `reselect`, or matching the same signature)
+   */
+  createSelector?: CreateSelectorFunction<any, any, any>
+}
+
+/**
+ * Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.
+ *
+ *  @example
+ * ```ts
+ * const MyContext = React.createContext<ReactReduxContextValue | null>(null);
+ * const customCreateApi = buildCreateApi(
+ *   coreModule(),
+ *   reactHooksModule({
+ *     hooks: {
+ *       useDispatch: createDispatchHook(MyContext),
+ *       useSelector: createSelectorHook(MyContext),
+ *       useStore: createStoreHook(MyContext)
+ *     }
+ *   })
+ * );
+ * ```
+ *
+ * @returns A module for use with `buildCreateApi`
+ */
+export const reactHooksModule = ({
+  batch = rrBatch,
+  hooks = {
+    useDispatch: rrUseDispatch,
+    useSelector: rrUseSelector,
+    useStore: rrUseStore,
+  },
+  createSelector = _createSelector,
+  unstable__sideEffectsInRender = false,
+  ...rest
+}: ReactHooksModuleOptions = {}): Module<ReactHooksModule> => {
+  if (process.env.NODE_ENV !== 'production') {
+    const hookNames = ['useDispatch', 'useSelector', 'useStore'] as const
+    let warned = false
+    for (const hookName of hookNames) {
+      // warn for old hook options
+      if (countObjectKeys(rest) > 0) {
+        if ((rest as Partial<typeof hooks>)[hookName]) {
+          if (!warned) {
+            console.warn(
+              'As of RTK 2.0, the hooks now need to be specified as one object, provided under a `hooks` key:' +
+                '\n`reactHooksModule({ hooks: { useDispatch, useSelector, useStore } })`',
+            )
+            warned = true
+          }
+        }
+        // migrate
+        // @ts-ignore
+        hooks[hookName] = rest[hookName]
+      }
+      // then make sure we have them all
+      if (typeof hooks[hookName] !== 'function') {
+        throw new Error(
+          `When using custom hooks for context, all ${
+            hookNames.length
+          } hooks need to be provided: ${hookNames.join(
+            ', ',
+          )}.\nHook ${hookName} was either not provided or not a function.`,
+        )
+      }
+    }
+  }
+
+  return {
+    name: reactHooksModuleName,
+    init(api, { serializeQueryArgs }, context) {
+      const anyApi = api as any as Api<
+        any,
+        Record<string, any>,
+        any,
+        any,
+        ReactHooksModule
+      >
+      const {
+        buildQueryHooks,
+        buildInfiniteQueryHooks,
+        buildMutationHook,
+        usePrefetch,
+      } = buildHooks({
+        api,
+        moduleOptions: {
+          batch,
+          hooks,
+          unstable__sideEffectsInRender,
+          createSelector,
+        },
+        serializeQueryArgs,
+        context,
+      })
+      safeAssign(anyApi, { usePrefetch })
+      safeAssign(context, { batch })
+
+      return {
+        injectEndpoint(endpointName, definition) {
+          if (isQueryDefinition(definition)) {
+            const {
+              useQuery,
+              useLazyQuery,
+              useLazyQuerySubscription,
+              useQueryState,
+              useQuerySubscription,
+            } = buildQueryHooks(endpointName)
+            safeAssign(anyApi.endpoints[endpointName], {
+              useQuery,
+              useLazyQuery,
+              useLazyQuerySubscription,
+              useQueryState,
+              useQuerySubscription,
+            })
+            ;(api as any)[`use${capitalize(endpointName)}Query`] = useQuery
+            ;(api as any)[`useLazy${capitalize(endpointName)}Query`] =
+              useLazyQuery
+          }
+          if (isMutationDefinition(definition)) {
+            const useMutation = buildMutationHook(endpointName)
+            safeAssign(anyApi.endpoints[endpointName], {
+              useMutation,
+            })
+            ;(api as any)[`use${capitalize(endpointName)}Mutation`] =
+              useMutation
+          } else if (isInfiniteQueryDefinition(definition)) {
+            const {
+              useInfiniteQuery,
+              useInfiniteQuerySubscription,
+              useInfiniteQueryState,
+            } = buildInfiniteQueryHooks(endpointName)
+            safeAssign(anyApi.endpoints[endpointName], {
+              useInfiniteQuery,
+              useInfiniteQuerySubscription,
+              useInfiniteQueryState,
+            })
+            ;(api as any)[`use${capitalize(endpointName)}InfiniteQuery`] =
+              useInfiniteQuery
+          }
+        },
+      }
+    },
+  }
+}
Index: node_modules/@reduxjs/toolkit/src/query/react/namedHooks.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/namedHooks.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/namedHooks.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,59 @@
+import type {
+  DefinitionType,
+  EndpointDefinitions,
+  MutationDefinition,
+  QueryDefinition,
+  InfiniteQueryDefinition,
+} from '@reduxjs/toolkit/query'
+import type {
+  UseInfiniteQuery,
+  UseLazyQuery,
+  UseMutation,
+  UseQuery,
+} from './buildHooks'
+
+type QueryHookNames<Definitions extends EndpointDefinitions> = {
+  [K in keyof Definitions as Definitions[K] extends {
+    type: DefinitionType.query
+  }
+    ? `use${Capitalize<K & string>}Query`
+    : never]: UseQuery<
+    Extract<Definitions[K], QueryDefinition<any, any, any, any>>
+  >
+}
+
+type LazyQueryHookNames<Definitions extends EndpointDefinitions> = {
+  [K in keyof Definitions as Definitions[K] extends {
+    type: DefinitionType.query
+  }
+    ? `useLazy${Capitalize<K & string>}Query`
+    : never]: UseLazyQuery<
+    Extract<Definitions[K], QueryDefinition<any, any, any, any>>
+  >
+}
+
+type InfiniteQueryHookNames<Definitions extends EndpointDefinitions> = {
+  [K in keyof Definitions as Definitions[K] extends {
+    type: DefinitionType.infinitequery
+  }
+    ? `use${Capitalize<K & string>}InfiniteQuery`
+    : never]: UseInfiniteQuery<
+    Extract<Definitions[K], InfiniteQueryDefinition<any, any, any, any, any>>
+  >
+}
+
+type MutationHookNames<Definitions extends EndpointDefinitions> = {
+  [K in keyof Definitions as Definitions[K] extends {
+    type: DefinitionType.mutation
+  }
+    ? `use${Capitalize<K & string>}Mutation`
+    : never]: UseMutation<
+    Extract<Definitions[K], MutationDefinition<any, any, any, any>>
+  >
+}
+
+export type HooksWithUniqueNames<Definitions extends EndpointDefinitions> =
+  QueryHookNames<Definitions> &
+    LazyQueryHookNames<Definitions> &
+    InfiniteQueryHookNames<Definitions> &
+    MutationHookNames<Definitions>
Index: node_modules/@reduxjs/toolkit/src/query/react/reactImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/reactImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/reactImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,10 @@
+export {
+  useEffect,
+  useRef,
+  useMemo,
+  useContext,
+  useCallback,
+  useDebugValue,
+  useLayoutEffect,
+  useState,
+} from 'react'
Index: node_modules/@reduxjs/toolkit/src/query/react/reactReduxImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/reactReduxImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/reactReduxImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1 @@
+export { shallowEqual, Provider, ReactReduxContext } from 'react-redux'
Index: node_modules/@reduxjs/toolkit/src/query/react/rtkqImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/rtkqImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/rtkqImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,8 @@
+export {
+  buildCreateApi,
+  coreModule,
+  copyWithStructuralSharing,
+  setupListeners,
+  QueryStatus,
+  skipToken,
+} from '@reduxjs/toolkit/query'
Index: node_modules/@reduxjs/toolkit/src/query/react/useSerializedStableValue.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/useSerializedStableValue.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/useSerializedStableValue.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,17 @@
+import { useEffect, useRef, useMemo } from './reactImports'
+import { copyWithStructuralSharing } from './rtkqImports'
+
+export function useStableQueryArgs<T>(queryArgs: T) {
+  const cache = useRef(queryArgs)
+  const copy = useMemo(
+    () => copyWithStructuralSharing(cache.current, queryArgs),
+    [queryArgs],
+  )
+  useEffect(() => {
+    if (cache.current !== copy) {
+      cache.current = copy
+    }
+  }, [copy])
+
+  return copy
+}
Index: node_modules/@reduxjs/toolkit/src/query/react/useShallowStableValue.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/react/useShallowStableValue.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/react/useShallowStableValue.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,13 @@
+import { useEffect, useRef } from './reactImports'
+import { shallowEqual } from './reactReduxImports'
+
+export function useShallowStableValue<T>(value: T) {
+  const cache = useRef(value)
+  useEffect(() => {
+    if (!shallowEqual(cache.current, value)) {
+      cache.current = value
+    }
+  }, [value])
+
+  return shallowEqual(cache.current, value) ? cache.current : value
+}
Index: node_modules/@reduxjs/toolkit/src/query/retry.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/retry.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/retry.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,233 @@
+import type {
+  BaseQueryApi,
+  BaseQueryArg,
+  BaseQueryEnhancer,
+  BaseQueryError,
+  BaseQueryExtraOptions,
+  BaseQueryFn,
+  BaseQueryMeta,
+} from './baseQueryTypes'
+import type { FetchBaseQueryError } from './fetchBaseQuery'
+import { HandledError } from './HandledError'
+
+/**
+ * Exponential backoff based on the attempt number.
+ *
+ * @remarks
+ * 1. 600ms * random(0.4, 1.4)
+ * 2. 1200ms * random(0.4, 1.4)
+ * 3. 2400ms * random(0.4, 1.4)
+ * 4. 4800ms * random(0.4, 1.4)
+ * 5. 9600ms * random(0.4, 1.4)
+ *
+ * @param attempt - Current attempt
+ * @param maxRetries - Maximum number of retries
+ */
+async function defaultBackoff(
+  attempt: number = 0,
+  maxRetries: number = 5,
+  signal?: AbortSignal,
+) {
+  const attempts = Math.min(attempt, maxRetries)
+
+  const timeout = ~~((Math.random() + 0.4) * (300 << attempts)) // Force a positive int in the case we make this an option
+
+  await new Promise<void>((resolve, reject) => {
+    const timeoutId = setTimeout(() => resolve(), timeout)
+
+    // If signal is provided and gets aborted, clear timeout and reject
+    if (signal) {
+      const abortHandler = () => {
+        clearTimeout(timeoutId)
+        reject(new Error('Aborted'))
+      }
+
+      // Check if already aborted
+      if (signal.aborted) {
+        clearTimeout(timeoutId)
+        reject(new Error('Aborted'))
+      } else {
+        signal.addEventListener('abort', abortHandler, { once: true })
+      }
+    }
+  })
+}
+
+type RetryConditionFunction = (
+  error: BaseQueryError<BaseQueryFn>,
+  args: BaseQueryArg<BaseQueryFn>,
+  extraArgs: {
+    attempt: number
+    baseQueryApi: BaseQueryApi
+    extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions
+  },
+) => boolean
+
+export type RetryOptions = {
+  /**
+   * Function used to determine delay between retries
+   */
+  backoff?: (
+    attempt: number,
+    maxRetries: number,
+    signal?: AbortSignal,
+  ) => Promise<void>
+} & (
+  | {
+      /**
+       * How many times the query will be retried (default: 5)
+       */
+      maxRetries?: number
+      retryCondition?: undefined
+    }
+  | {
+      /**
+       * Callback to determine if a retry should be attempted.
+       * Return `true` for another retry and `false` to quit trying prematurely.
+       */
+      retryCondition?: RetryConditionFunction
+      maxRetries?: undefined
+    }
+)
+
+function fail<BaseQuery extends BaseQueryFn = BaseQueryFn>(
+  error: BaseQueryError<BaseQuery>,
+  meta?: BaseQueryMeta<BaseQuery>,
+): never {
+  throw Object.assign(new HandledError({ error, meta }), {
+    throwImmediately: true,
+  })
+}
+
+/**
+ * Checks if the abort signal is aborted and fails immediately if so.
+ * Used to exit retry loops cleanly when a request is aborted.
+ */
+function failIfAborted(signal: AbortSignal): void {
+  if (signal.aborted) {
+    fail({ status: 'CUSTOM_ERROR', error: 'Aborted' })
+  }
+}
+
+const EMPTY_OPTIONS = {}
+
+const retryWithBackoff: BaseQueryEnhancer<
+  unknown,
+  RetryOptions,
+  RetryOptions | void
+> = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {
+  // We need to figure out `maxRetries` before we define `defaultRetryCondition.
+  // This is probably goofy, but ought to work.
+  // Put our defaults in one array, filter out undefineds, grab the last value.
+  const possibleMaxRetries: number[] = [
+    5,
+    ((defaultOptions as any) || EMPTY_OPTIONS).maxRetries,
+    ((extraOptions as any) || EMPTY_OPTIONS).maxRetries,
+  ].filter((x) => x !== undefined)
+  const [maxRetries] = possibleMaxRetries.slice(-1)
+
+  const defaultRetryCondition: RetryConditionFunction = (_, __, { attempt }) =>
+    attempt <= maxRetries
+
+  const options: {
+    maxRetries: number
+    backoff: typeof defaultBackoff
+    retryCondition: typeof defaultRetryCondition
+  } = {
+    maxRetries,
+    backoff: defaultBackoff,
+    retryCondition: defaultRetryCondition,
+    ...defaultOptions,
+    ...extraOptions,
+  }
+  let retry = 0
+
+  while (true) {
+    // Check if aborted before each attempt
+    failIfAborted(api.signal)
+
+    try {
+      const result = await baseQuery(args, api, extraOptions)
+      // baseQueries _should_ return an error property, so we should check for that and throw it to continue retrying
+      if (result.error) {
+        throw new HandledError(result)
+      }
+      return result
+    } catch (e: any) {
+      retry++
+
+      if (e.throwImmediately) {
+        if (e instanceof HandledError) {
+          return e.value
+        }
+
+        // We don't know what this is, so we have to rethrow it
+        throw e
+      }
+
+      if (e instanceof HandledError) {
+        if (
+          !options.retryCondition(e.value.error as FetchBaseQueryError, args, {
+            attempt: retry,
+            baseQueryApi: api,
+            extraOptions,
+          })
+        ) {
+          return e.value // Max retries for expected error
+        }
+      } else {
+        // For unexpected errors, respect maxRetries
+        if (retry > options.maxRetries) {
+          // Return the error as a proper error response instead of throwing
+          return { error: e }
+        }
+      }
+
+      // Check if aborted before backoff
+      failIfAborted(api.signal)
+
+      try {
+        await options.backoff(retry, options.maxRetries, api.signal)
+      } catch (backoffError) {
+        // If backoff was aborted, exit the retry loop
+        failIfAborted(api.signal)
+        // Otherwise, rethrow the backoff error
+        throw backoffError
+      }
+    }
+  }
+}
+
+/**
+ * A utility that can wrap `baseQuery` in the API definition to provide retries with a basic exponential backoff.
+ *
+ * @example
+ *
+ * ```ts
+ * // codeblock-meta title="Retry every request 5 times by default"
+ * import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'
+ * interface Post {
+ *   id: number
+ *   name: string
+ * }
+ * type PostsResponse = Post[]
+ *
+ * // maxRetries: 5 is the default, and can be omitted. Shown for documentation purposes.
+ * const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), { maxRetries: 5 });
+ * export const api = createApi({
+ *   baseQuery: staggeredBaseQuery,
+ *   endpoints: (build) => ({
+ *     getPosts: build.query<PostsResponse, void>({
+ *       query: () => ({ url: 'posts' }),
+ *     }),
+ *     getPost: build.query<PostsResponse, string>({
+ *       query: (id) => ({ url: `post/${id}` }),
+ *       extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint
+ *     }),
+ *   }),
+ * });
+ *
+ * export const { useGetPostsQuery, useGetPostQuery } = api;
+ * ```
+ */
+export const retry = /* @__PURE__ */ Object.assign(retryWithBackoff, { fail })
Index: node_modules/@reduxjs/toolkit/src/query/standardSchema.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/standardSchema.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/standardSchema.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,35 @@
+import type { StandardSchemaV1 } from '@standard-schema/spec'
+import { SchemaError } from '@standard-schema/utils'
+import type { SchemaType } from './endpointDefinitions'
+
+export class NamedSchemaError extends SchemaError {
+  constructor(
+    issues: readonly StandardSchemaV1.Issue[],
+    public readonly value: any,
+    public readonly schemaName: `${SchemaType}Schema`,
+    public readonly _bqMeta: any,
+  ) {
+    super(issues)
+  }
+}
+
+export const shouldSkip = (
+  skipSchemaValidation: boolean | SchemaType[] | undefined,
+  schemaName: SchemaType,
+) =>
+  Array.isArray(skipSchemaValidation)
+    ? skipSchemaValidation.includes(schemaName)
+    : !!skipSchemaValidation
+
+export async function parseWithSchema<Schema extends StandardSchemaV1>(
+  schema: Schema,
+  data: unknown,
+  schemaName: `${SchemaType}Schema`,
+  bqMeta: any,
+): Promise<StandardSchemaV1.InferOutput<Schema>> {
+  const result = await schema['~standard'].validate(data)
+  if (result.issues) {
+    throw new NamedSchemaError(result.issues, data, schemaName, bqMeta)
+  }
+  return result.value
+}
Index: node_modules/@reduxjs/toolkit/src/query/tests/apiProvider.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/apiProvider.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/apiProvider.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,170 @@
+import { configureStore } from '@reduxjs/toolkit'
+import {
+  ApiProvider,
+  buildCreateApi,
+  coreModule,
+  createApi,
+  reactHooksModule,
+} from '@reduxjs/toolkit/query/react'
+import { fireEvent, render, waitFor } from '@testing-library/react'
+import { delay } from 'msw'
+import * as React from 'react'
+import type { ReactReduxContextValue } from 'react-redux'
+import {
+  Provider,
+  createDispatchHook,
+  createSelectorHook,
+  createStoreHook,
+} from 'react-redux'
+
+const api = createApi({
+  baseQuery: async (arg: any) => {
+    await delay(150)
+    return { data: arg?.body ? arg.body : null }
+  },
+  endpoints: (build) => ({
+    getUser: build.query<any, number>({
+      query: (arg) => arg,
+    }),
+    updateUser: build.mutation<any, { name: string }>({
+      query: (update) => ({ body: update }),
+    }),
+  }),
+})
+
+afterEach(() => {
+  vi.resetAllMocks()
+})
+
+describe('ApiProvider', () => {
+  test('ApiProvider allows a user to make queries without a traditional Redux setup', async () => {
+    function User() {
+      const [value, setValue] = React.useState(0)
+
+      const { isFetching } = api.endpoints.getUser.useQuery(1, {
+        skip: value < 1,
+      })
+
+      return (
+        <div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <button onClick={() => setValue((val) => val + 1)}>
+            Increment value
+          </button>
+        </div>
+      )
+    }
+
+    const { getByText, getByTestId } = render(
+      <ApiProvider api={api}>
+        <User />
+      </ApiProvider>,
+    )
+
+    await waitFor(() =>
+      expect(getByTestId('isFetching').textContent).toBe('false'),
+    )
+    fireEvent.click(getByText('Increment value'))
+    await waitFor(() =>
+      expect(getByTestId('isFetching').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(getByTestId('isFetching').textContent).toBe('false'),
+    )
+    fireEvent.click(getByText('Increment value'))
+    // Being that nothing has changed in the args, this should never fire.
+    expect(getByTestId('isFetching').textContent).toBe('false')
+  })
+  test('ApiProvider throws if nested inside a Redux context', () => {
+    // Intentionally swallow the "unhandled error" message
+    vi.spyOn(console, 'error').mockImplementation(() => {})
+    expect(() =>
+      render(
+        <Provider store={configureStore({ reducer: () => null })}>
+          <ApiProvider api={api}>child</ApiProvider>
+        </Provider>,
+      ),
+    ).toThrowErrorMatchingInlineSnapshot(
+      `[Error: Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.]`,
+    )
+  })
+  test('ApiProvider allows a custom context', async () => {
+    const customContext = React.createContext<ReactReduxContextValue | null>(
+      null,
+    )
+
+    const createApiWithCustomContext = buildCreateApi(
+      coreModule(),
+      reactHooksModule({
+        hooks: {
+          useStore: createStoreHook(customContext),
+          useSelector: createSelectorHook(customContext),
+          useDispatch: createDispatchHook(customContext),
+        },
+      }),
+    )
+
+    const customApi = createApiWithCustomContext({
+      baseQuery: async (arg: any) => {
+        await delay(150)
+        return { data: arg?.body ? arg.body : null }
+      },
+      endpoints: (build) => ({
+        getUser: build.query<any, number>({
+          query: (arg) => arg,
+        }),
+        updateUser: build.mutation<any, { name: string }>({
+          query: (update) => ({ body: update }),
+        }),
+      }),
+    })
+
+    function User() {
+      const [value, setValue] = React.useState(0)
+
+      const { isFetching } = customApi.endpoints.getUser.useQuery(1, {
+        skip: value < 1,
+      })
+
+      return (
+        <div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <button onClick={() => setValue((val) => val + 1)}>
+            Increment value
+          </button>
+        </div>
+      )
+    }
+
+    const { getByText, getByTestId } = render(
+      <ApiProvider api={customApi} context={customContext}>
+        <User />
+      </ApiProvider>,
+    )
+
+    await waitFor(() =>
+      expect(getByTestId('isFetching').textContent).toBe('false'),
+    )
+    fireEvent.click(getByText('Increment value'))
+    await waitFor(() =>
+      expect(getByTestId('isFetching').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(getByTestId('isFetching').textContent).toBe('false'),
+    )
+    fireEvent.click(getByText('Increment value'))
+    // Being that nothing has changed in the args, this should never fire.
+    expect(getByTestId('isFetching').textContent).toBe('false')
+
+    // won't throw if nested, because context is different
+    expect(() =>
+      render(
+        <Provider store={configureStore({ reducer: () => null })}>
+          <ApiProvider api={customApi} context={customContext}>
+            child
+          </ApiProvider>
+        </Provider>,
+      ),
+    ).not.toThrow()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/baseQueryTypes.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/baseQueryTypes.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/baseQueryTypes.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,32 @@
+import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query'
+
+describe('type tests', () => {
+  test('BaseQuery meta types propagate to endpoint callbacks', () => {
+    createApi({
+      baseQuery: fetchBaseQuery(),
+      endpoints: (build) => ({
+        getDummy: build.query<null, undefined>({
+          query: () => 'dummy',
+          onCacheEntryAdded: async (arg, { cacheDataLoaded }) => {
+            const { meta } = await cacheDataLoaded
+            const { request, response } = meta! // Expect request and response to be there
+          },
+        }),
+      }),
+    })
+
+    const baseQuery = retry(fetchBaseQuery()) // Even when wrapped with retry
+    createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        getDummy: build.query<null, undefined>({
+          query: () => 'dummy',
+          onCacheEntryAdded: async (arg, { cacheDataLoaded }) => {
+            const { meta } = await cacheDataLoaded
+            const { request, response } = meta! // Expect request and response to be there
+          },
+        }),
+      }),
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildCreateApi.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildCreateApi.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildCreateApi.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,168 @@
+import { createSelectorCreator, lruMemoize } from '@reduxjs/toolkit'
+import {
+  buildCreateApi,
+  coreModule,
+  reactHooksModule,
+} from '@reduxjs/toolkit/query/react'
+import { render, screen, waitFor } from '@testing-library/react'
+import { delay } from 'msw'
+import * as React from 'react'
+import type { ReactReduxContextValue } from 'react-redux'
+import {
+  Provider,
+  createDispatchHook,
+  createSelectorHook,
+  createStoreHook,
+} from 'react-redux'
+import { setupApiStore, useRenderCounter } from '../../tests/utils/helpers'
+
+const MyContext = React.createContext<ReactReduxContextValue | null>(null)
+
+describe('buildCreateApi', () => {
+  test('Works with all hooks provided', async () => {
+    const customCreateApi = buildCreateApi(
+      coreModule(),
+      reactHooksModule({
+        hooks: {
+          useDispatch: createDispatchHook(MyContext),
+          useSelector: createSelectorHook(MyContext),
+          useStore: createStoreHook(MyContext),
+        },
+      }),
+    )
+
+    const api = customCreateApi({
+      baseQuery: async (arg: any) => {
+        await delay(150)
+
+        return {
+          data: arg?.body ? { ...arg.body } : {},
+        }
+      },
+      endpoints: (build) => ({
+        getUser: build.query<{ name: string }, number>({
+          query: () => ({
+            body: { name: 'Timmy' },
+          }),
+        }),
+      }),
+    })
+
+    let getRenderCount: () => number = () => 0
+
+    const storeRef = setupApiStore(api, {}, { withoutTestLifecycles: true })
+
+    // Copy of 'useQuery hook basic render count assumptions' from `buildHooks.test.tsx`
+    function User() {
+      const { isFetching } = api.endpoints.getUser.useQuery(1)
+      getRenderCount = useRenderCounter()
+
+      return (
+        <div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+        </div>
+      )
+    }
+
+    function Wrapper({ children }: any) {
+      return (
+        <Provider store={storeRef.store} context={MyContext}>
+          {children}
+        </Provider>
+      )
+    }
+
+    render(<User />, { wrapper: Wrapper })
+    // By the time this runs, the initial render will happen, and the query
+    //  will start immediately running by the time we can expect this
+    expect(getRenderCount()).toBe(2)
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+    expect(getRenderCount()).toBe(3)
+  })
+
+  test("Throws an error if you don't provide all hooks", async () => {
+    const callBuildCreateApi = () => {
+      const customCreateApi = buildCreateApi(
+        coreModule(),
+        reactHooksModule({
+          // @ts-ignore
+          hooks: {
+            useDispatch: createDispatchHook(MyContext),
+            useSelector: createSelectorHook(MyContext),
+          },
+        }),
+      )
+    }
+
+    expect(callBuildCreateApi).toThrowErrorMatchingInlineSnapshot(
+      `
+      [Error: When using custom hooks for context, all 3 hooks need to be provided: useDispatch, useSelector, useStore.
+      Hook useStore was either not provided or not a function.]
+    `,
+    )
+  })
+  test('allows passing createSelector instance', async () => {
+    const memoize = vi.fn(lruMemoize)
+    const createSelector = createSelectorCreator(memoize)
+    const createApi = buildCreateApi(
+      coreModule({ createSelector }),
+      reactHooksModule({ createSelector }),
+    )
+    const api = createApi({
+      baseQuery: async (arg: any) => {
+        await delay(150)
+
+        return {
+          data: arg?.body ? { ...arg.body } : {},
+        }
+      },
+      endpoints: (build) => ({
+        getUser: build.query<{ name: string }, number>({
+          query: () => ({
+            body: { name: 'Timmy' },
+          }),
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, {}, { withoutTestLifecycles: true })
+
+    await storeRef.store.dispatch(api.endpoints.getUser.initiate(1))
+
+    const selectUser = api.endpoints.getUser.select(1)
+
+    expect(selectUser(storeRef.store.getState()).data).toEqual({
+      name: 'Timmy',
+    })
+
+    expect(memoize).toHaveBeenCalledTimes(4)
+
+    memoize.mockClear()
+
+    function User() {
+      const { isFetching } = api.endpoints.getUser.useQuery(1)
+
+      return (
+        <div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+        </div>
+      )
+    }
+
+    function Wrapper({ children }: any) {
+      return <Provider store={storeRef.store}>{children}</Provider>
+    }
+
+    render(<User />, { wrapper: Wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+
+    // select() + selectFromResult
+    expect(memoize).toHaveBeenCalledTimes(8)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildHooks.test-d.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildHooks.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildHooks.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,343 @@
+import type {
+  QueryStateSelector,
+  UseMutation,
+  UseQuery,
+} from '@internal/query/react/buildHooks'
+import { ANY } from '@internal/tests/utils/helpers'
+import type { SerializedError } from '@reduxjs/toolkit'
+import type {
+  QueryDefinition,
+  SubscriptionOptions,
+  TypedQueryStateSelector,
+} from '@reduxjs/toolkit/query/react'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+import { useState } from 'react'
+
+let amount = 0
+let nextItemId = 0
+
+interface Item {
+  id: number
+}
+
+const api = createApi({
+  baseQuery: (arg: any) => {
+    if (arg?.body && 'amount' in arg.body) {
+      amount += 1
+    }
+
+    if (arg?.body && 'forceError' in arg.body) {
+      return {
+        error: {
+          status: 500,
+          data: null,
+        },
+      }
+    }
+
+    if (arg?.body && 'listItems' in arg.body) {
+      const items: Item[] = []
+      for (let i = 0; i < 3; i++) {
+        const item = { id: nextItemId++ }
+        items.push(item)
+      }
+      return { data: items }
+    }
+
+    return {
+      data: arg?.body ? { ...arg.body, ...(amount ? { amount } : {}) } : {},
+    }
+  },
+  endpoints: (build) => ({
+    getUser: build.query<{ name: string }, number>({
+      query: () => ({
+        body: { name: 'Timmy' },
+      }),
+    }),
+    getUserAndForceError: build.query<{ name: string }, number>({
+      query: () => ({
+        body: {
+          forceError: true,
+        },
+      }),
+    }),
+    getIncrementedAmount: build.query<{ amount: number }, void>({
+      query: () => ({
+        url: '',
+        body: {
+          amount,
+        },
+      }),
+    }),
+    updateUser: build.mutation<{ name: string }, { name: string }>({
+      query: (update) => ({ body: update }),
+    }),
+    getError: build.query({
+      query: () => '/error',
+    }),
+    listItems: build.query<Item[], { pageNumber: number }>({
+      serializeQueryArgs: ({ endpointName }) => {
+        return endpointName
+      },
+      query: ({ pageNumber }) => ({
+        url: `items?limit=1&offset=${pageNumber}`,
+        body: {
+          listItems: true,
+        },
+      }),
+      merge: (currentCache, newItems) => {
+        currentCache.push(...newItems)
+      },
+      forceRefetch: () => {
+        return true
+      },
+    }),
+  }),
+})
+
+describe('type tests', () => {
+  test('useLazyQuery hook callback returns various properties to handle the result', () => {
+    function User() {
+      const [getUser] = api.endpoints.getUser.useLazyQuery()
+      const [{ successMsg, errMsg, isAborted }, setValues] = useState({
+        successMsg: '',
+        errMsg: '',
+        isAborted: false,
+      })
+
+      const handleClick = (abort: boolean) => async () => {
+        const res = getUser(1)
+
+        // no-op simply for clearer type assertions
+        res.then((result) => {
+          if (result.isSuccess) {
+            expectTypeOf(result).toMatchTypeOf<{
+              data: {
+                name: string
+              }
+            }>()
+          }
+
+          if (result.isError) {
+            expectTypeOf(result).toMatchTypeOf<{
+              error: { status: number; data: unknown } | SerializedError
+            }>()
+          }
+        })
+
+        expectTypeOf(res.arg).toBeNumber()
+
+        expectTypeOf(res.requestId).toBeString()
+
+        expectTypeOf(res.abort).toEqualTypeOf<() => void>()
+
+        expectTypeOf(res.unsubscribe).toEqualTypeOf<() => void>()
+
+        expectTypeOf(res.updateSubscriptionOptions).toEqualTypeOf<
+          (options: SubscriptionOptions) => void
+        >()
+
+        expectTypeOf(res.refetch).toMatchTypeOf<() => void>()
+
+        expectTypeOf(res.unwrap()).resolves.toEqualTypeOf<{ name: string }>()
+      }
+
+      return (
+        <div>
+          <button onClick={handleClick(false)}>Fetch User successfully</button>
+          <button onClick={handleClick(true)}>Fetch User and abort</button>
+          <div>{successMsg}</div>
+          <div>{errMsg}</div>
+          <div>{isAborted ? 'Request was aborted' : ''}</div>
+        </div>
+      )
+    }
+  })
+
+  test('useMutation hook callback returns various properties to handle the result', async () => {
+    function User() {
+      const [updateUser] = api.endpoints.updateUser.useMutation()
+      const [successMsg, setSuccessMsg] = useState('')
+      const [errMsg, setErrMsg] = useState('')
+      const [isAborted, setIsAborted] = useState(false)
+
+      const handleClick = async () => {
+        const res = updateUser({ name: 'Banana' })
+
+        expectTypeOf(res).resolves.toMatchTypeOf<
+          | {
+              error: { status: number; data: unknown } | SerializedError
+            }
+          | {
+              data: {
+                name: string
+              }
+            }
+        >()
+
+        expectTypeOf(res.arg).toMatchTypeOf<{
+          endpointName: string
+          originalArgs: { name: string }
+          track?: boolean
+        }>()
+
+        expectTypeOf(res.requestId).toBeString()
+
+        expectTypeOf(res.abort).toEqualTypeOf<() => void>()
+
+        expectTypeOf(res.unwrap()).resolves.toEqualTypeOf<{ name: string }>()
+
+        expectTypeOf(res.reset).toEqualTypeOf<() => void>()
+      }
+
+      return (
+        <div>
+          <button onClick={handleClick}>Update User and abort</button>
+          <div>{successMsg}</div>
+          <div>{errMsg}</div>
+          <div>{isAborted ? 'Request was aborted' : ''}</div>
+        </div>
+      )
+    }
+  })
+
+  test('top level named hooks', () => {
+    interface Post {
+      id: number
+      name: string
+      fetched_at: string
+    }
+
+    type PostsResponse = Post[]
+
+    const api = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/' }),
+      tagTypes: ['Posts'],
+      endpoints: (build) => ({
+        getPosts: build.query<PostsResponse, void>({
+          query: () => ({ url: 'posts' }),
+          providesTags: (result) =>
+            result ? result.map(({ id }) => ({ type: 'Posts', id })) : [],
+        }),
+        updatePost: build.mutation<Post, Partial<Post>>({
+          query: ({ id, ...body }) => ({
+            url: `post/${id}`,
+            method: 'PUT',
+            body,
+          }),
+          invalidatesTags: (result, error, { id }) => [{ type: 'Posts', id }],
+        }),
+        addPost: build.mutation<Post, Partial<Post>>({
+          query: (body) => ({
+            url: `post`,
+            method: 'POST',
+            body,
+          }),
+          invalidatesTags: ['Posts'],
+        }),
+      }),
+    })
+
+    expectTypeOf(api.useGetPostsQuery).toEqualTypeOf(
+      api.endpoints.getPosts.useQuery,
+    )
+
+    expectTypeOf(api.useUpdatePostMutation).toEqualTypeOf(
+      api.endpoints.updatePost.useMutation,
+    )
+
+    expectTypeOf(api.useAddPostMutation).toEqualTypeOf(
+      api.endpoints.addPost.useMutation,
+    )
+  })
+
+  test('UseQuery type can be used to recreate the hook type', () => {
+    const fakeQuery = ANY as UseQuery<
+      typeof api.endpoints.getUser.Types.QueryDefinition
+    >
+
+    expectTypeOf(fakeQuery).toEqualTypeOf(api.endpoints.getUser.useQuery)
+  })
+
+  test('UseMutation type can be used to recreate the hook type', () => {
+    const fakeMutation = ANY as UseMutation<
+      typeof api.endpoints.updateUser.Types.MutationDefinition
+    >
+
+    expectTypeOf(fakeMutation).toEqualTypeOf(
+      api.endpoints.updateUser.useMutation,
+    )
+  })
+
+  test('TypedQueryStateSelector creates a pre-typed version of QueryStateSelector', () => {
+    type Post = {
+      id: number
+      title: string
+    }
+
+    type PostsApiResponse = {
+      posts: Post[]
+      total: number
+      skip: number
+      limit: number
+    }
+
+    type QueryArgument = number | undefined
+
+    type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
+
+    type SelectedResult = Pick<PostsApiResponse, 'posts'>
+
+    const postsApiSlice = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),
+      reducerPath: 'postsApi',
+      tagTypes: ['Posts'],
+      endpoints: (build) => ({
+        getPosts: build.query<PostsApiResponse, QueryArgument>({
+          query: (limit = 5) => `?limit=${limit}&select=title`,
+        }),
+      }),
+    })
+
+    const { useGetPostsQuery } = postsApiSlice
+
+    function PostById({ id }: { id: number }) {
+      const { post } = useGetPostsQuery(undefined, {
+        selectFromResult: (state) => ({
+          post: state.data?.posts.find((post) => post.id === id),
+        }),
+      })
+
+      expectTypeOf(post).toEqualTypeOf<Post | undefined>()
+
+      return <li>{post?.title}</li>
+    }
+
+    const EMPTY_ARRAY: Post[] = []
+
+    const typedSelectFromResult: TypedQueryStateSelector<
+      PostsApiResponse,
+      QueryArgument,
+      BaseQueryFunction,
+      SelectedResult
+    > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })
+
+    function PostsList() {
+      const { posts } = useGetPostsQuery(undefined, {
+        selectFromResult: typedSelectFromResult,
+      })
+
+      expectTypeOf(posts).toEqualTypeOf<Post[]>()
+
+      return (
+        <div>
+          <ul>
+            {posts.map((post) => (
+              <PostById key={post.id} id={post.id} />
+            ))}
+          </ul>
+        </div>
+      )
+    }
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildHooks.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildHooks.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildHooks.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,4142 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import type { SubscriptionOptions } from '@internal/query/core/apiState'
+import type { SubscriptionSelectors } from '@internal/query/core/buildMiddleware/types'
+import { server } from '@internal/query/tests/mocks/server'
+import { countObjectKeys } from '@internal/query/utils/countObjectKeys'
+import {
+  actionsReducer,
+  setupApiStore,
+  useRenderCounter,
+  waitForFakeTimer,
+  waitMs,
+  withProvider,
+} from '@internal/tests/utils/helpers'
+import type { UnknownAction } from '@reduxjs/toolkit'
+import {
+  configureStore,
+  createListenerMiddleware,
+  createSlice,
+} from '@reduxjs/toolkit'
+import {
+  QueryStatus,
+  createApi,
+  fetchBaseQuery,
+  skipToken,
+} from '@reduxjs/toolkit/query/react'
+import {
+  act,
+  fireEvent,
+  render,
+  renderHook,
+  screen,
+  waitFor,
+} from '@testing-library/react'
+import { userEvent } from '@testing-library/user-event'
+import type { SyncScreen } from '@testing-library/react-render-stream/pure'
+import { createRenderStream } from '@testing-library/react-render-stream/pure'
+import { HttpResponse, http, delay } from 'msw'
+import { useEffect, useMemo, useRef, useState } from 'react'
+import type { InfiniteQueryResultFlags } from '../core/buildSelectors'
+
+// Just setup a temporary in-memory counter for tests that `getIncrementedAmount`.
+// This can be used to test how many renders happen due to data changes or
+// the refetching behavior of components.
+let amount = 0
+let nextItemId = 0
+let refetchCount = 0
+
+interface Item {
+  id: number
+}
+
+const api = createApi({
+  baseQuery: async (arg: any) => {
+    await waitForFakeTimer(150)
+    if (arg?.body && 'amount' in arg.body) {
+      amount += 1
+    }
+
+    if (arg?.body && 'forceError' in arg.body) {
+      return {
+        error: {
+          status: 500,
+          data: null,
+        },
+      }
+    }
+
+    if (arg?.body && 'listItems' in arg.body) {
+      const items: Item[] = []
+      for (let i = 0; i < 3; i++) {
+        const item = { id: nextItemId++ }
+        items.push(item)
+      }
+      return { data: items }
+    }
+
+    return {
+      data: arg?.body ? { ...arg.body, ...(amount ? { amount } : {}) } : {},
+    }
+  },
+  tagTypes: ['IncrementedAmount'],
+  endpoints: (build) => ({
+    getUser: build.query<{ name: string }, number>({
+      query: () => ({
+        body: { name: 'Timmy' },
+      }),
+    }),
+    getUserAndForceError: build.query<{ name: string }, number>({
+      query: () => ({
+        body: {
+          forceError: true,
+        },
+      }),
+    }),
+    getUserWithRefetchError: build.query<{ name: string }, number>({
+      queryFn: async (id) => {
+        refetchCount += 1
+
+        if (refetchCount > 1) {
+          return { error: true } as any
+        }
+
+        return { data: { name: 'Timmy' } }
+      },
+    }),
+    getIncrementedAmount: build.query<{ amount: number }, void>({
+      query: () => ({
+        url: '',
+        body: {
+          amount,
+        },
+      }),
+      providesTags: ['IncrementedAmount'],
+    }),
+    triggerUpdatedAmount: build.mutation<void, void>({
+      queryFn: async () => {
+        return { data: undefined }
+      },
+      invalidatesTags: ['IncrementedAmount'],
+    }),
+    updateUser: build.mutation<{ name: string }, { name: string }>({
+      query: (update) => ({ body: update }),
+    }),
+    getError: build.query({
+      query: () => '/error',
+    }),
+    listItems: build.query<Item[], { pageNumber: number | bigint }>({
+      serializeQueryArgs: ({ endpointName }) => {
+        return endpointName
+      },
+      query: ({ pageNumber }) => ({
+        url: `items?limit=1&offset=${pageNumber}`,
+        body: {
+          listItems: true,
+        },
+      }),
+      merge: (currentCache, newItems) => {
+        currentCache.push(...newItems)
+      },
+      forceRefetch: () => {
+        return true
+      },
+    }),
+    queryWithDeepArg: build.query<string, { param: { nested: string } }>({
+      query: ({ param: { nested } }) => nested,
+      serializeQueryArgs: ({ queryArgs }) => {
+        return queryArgs.param.nested
+      },
+    }),
+  }),
+})
+
+const listenerMiddleware = createListenerMiddleware()
+
+let actions: UnknownAction[] = []
+
+const storeRef = setupApiStore(
+  api,
+  {},
+  {
+    middleware: {
+      prepend: [listenerMiddleware.middleware],
+    },
+  },
+)
+
+let getSubscriptions: SubscriptionSelectors['getSubscriptions']
+let getSubscriptionCount: SubscriptionSelectors['getSubscriptionCount']
+
+beforeEach(() => {
+  actions = []
+  listenerMiddleware.startListening({
+    predicate: () => true,
+    effect: (action) => {
+      actions.push(action)
+    },
+  })
+  ;({ getSubscriptions, getSubscriptionCount } = storeRef.store.dispatch(
+    api.internalActions.internal_getRTKQSubscriptions(),
+  ) as unknown as SubscriptionSelectors)
+})
+
+afterEach(() => {
+  nextItemId = 0
+  amount = 0
+  listenerMiddleware.clearListeners()
+
+  server.resetHandlers()
+})
+
+let getRenderCount: () => number = () => 0
+
+describe('hooks tests', () => {
+  describe('useQuery', () => {
+    test('useQuery hook basic render count assumptions', async () => {
+      function User() {
+        const { isFetching } = api.endpoints.getUser.useQuery(1)
+        getRenderCount = useRenderCounter()
+
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      // By the time this runs, the initial render will happen, and the query
+      //  will start immediately running by the time we can expect this
+      expect(getRenderCount()).toBe(2)
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      expect(getRenderCount()).toBe(3)
+    })
+
+    test('useQuery hook sets isFetching=true whenever a request is in flight', async () => {
+      function User() {
+        const [value, setValue] = useState(0)
+
+        const { isFetching } = api.endpoints.getUser.useQuery(1, {
+          skip: value < 1,
+        })
+        getRenderCount = useRenderCounter()
+
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button onClick={() => setValue((val) => val + 1)}>
+              Increment value
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      expect(getRenderCount()).toBe(1)
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      fireEvent.click(screen.getByText('Increment value')) // setState = 1, perform request = 2
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      expect(getRenderCount()).toBe(4)
+
+      fireEvent.click(screen.getByText('Increment value'))
+      // Being that nothing has changed in the args, this should never fire.
+      expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      expect(getRenderCount()).toBe(5) // even though there was no request, the button click updates the state so this is an expected render
+    })
+
+    test('useQuery hook sets isLoading=true only on initial request', async () => {
+      let refetch: any, isLoading: boolean, isFetching: boolean
+      function User() {
+        const [value, setValue] = useState(0)
+
+        ;({ isLoading, isFetching, refetch } = api.endpoints.getUser.useQuery(
+          2,
+          {
+            skip: value < 1,
+          },
+        ))
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button onClick={() => setValue((val) => val + 1)}>
+              Increment value
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      // Being that we skipped the initial request on mount, this should be false
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+      fireEvent.click(screen.getByText('Increment value'))
+      // Condition is met, should load
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      ) // Make sure the original loading has completed.
+      fireEvent.click(screen.getByText('Increment value'))
+      // Being that we already have data, isLoading should be false
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+      // We call a refetch, should still be `false`
+      act(() => void refetch())
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      expect(screen.getByTestId('isLoading').textContent).toBe('false')
+    })
+
+    test('useQuery hook sets isLoading and isFetching to the correct states', async () => {
+      let refetchMe: () => void = () => {}
+      function User() {
+        const [value, setValue] = useState(0)
+        getRenderCount = useRenderCounter()
+
+        const { isLoading, isFetching, refetch } =
+          api.endpoints.getUser.useQuery(22, { skip: value < 1 })
+        refetchMe = refetch
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <button onClick={() => setValue((val) => val + 1)}>
+              Increment value
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      expect(getRenderCount()).toBe(1)
+
+      expect(screen.getByTestId('isLoading').textContent).toBe('false')
+      expect(screen.getByTestId('isFetching').textContent).toBe('false')
+
+      fireEvent.click(screen.getByText('Increment value')) // renders: set state = 1, perform request = 2
+      // Condition is met, should load
+      await waitFor(() => {
+        expect(screen.getByTestId('isLoading').textContent).toBe('true')
+        expect(screen.getByTestId('isFetching').textContent).toBe('true')
+      })
+
+      // Make sure the request is done for sure.
+      await waitFor(() => {
+        expect(screen.getByTestId('isLoading').textContent).toBe('false')
+        expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      })
+      expect(getRenderCount()).toBe(4)
+
+      fireEvent.click(screen.getByText('Increment value'))
+      // Being that we already have data and changing the value doesn't trigger a new request, only the button click should impact the render
+      await waitFor(() => {
+        expect(screen.getByTestId('isLoading').textContent).toBe('false')
+        expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      })
+      expect(getRenderCount()).toBe(5)
+
+      // We call a refetch, should set `isFetching` to true, then false when complete/errored
+      act(() => void refetchMe())
+      await waitFor(() => {
+        expect(screen.getByTestId('isLoading').textContent).toBe('false')
+        expect(screen.getByTestId('isFetching').textContent).toBe('true')
+      })
+      await waitFor(() => {
+        expect(screen.getByTestId('isLoading').textContent).toBe('false')
+        expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      })
+      expect(getRenderCount()).toBe(7)
+    })
+
+    test('`isLoading` does not jump back to true, while `isFetching` does', async () => {
+      const loadingHist: boolean[] = [],
+        fetchingHist: boolean[] = []
+
+      function User({ id }: { id: number }) {
+        const { isLoading, isFetching, status } =
+          api.endpoints.getUser.useQuery(id)
+
+        useEffect(() => {
+          loadingHist.push(isLoading)
+        }, [isLoading])
+        useEffect(() => {
+          fetchingHist.push(isFetching)
+        }, [isFetching])
+        return (
+          <div data-testid="status">
+            {status === QueryStatus.fulfilled && id}
+          </div>
+        )
+      }
+
+      let { rerender } = render(<User id={1} />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('1'),
+      )
+      rerender(<User id={2} />)
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('2'),
+      )
+
+      expect(loadingHist).toEqual([true, false])
+      expect(fetchingHist).toEqual([true, false, true, false])
+    })
+
+    test('`isSuccess` does not jump back false on subsequent queries', async () => {
+      type LoadingState = {
+        id: number
+        isFetching: boolean
+        isSuccess: boolean
+      }
+      const loadingHistory: LoadingState[] = []
+
+      function User({ id }: { id: number }) {
+        const queryRes = api.endpoints.getUser.useQuery(id)
+
+        useEffect(() => {
+          const { isFetching, isSuccess } = queryRes
+          loadingHistory.push({ id, isFetching, isSuccess })
+        }, [id, queryRes])
+        return (
+          <div data-testid="status">
+            {queryRes.status === QueryStatus.fulfilled && id}
+          </div>
+        )
+      }
+
+      let { rerender } = render(<User id={1} />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('1'),
+      )
+      rerender(<User id={2} />)
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('2'),
+      )
+
+      expect(loadingHistory).toEqual([
+        // Initial render(s)
+        { id: 1, isFetching: true, isSuccess: false },
+        { id: 1, isFetching: true, isSuccess: false },
+        // Data returned
+        { id: 1, isFetching: false, isSuccess: true },
+        // ID changed, there's an uninitialized cache entry.
+        // IMPORTANT: `isSuccess` should not be false here.
+        // We have valid data already for the old item.
+        { id: 2, isFetching: true, isSuccess: true },
+        { id: 2, isFetching: true, isSuccess: true },
+        { id: 2, isFetching: false, isSuccess: true },
+      ])
+    })
+
+    test('isSuccess stays consistent if there is an error while refetching', async () => {
+      type LoadingState = {
+        id: number
+        isFetching: boolean
+        isSuccess: boolean
+        isError: boolean
+      }
+      const loadingHistory: LoadingState[] = []
+
+      function Component({ id = 1 }) {
+        const queryRes = api.endpoints.getUserWithRefetchError.useQuery(id)
+        const { refetch, data, status } = queryRes
+
+        useEffect(() => {
+          const { isFetching, isSuccess, isError } = queryRes
+          loadingHistory.push({ id, isFetching, isSuccess, isError })
+        }, [id, queryRes])
+
+        return (
+          <div>
+            <button
+              onClick={() => {
+                refetch()
+              }}
+            >
+              refetch
+            </button>
+            <div data-testid="name">{data?.name}</div>
+            <div data-testid="status">{status}</div>
+          </div>
+        )
+      }
+
+      render(<Component />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('name').textContent).toBe('Timmy'),
+      )
+
+      fireEvent.click(screen.getByText('refetch'))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('pending'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('rejected'),
+      )
+
+      fireEvent.click(screen.getByText('refetch'))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('pending'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('rejected'),
+      )
+
+      expect(loadingHistory).toEqual([
+        // Initial renders
+        { id: 1, isFetching: true, isSuccess: false, isError: false },
+        { id: 1, isFetching: true, isSuccess: false, isError: false },
+        // Data is returned
+        { id: 1, isFetching: false, isSuccess: true, isError: false },
+        // Started first refetch
+        { id: 1, isFetching: true, isSuccess: true, isError: false },
+        // First refetch errored
+        { id: 1, isFetching: false, isSuccess: false, isError: true },
+        // Started second refetch
+        // IMPORTANT We expect `isSuccess` to still be false,
+        // despite having started the refetch again.
+        { id: 1, isFetching: true, isSuccess: false, isError: false },
+        // Second refetch errored
+        { id: 1, isFetching: false, isSuccess: false, isError: true },
+      ])
+    })
+
+    test('useQuery hook respects refetchOnMountOrArgChange: true', async () => {
+      let data, isLoading, isFetching
+      function User() {
+        ;({ data, isLoading, isFetching } =
+          api.endpoints.getIncrementedAmount.useQuery(undefined, {
+            refetchOnMountOrArgChange: true,
+          }))
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <div data-testid="amount">{String(data?.amount)}</div>
+          </div>
+        )
+      }
+
+      const { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('1'),
+      )
+
+      unmount()
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      // Let's make sure we actually fetch, and we increment
+      expect(screen.getByTestId('isLoading').textContent).toBe('false')
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('2'),
+      )
+    })
+
+    test('useQuery does not refetch when refetchOnMountOrArgChange: NUMBER condition is not met', async () => {
+      let data, isLoading, isFetching
+      function User() {
+        ;({ data, isLoading, isFetching } =
+          api.endpoints.getIncrementedAmount.useQuery(undefined, {
+            refetchOnMountOrArgChange: 10,
+          }))
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <div data-testid="amount">{String(data?.amount)}</div>
+          </div>
+        )
+      }
+
+      const { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('1'),
+      )
+
+      unmount()
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      // Let's make sure we actually fetch, and we increment. Should be false because we do this immediately
+      // and the condition is set to 10 seconds
+      expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('1'),
+      )
+    })
+
+    test('useQuery refetches when refetchOnMountOrArgChange: NUMBER condition is met', async () => {
+      let data, isLoading, isFetching
+      function User() {
+        ;({ data, isLoading, isFetching } =
+          api.endpoints.getIncrementedAmount.useQuery(undefined, {
+            refetchOnMountOrArgChange: 0.5,
+          }))
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <div data-testid="amount">{String(data?.amount)}</div>
+          </div>
+        )
+      }
+
+      const { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('1'),
+      )
+
+      unmount()
+
+      // Wait to make sure we've passed the `refetchOnMountOrArgChange` value
+      await waitMs(510)
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      // Let's make sure we actually fetch, and we increment
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('2'),
+      )
+    })
+
+    test('refetchOnMountOrArgChange works as expected when changing skip from false->true', async () => {
+      let data, isLoading, isFetching
+      function User() {
+        const [skip, setSkip] = useState(true)
+        ;({ data, isLoading, isFetching } =
+          api.endpoints.getIncrementedAmount.useQuery(undefined, {
+            refetchOnMountOrArgChange: 0.5,
+            skip,
+          }))
+
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <div data-testid="amount">{String(data?.amount)}</div>
+            <button onClick={() => setSkip((prev) => !prev)}>
+              change skip
+            </button>
+            ;
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      expect(screen.getByTestId('isLoading').textContent).toBe('false')
+      expect(screen.getByTestId('amount').textContent).toBe('undefined')
+
+      fireEvent.click(screen.getByText('change skip'))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('1'),
+      )
+    })
+
+    test('refetchOnMountOrArgChange works as expected when changing skip from false->true with a cached query', async () => {
+      // 1. we need to mount a skipped query, then toggle skip to generate a cached result
+      // 2. we need to mount a skipped component after that, then toggle skip as well. should pull from the cache.
+      // 3. we need to mount another skipped component, then toggle skip after the specified duration and expect the time condition to be satisfied
+
+      let data, isLoading, isFetching
+      function User() {
+        const [skip, setSkip] = useState(true)
+        ;({ data, isLoading, isFetching } =
+          api.endpoints.getIncrementedAmount.useQuery(undefined, {
+            skip,
+            refetchOnMountOrArgChange: 0.5,
+          }))
+
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <div data-testid="amount">{String(data?.amount)}</div>
+            <button onClick={() => setSkip((prev) => !prev)}>
+              change skip
+            </button>
+            ;
+          </div>
+        )
+      }
+
+      let { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+      expect(screen.getByTestId('isFetching').textContent).toBe('false')
+
+      // skipped queries do nothing by default, so we need to toggle that to get a cached result
+      fireEvent.click(screen.getByText('change skip'))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+
+      await waitFor(() => {
+        expect(screen.getByTestId('amount').textContent).toBe('1')
+        expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      })
+
+      unmount()
+
+      await waitMs(100)
+
+      // This will pull from the cache as the time criteria is not met.
+      ;({ unmount } = render(<User />, {
+        wrapper: storeRef.wrapper,
+      }))
+
+      // skipped queries return nothing
+      expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      expect(screen.getByTestId('amount').textContent).toBe('undefined')
+
+      // toggle skip -> true... won't refetch as the time critera is not met, and just loads the cached values
+      fireEvent.click(screen.getByText('change skip'))
+      expect(screen.getByTestId('isFetching').textContent).toBe('false')
+      expect(screen.getByTestId('amount').textContent).toBe('1')
+
+      unmount()
+
+      await waitMs(500)
+      ;({ unmount } = render(<User />, {
+        wrapper: storeRef.wrapper,
+      }))
+
+      // toggle skip -> true... will cause a refetch as the time criteria is now satisfied
+      fireEvent.click(screen.getByText('change skip'))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      await waitFor(() =>
+        expect(screen.getByTestId('amount').textContent).toBe('2'),
+      )
+    })
+
+    test(`useQuery refetches when query args object changes even if serialized args don't change`, async () => {
+      const user = userEvent.setup()
+
+      function ItemList() {
+        const [pageNumber, setPageNumber] = useState(0)
+        const { data = [] } = api.useListItemsQuery({
+          pageNumber,
+        })
+
+        const renderedItems = data.map((item) => (
+          <li key={item.id}>ID: {item.id}</li>
+        ))
+        return (
+          <div>
+            <button onClick={() => setPageNumber(pageNumber + 1)}>
+              Next Page
+            </button>
+            <ul>{renderedItems}</ul>
+          </div>
+        )
+      }
+
+      render(<ItemList />, { wrapper: storeRef.wrapper })
+
+      await screen.findByText('ID: 0')
+
+      await user.click(screen.getByText('Next Page'))
+
+      await screen.findByText('ID: 3')
+    })
+
+    test(`useQuery shouldn't call args serialization if request skipped`, async () => {
+      expect(() =>
+        renderHook(() => api.endpoints.queryWithDeepArg.useQuery(skipToken), {
+          wrapper: storeRef.wrapper,
+        }),
+      ).not.toThrow()
+    })
+
+    test(`useQuery gracefully handles bigint types`, async () => {
+      const user = userEvent.setup()
+
+      function ItemList() {
+        const [pageNumber, setPageNumber] = useState(0)
+        const { data = [] } = api.useListItemsQuery({
+          pageNumber: BigInt(pageNumber),
+        })
+
+        const renderedItems = data.map((item) => (
+          <li key={item.id}>ID: {item.id}</li>
+        ))
+        return (
+          <div>
+            <button onClick={() => setPageNumber(pageNumber + 1)}>
+              Next Page
+            </button>
+            <ul>{renderedItems}</ul>
+          </div>
+        )
+      }
+
+      render(<ItemList />, { wrapper: storeRef.wrapper })
+
+      await screen.findByText('ID: 0')
+
+      await user.click(screen.getByText('Next Page'))
+
+      await screen.findByText('ID: 3')
+    })
+
+    describe('api.util.resetApiState resets hook', () => {
+      test('without `selectFromResult`', async () => {
+        const { result } = renderHook(() => api.endpoints.getUser.useQuery(5), {
+          wrapper: storeRef.wrapper,
+        })
+
+        await waitFor(() => expect(result.current.isSuccess).toBe(true))
+
+        act(() => void storeRef.store.dispatch(api.util.resetApiState()))
+
+        expect(result.current).toEqual(
+          expect.objectContaining({
+            isError: false,
+            isFetching: true,
+            isLoading: true,
+            isSuccess: false,
+            isUninitialized: false,
+            refetch: expect.any(Function),
+            status: 'pending',
+          }),
+        )
+      })
+      test('with `selectFromResult`', async () => {
+        const selectFromResult = vi.fn((x) => x)
+        const { result } = renderHook(
+          () => api.endpoints.getUser.useQuery(5, { selectFromResult }),
+          {
+            wrapper: storeRef.wrapper,
+          },
+        )
+
+        await waitFor(() => expect(result.current.isSuccess).toBe(true))
+        selectFromResult.mockClear()
+        act(() => {
+          storeRef.store.dispatch(api.util.resetApiState())
+        })
+
+        expect(selectFromResult).toHaveBeenNthCalledWith(1, {
+          isError: false,
+          isFetching: false,
+          isLoading: false,
+          isSuccess: false,
+          isUninitialized: true,
+          status: 'uninitialized',
+        })
+      })
+
+      test('hook should not be stuck loading post resetApiState after re-render', async () => {
+        const user = userEvent.setup()
+
+        function QueryComponent() {
+          const { isLoading, data } = api.endpoints.getUser.useQuery(1)
+
+          if (isLoading) {
+            return <p>Loading...</p>
+          }
+
+          return <p>{data?.name}</p>
+        }
+
+        function Wrapper() {
+          const [open, setOpen] = useState(true)
+
+          const handleRerender = () => {
+            setOpen(false)
+            setTimeout(() => {
+              setOpen(true)
+            }, 250)
+          }
+
+          const handleReset = () => {
+            storeRef.store.dispatch(api.util.resetApiState())
+          }
+
+          return (
+            <>
+              <button onClick={handleRerender} aria-label="Rerender component">
+                Rerender
+              </button>
+              {open ? (
+                <div>
+                  <button onClick={handleReset} aria-label="Reset API state">
+                    Reset
+                  </button>
+
+                  <QueryComponent />
+                </div>
+              ) : null}
+            </>
+          )
+        }
+
+        render(<Wrapper />, { wrapper: storeRef.wrapper })
+
+        await user.click(
+          screen.getByRole('button', { name: /Rerender component/i }),
+        )
+        await waitFor(() => {
+          expect(screen.getByText('Timmy')).toBeTruthy()
+        })
+
+        await user.click(
+          screen.getByRole('button', { name: /reset api state/i }),
+        )
+        await waitFor(() => {
+          expect(screen.queryByText('Loading...')).toBeNull()
+        })
+        await waitFor(() => {
+          expect(screen.getByText('Timmy')).toBeTruthy()
+        })
+      })
+    })
+
+    test('useQuery refetch method returns a promise that resolves with the result', async () => {
+      const { result } = renderHook(
+        () => api.endpoints.getIncrementedAmount.useQuery(),
+        {
+          wrapper: storeRef.wrapper,
+        },
+      )
+
+      await waitFor(() => expect(result.current.isSuccess).toBe(true))
+      const originalAmount = result.current.data!.amount
+
+      const { refetch } = result.current
+
+      let resPromise: ReturnType<typeof refetch> = null as any
+      await act(async () => {
+        resPromise = refetch()
+      })
+      expect(resPromise).toBeInstanceOf(Promise)
+      const res = await act(() => resPromise)
+      expect(res.data!.amount).toBeGreaterThan(originalAmount)
+    })
+
+    // See https://github.com/reduxjs/redux-toolkit/issues/4267 - Memory leak in useQuery rapid query arg changes
+    test('Hook subscriptions are properly cleaned up when query is fulfilled/rejected', async () => {
+      // This is imported already, but it seems to be causing issues with the test on certain matrixes
+
+      const pokemonApi = createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+        endpoints: (builder) => ({
+          getTest: builder.query<string, number>({
+            async queryFn() {
+              await new Promise((resolve) => setTimeout(resolve, 1000))
+              return { data: 'data!' }
+            },
+            keepUnusedDataFor: 0,
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(pokemonApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const checkNumQueries = (count: number) => {
+        const cacheEntries = Object.keys(storeRef.store.getState().api.queries)
+        const queries = cacheEntries.length
+
+        expect(queries).toBe(count)
+      }
+
+      let i = 0
+
+      function User() {
+        const [fetchTest, { isFetching, isUninitialized }] =
+          pokemonApi.endpoints.getTest.useLazyQuery()
+
+        return (
+          <div>
+            <div data-testid="isUninitialized">{String(isUninitialized)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button data-testid="fetchButton" onClick={() => fetchTest(i++)}>
+              fetchUser
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      fireEvent.click(screen.getByTestId('fetchButton'))
+      fireEvent.click(screen.getByTestId('fetchButton'))
+      fireEvent.click(screen.getByTestId('fetchButton'))
+      checkNumQueries(3)
+
+      await act(async () => {
+        await delay(1500)
+      })
+
+      // There should only be one stored query once they have had time to resolve
+      checkNumQueries(1)
+    })
+
+    // See https://github.com/reduxjs/redux-toolkit/issues/3182
+    test('Hook subscriptions are properly cleaned up when changing skip back and forth', async () => {
+      const pokemonApi = createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+        endpoints: (builder) => ({
+          getPokemonByName: builder.query({
+            queryFn: (name: string) => ({ data: null }),
+            keepUnusedDataFor: 1,
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(pokemonApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const checkNumSubscriptions = (arg: string, count: number) => {
+        const subscriptions = getSubscriptions()
+        const cacheKeyEntry = subscriptions.get(arg)
+
+        if (cacheKeyEntry) {
+          const subscriptionCount = Object.keys(cacheKeyEntry) //getSubscriptionCount(arg)
+          expect(subscriptionCount).toBe(count)
+        }
+      }
+
+      // 1) Initial state: an active subscription
+      const { rerender, unmount } = renderHook(
+        ([arg, options]: Parameters<
+          typeof pokemonApi.useGetPokemonByNameQuery
+        >) => pokemonApi.useGetPokemonByNameQuery(arg, options),
+        {
+          wrapper: storeRef.wrapper,
+          initialProps: ['a'],
+        },
+      )
+
+      await act(async () => {
+        await waitMs(1)
+      })
+
+      // 2) Set the current subscription to `{skip: true}
+      rerender(['a', { skip: true }])
+
+      // 3) Change _both_ the cache key _and_ `{skip: false}` at the same time.
+      // This causes the `subscriptionRemoved` check to be `true`.
+      rerender(['b'])
+
+      // There should only be one active subscription after changing the arg
+      checkNumSubscriptions('b', 1)
+
+      // 4) Re-render with the same arg.
+      // This causes the `subscriptionRemoved` check to be `false`.
+      // Correct behavior is this does _not_ clear the promise ref,
+      // so
+      rerender(['b'])
+
+      // There should only be one active subscription after changing the arg
+      checkNumSubscriptions('b', 1)
+
+      await act(async () => {
+        await waitMs(1)
+      })
+
+      unmount()
+
+      await act(async () => {
+        await waitMs(1)
+      })
+
+      // There should be no subscription entries left over after changing
+      // cache key args and swapping `skip` on and off
+      checkNumSubscriptions('b', 0)
+
+      const finalSubscriptions = getSubscriptions()
+
+      for (const cacheKeyEntry of Object.values(finalSubscriptions)) {
+        expect(Object.values(cacheKeyEntry!).length).toBe(0)
+      }
+    })
+
+    test('Hook subscription failures do not reset isLoading state', async () => {
+      const states: boolean[] = []
+
+      function Parent() {
+        const { isLoading } = api.endpoints.getUserAndForceError.useQuery(1)
+
+        // Collect loading states to verify that it does not revert back to true.
+        states.push(isLoading)
+
+        // Parent conditionally renders child when loading.
+        if (isLoading) return null
+
+        return <Child />
+      }
+
+      function Child() {
+        // Using the same args as the parent
+        api.endpoints.getUserAndForceError.useQuery(1)
+
+        return null
+      }
+
+      render(<Parent />, { wrapper: storeRef.wrapper })
+
+      expect(states).toHaveLength(2)
+
+      // Allow at least three state effects to hit.
+      // Trying to see if any [true, false, true] occurs.
+      await act(async () => {
+        await waitForFakeTimer(150)
+      })
+
+      expect(states).toHaveLength(4)
+
+      await act(async () => {
+        await waitForFakeTimer(150)
+      })
+
+      expect(states).toHaveLength(5)
+
+      await act(async () => {
+        await waitForFakeTimer(150)
+      })
+
+      expect(states).toHaveLength(5)
+
+      // Find if at any time the isLoading state has reverted
+      // E.G.: `[..., true, false, ..., true]`
+      //              ^^^^  ^^^^^       ^^^^
+      const firstTrue = states.indexOf(true)
+      const firstFalse = states.slice(firstTrue).indexOf(false)
+      const revertedState = states.slice(firstFalse).indexOf(true)
+
+      expect(
+        revertedState,
+        `Expected isLoading state to never revert back to true but did after ${revertedState} renders...`,
+      ).toBe(-1)
+    })
+
+    test('query thunk should be aborted when component unmounts and cache entry is removed', async () => {
+      let abortSignalFromQueryFn: AbortSignal | undefined
+
+      const pokemonApi = createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+        endpoints: (builder) => ({
+          getTest: builder.query<string, number>({
+            async queryFn(arg, { signal }) {
+              abortSignalFromQueryFn = signal
+
+              // Simulate a long-running request that should be aborted
+              await new Promise((resolve, reject) => {
+                const timeout = setTimeout(resolve, 5000)
+
+                signal.addEventListener('abort', () => {
+                  clearTimeout(timeout)
+                  reject(new Error('Aborted'))
+                })
+              })
+
+              return { data: 'data!' }
+            },
+            keepUnusedDataFor: 0.01, // Very short timeout (10ms)
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(pokemonApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      function TestComponent() {
+        const { data, isFetching } = pokemonApi.endpoints.getTest.useQuery(1)
+
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <div data-testid="data">{data || 'no data'}</div>
+          </div>
+        )
+      }
+
+      function App() {
+        const [showComponent, setShowComponent] = useState(true)
+
+        return (
+          <div>
+            {showComponent && <TestComponent />}
+            <button
+              data-testid="unmount"
+              onClick={() => setShowComponent(false)}
+            >
+              Unmount Component
+            </button>
+          </div>
+        )
+      }
+
+      render(<App />, { wrapper: storeRef.wrapper })
+
+      // Wait for the query to start
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+
+      // Verify we have an abort signal
+      expect(abortSignalFromQueryFn).toBeDefined()
+      expect(abortSignalFromQueryFn!.aborted).toBe(false)
+
+      // Unmount the component
+      fireEvent.click(screen.getByTestId('unmount'))
+
+      // Wait for the cache entry to be removed (keepUnusedDataFor: 0.01s = 10ms)
+      await act(async () => {
+        await delay(100)
+      })
+
+      // The abort signal should now be aborted
+      expect(abortSignalFromQueryFn!.aborted).toBe(true)
+    })
+
+    describe('Hook middleware requirements', () => {
+      const consoleErrorSpy = vi
+        .spyOn(console, 'error')
+        .mockImplementation(noop)
+
+      afterEach(() => {
+        consoleErrorSpy.mockClear()
+      })
+
+      afterAll(() => {
+        consoleErrorSpy.mockRestore()
+      })
+
+      test('Throws error if middleware is not added to the store', async () => {
+        const store = configureStore({
+          reducer: {
+            [api.reducerPath]: api.reducer,
+          },
+        })
+
+        const doRender = () => {
+          renderHook(() => api.endpoints.getIncrementedAmount.useQuery(), {
+            wrapper: withProvider(store),
+          })
+        }
+
+        expect(doRender).toThrowError(
+          /Warning: Middleware for RTK-Query API at reducerPath "api" has not been added to the store/,
+        )
+      })
+    })
+  })
+
+  describe('useLazyQuery', () => {
+    let data: any
+
+    afterEach(() => {
+      data = undefined
+    })
+
+    let getRenderCount: () => number = () => 0
+    test('useLazyQuery does not automatically fetch when mounted and has undefined data', async () => {
+      function User() {
+        const [fetchUser, { data: hookData, isFetching, isUninitialized }] =
+          api.endpoints.getUser.useLazyQuery()
+        getRenderCount = useRenderCounter()
+
+        data = hookData
+
+        return (
+          <div>
+            <div data-testid="isUninitialized">{String(isUninitialized)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button data-testid="fetchButton" onClick={() => fetchUser(1)}>
+              fetchUser
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      expect(getRenderCount()).toBe(1)
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isUninitialized').textContent).toBe('true'),
+      )
+      await waitFor(() => expect(data).toBeUndefined())
+
+      fireEvent.click(screen.getByTestId('fetchButton'))
+      expect(getRenderCount()).toBe(2)
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isUninitialized').textContent).toBe('false'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      expect(getRenderCount()).toBe(3)
+
+      fireEvent.click(screen.getByTestId('fetchButton'))
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      expect(getRenderCount()).toBe(5)
+    })
+
+    test('useLazyQuery accepts updated subscription options and only dispatches updateSubscriptionOptions when values are updated', async () => {
+      let interval = 1000
+      function User() {
+        const [options, setOptions] = useState<SubscriptionOptions>()
+        const [fetchUser, { data: hookData, isFetching, isUninitialized }] =
+          api.endpoints.getUser.useLazyQuery(options)
+        getRenderCount = useRenderCounter()
+
+        data = hookData
+
+        return (
+          <div>
+            <div data-testid="isUninitialized">{String(isUninitialized)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+
+            <button data-testid="fetchButton" onClick={() => fetchUser(1)}>
+              fetchUser
+            </button>
+            <button
+              data-testid="updateOptions"
+              onClick={() =>
+                setOptions({
+                  pollingInterval: interval,
+                })
+              }
+            >
+              updateOptions
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      expect(getRenderCount()).toBe(1) // hook mount
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isUninitialized').textContent).toBe('true'),
+      )
+      await waitFor(() => expect(data).toBeUndefined())
+
+      fireEvent.click(screen.getByTestId('fetchButton'))
+      expect(getRenderCount()).toBe(2)
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      expect(getRenderCount()).toBe(3)
+
+      fireEvent.click(screen.getByTestId('updateOptions')) // setState = 1
+      expect(getRenderCount()).toBe(4)
+
+      fireEvent.click(screen.getByTestId('fetchButton')) // perform new request = 2
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      expect(getRenderCount()).toBe(6)
+
+      interval = 1000
+
+      fireEvent.click(screen.getByTestId('updateOptions')) // setState = 1
+      expect(getRenderCount()).toBe(7)
+
+      fireEvent.click(screen.getByTestId('fetchButton'))
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      expect(getRenderCount()).toBe(9)
+
+      expect(
+        actions.filter(api.internalActions.updateSubscriptionOptions.match),
+      ).toHaveLength(1)
+    })
+
+    test('useLazyQuery accepts updated args and unsubscribes the original query', async () => {
+      function User() {
+        const [fetchUser, { data: hookData, isFetching, isUninitialized }] =
+          api.endpoints.getUser.useLazyQuery()
+
+        data = hookData
+
+        return (
+          <div>
+            <div data-testid="isUninitialized">{String(isUninitialized)}</div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+
+            <button data-testid="fetchUser1" onClick={() => fetchUser(1)}>
+              fetchUser1
+            </button>
+            <button data-testid="fetchUser2" onClick={() => fetchUser(2)}>
+              fetchUser2
+            </button>
+          </div>
+        )
+      }
+
+      const { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isUninitialized').textContent).toBe('true'),
+      )
+      await waitFor(() => expect(data).toBeUndefined())
+
+      fireEvent.click(screen.getByTestId('fetchUser1'))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      // Being that there is only the initial query, no unsubscribe should be dispatched
+      expect(
+        actions.filter(api.internalActions.unsubscribeQueryResult.match),
+      ).toHaveLength(0)
+
+      fireEvent.click(screen.getByTestId('fetchUser2'))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      expect(
+        actions.filter(api.internalActions.unsubscribeQueryResult.match),
+      ).toHaveLength(1)
+
+      fireEvent.click(screen.getByTestId('fetchUser1'))
+
+      expect(
+        actions.filter(api.internalActions.unsubscribeQueryResult.match),
+      ).toHaveLength(2)
+
+      // we always unsubscribe the original promise and create a new one
+      fireEvent.click(screen.getByTestId('fetchUser1'))
+      expect(
+        actions.filter(api.internalActions.unsubscribeQueryResult.match),
+      ).toHaveLength(3)
+
+      unmount()
+
+      // We unsubscribe after the component unmounts
+      expect(
+        actions.filter(api.internalActions.unsubscribeQueryResult.match),
+      ).toHaveLength(4)
+    })
+
+    test('useLazyQuery hook callback returns various properties to handle the result', async () => {
+      const user = userEvent.setup()
+
+      function User() {
+        const [getUser] = api.endpoints.getUser.useLazyQuery()
+        const [{ successMsg, errMsg, isAborted }, setValues] = useState({
+          successMsg: '',
+          errMsg: '',
+          isAborted: false,
+        })
+
+        const handleClick = (abort: boolean) => async () => {
+          const res = getUser(1)
+
+          // abort the query immediately to force an error
+          if (abort) res.abort()
+          res
+            .unwrap()
+            .then((result) => {
+              setValues({
+                successMsg: `Successfully fetched user ${result.name}`,
+                errMsg: '',
+                isAborted: false,
+              })
+            })
+            .catch((err) => {
+              setValues({
+                successMsg: '',
+                errMsg: `An error has occurred fetching userId: ${res.arg}`,
+                isAborted: err.name === 'AbortError',
+              })
+            })
+        }
+
+        return (
+          <div>
+            <button onClick={handleClick(false)}>
+              Fetch User successfully
+            </button>
+            <button onClick={handleClick(true)}>Fetch User and abort</button>
+            <div>{successMsg}</div>
+            <div>{errMsg}</div>
+            <div>{isAborted ? 'Request was aborted' : ''}</div>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      expect(screen.queryByText(/An error has occurred/i)).toBeNull()
+      expect(screen.queryByText(/Successfully fetched user/i)).toBeNull()
+      expect(screen.queryByText('Request was aborted')).toBeNull()
+
+      fireEvent.click(
+        screen.getByRole('button', { name: 'Fetch User and abort' }),
+      )
+      await screen.findByText('An error has occurred fetching userId: 1')
+      expect(screen.queryByText(/Successfully fetched user/i)).toBeNull()
+      screen.getByText('Request was aborted')
+
+      await user.click(
+        screen.getByRole('button', { name: 'Fetch User successfully' }),
+      )
+
+      await screen.findByText('Successfully fetched user Timmy')
+      expect(screen.queryByText(/An error has occurred/i)).toBeNull()
+      expect(screen.queryByText('Request was aborted')).toBeNull()
+    })
+
+    // Based on issue #5079, which I couldn't reproduce but we might as well capture
+    test('useLazyQuery calling abort() multiple times does not throw an error', async () => {
+      const user = userEvent.setup()
+
+      // Create a fresh API instance with fetchBaseQuery and timeout, matching the user's example
+      const timeoutApi = createApi({
+        baseQuery: fetchBaseQuery({
+          baseUrl: 'https://example.com',
+          timeout: 5000,
+        }),
+        endpoints: (builder) => ({
+          getData: builder.query<string, void>({
+            query: () => ({ url: '/data/' }),
+          }),
+        }),
+      })
+
+      const timeoutStoreRef = setupApiStore(timeoutApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      // Set up a mock handler for the endpoint
+      server.use(
+        http.get('https://example.com/data/', async () => {
+          await delay(100)
+          return HttpResponse.json('test data')
+        }),
+      )
+
+      function Component() {
+        const [trigger] = timeoutApi.endpoints.getData.useLazyQuery()
+        const abortRef = useRef<(() => void) | undefined>(undefined)
+        const [errorMsg, setErrorMsg] = useState('')
+
+        const handleChange = () => {
+          // Abort any previous request
+          abortRef.current?.()
+
+          // Trigger new request
+          const result = trigger()
+
+          // Store abort function for next call
+          abortRef.current = () => {
+            try {
+              result.abort()
+            } catch (err: any) {
+              setErrorMsg(err.message)
+            }
+          }
+        }
+
+        return (
+          <div>
+            <input data-testid="input" onChange={handleChange} />
+            <div data-testid="error">{errorMsg}</div>
+          </div>
+        )
+      }
+
+      render(<Component />, { wrapper: timeoutStoreRef.wrapper })
+
+      const input = screen.getByTestId('input')
+
+      // Trigger multiple rapid changes that will call abort() multiple times
+      await user.type(input, 'abc')
+
+      // Wait a bit to ensure any errors would have been caught
+      await waitMs(200)
+
+      // Should not have any error messages
+      expect(screen.getByTestId('error').textContent).toBe('')
+    })
+
+    test('unwrapping the useLazyQuery trigger result does not throw on ConditionError and instead returns the aggregate error', async () => {
+      function User() {
+        const [getUser, { data, error }] =
+          api.endpoints.getUserAndForceError.useLazyQuery()
+
+        const [unwrappedError, setUnwrappedError] = useState<any>()
+
+        const handleClick = async () => {
+          const res = getUser(1)
+
+          try {
+            await res.unwrap()
+          } catch (error) {
+            setUnwrappedError(error)
+          }
+        }
+
+        return (
+          <div>
+            <button onClick={handleClick}>Fetch User</button>
+            <div data-testid="result">{JSON.stringify(data)}</div>
+            <div data-testid="error">{JSON.stringify(error)}</div>
+            <div data-testid="unwrappedError">
+              {JSON.stringify(unwrappedError)}
+            </div>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      const fetchButton = screen.getByRole('button', { name: 'Fetch User' })
+      fireEvent.click(fetchButton)
+      fireEvent.click(fetchButton) // This technically dispatches a ConditionError, but we don't want to see that here. We want the real error to resolve.
+
+      await waitFor(() => {
+        const errorResult = screen.getByTestId('error')?.textContent
+        const unwrappedErrorResult =
+          screen.getByTestId('unwrappedError')?.textContent
+
+        if (errorResult && unwrappedErrorResult) {
+          expect(JSON.parse(errorResult)).toMatchObject({
+            status: 500,
+            data: null,
+          })
+          expect(JSON.parse(unwrappedErrorResult)).toMatchObject(
+            JSON.parse(errorResult),
+          )
+        }
+      })
+
+      expect(screen.getByTestId('result').textContent).toBe('')
+    })
+
+    test('useLazyQuery does not throw on ConditionError and instead returns the aggregate result', async () => {
+      function User() {
+        const [getUser, { data, error }] = api.endpoints.getUser.useLazyQuery()
+
+        const [unwrappedResult, setUnwrappedResult] = useState<
+          undefined | { name: string }
+        >()
+
+        const handleClick = async () => {
+          const res = getUser(1)
+
+          const result = await res.unwrap()
+          setUnwrappedResult(result)
+        }
+
+        return (
+          <div>
+            <button onClick={handleClick}>Fetch User</button>
+            <div data-testid="result">{JSON.stringify(data)}</div>
+            <div data-testid="error">{JSON.stringify(error)}</div>
+            <div data-testid="unwrappedResult">
+              {JSON.stringify(unwrappedResult)}
+            </div>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      const fetchButton = screen.getByRole('button', { name: 'Fetch User' })
+      fireEvent.click(fetchButton)
+      fireEvent.click(fetchButton) // This technically dispatches a ConditionError, but we don't want to see that here. We want the real result to resolve and ignore the error.
+
+      await waitFor(() => {
+        const dataResult = screen.getByTestId('error')?.textContent
+        const unwrappedDataResult =
+          screen.getByTestId('unwrappedResult')?.textContent
+
+        if (dataResult && unwrappedDataResult) {
+          expect(JSON.parse(dataResult)).toMatchObject({
+            name: 'Timmy',
+          })
+          expect(JSON.parse(unwrappedDataResult)).toMatchObject(
+            JSON.parse(dataResult),
+          )
+        }
+      })
+
+      expect(screen.getByTestId('error').textContent).toBe('')
+    })
+
+    test('useLazyQuery trigger promise returns the correctly updated data', async () => {
+      const user = userEvent.setup()
+
+      const LazyUnwrapUseEffect = () => {
+        const [triggerGetIncrementedAmount, { isFetching, isSuccess, data }] =
+          api.endpoints.getIncrementedAmount.useLazyQuery()
+
+        type AmountData = { amount: number } | undefined
+
+        const [triggerUpdate] = api.endpoints.triggerUpdatedAmount.useMutation()
+
+        const [dataFromQuery, setDataFromQuery] =
+          useState<AmountData>(undefined)
+        const [dataFromTrigger, setDataFromTrigger] =
+          useState<AmountData>(undefined)
+
+        const handleLoad = async () => {
+          try {
+            const res = await triggerGetIncrementedAmount().unwrap()
+
+            setDataFromTrigger(res) // adding client side state here will cause stale data
+          } catch (error) {
+            console.error('Error handling increment trigger', error)
+          }
+        }
+
+        const handleMutate = async () => {
+          try {
+            await triggerUpdate()
+            // Force the lazy trigger to refetch
+            await handleLoad()
+          } catch (error) {
+            console.error('Error handling mutate trigger', error)
+          }
+        }
+
+        useEffect(() => {
+          // Intentionally copy to local state for comparison purposes
+          setDataFromQuery(data)
+        }, [data])
+
+        let content: React.ReactNode | null = null
+
+        if (isFetching) {
+          content = <div className="loading">Loading</div>
+        } else if (isSuccess) {
+          content = (
+            <div className="wrapper">
+              <div>
+                useEffect data: {dataFromQuery?.amount ?? 'No query amount'}
+              </div>
+              <div>
+                Unwrap data: {dataFromTrigger?.amount ?? 'No trigger amount'}
+              </div>
+            </div>
+          )
+        }
+
+        return (
+          <div className="outer">
+            <button onClick={() => handleLoad()}>Load Data</button>
+            <button onClick={() => handleMutate()}>Update Data</button>
+            {content}
+          </div>
+        )
+      }
+
+      render(<LazyUnwrapUseEffect />, { wrapper: storeRef.wrapper })
+
+      // Kick off the initial fetch via lazy query trigger
+      await user.click(screen.getByText('Load Data'))
+
+      // We get back initial data, which should get copied into local state,
+      // and also should come back as valid via the lazy trigger promise
+      await waitFor(() => {
+        expect(screen.getByText('useEffect data: 1')).toBeTruthy()
+        expect(screen.getByText('Unwrap data: 1')).toBeTruthy()
+      })
+
+      // If we mutate and then re-run the lazy trigger afterwards...
+      await user.click(screen.getByText('Update Data'))
+
+      // We should see both sets of data agree (ie, the lazy trigger promise
+      // should not return stale data or be out of sync with the hook).
+      // Prior to PR #4651, this would fail because the trigger never updated properly.
+      await waitFor(() => {
+        expect(screen.getByText('useEffect data: 2')).toBeTruthy()
+        expect(screen.getByText('Unwrap data: 2')).toBeTruthy()
+      })
+    })
+
+    test('`reset` sets state back to original state', async () => {
+      const user = userEvent.setup()
+
+      function User() {
+        const [getUser, { isSuccess, isUninitialized, reset }, _lastInfo] =
+          api.endpoints.getUser.useLazyQuery()
+
+        const handleFetchClick = async () => {
+          await getUser(1).unwrap()
+        }
+
+        return (
+          <div>
+            <span>
+              {isUninitialized
+                ? 'isUninitialized'
+                : isSuccess
+                  ? 'isSuccess'
+                  : 'other'}
+            </span>
+            <button onClick={handleFetchClick}>Fetch User</button>
+            <button onClick={reset}>Reset</button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      await screen.findByText(/isUninitialized/i)
+      expect(countObjectKeys(storeRef.store.getState().api.queries)).toBe(0)
+
+      await user.click(screen.getByRole('button', { name: 'Fetch User' }))
+
+      await screen.findByText(/isSuccess/i)
+      expect(countObjectKeys(storeRef.store.getState().api.queries)).toBe(1)
+
+      await user.click(
+        screen.getByRole('button', {
+          name: 'Reset',
+        }),
+      )
+
+      await screen.findByText(/isUninitialized/i)
+      expect(countObjectKeys(storeRef.store.getState().api.queries)).toBe(0)
+    })
+  })
+
+  describe('useInfiniteQuery', () => {
+    type Pokemon = {
+      id: string
+      name: string
+    }
+
+    const pokemonApi = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+      endpoints: (builder) => ({
+        getInfinitePokemon: builder.infiniteQuery<Pokemon, string, number>({
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+            getPreviousPageParam: (
+              firstPage,
+              allPages,
+              firstPageParam,
+              allPageParams,
+            ) => {
+              return firstPageParam > 0 ? firstPageParam - 1 : undefined
+            },
+          },
+          query({ pageParam }) {
+            return `https://example.com/listItems?page=${pageParam}`
+          },
+        }),
+      }),
+    })
+
+    const pokemonApiWithRefetch = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+      endpoints: (builder) => ({
+        getInfinitePokemon: builder.infiniteQuery<Pokemon, string, number>({
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+            getPreviousPageParam: (
+              firstPage,
+              allPages,
+              firstPageParam,
+              allPageParams,
+            ) => {
+              return firstPageParam > 0 ? firstPageParam - 1 : undefined
+            },
+          },
+          query({ pageParam }) {
+            return `https://example.com/listItems?page=${pageParam}`
+          },
+        }),
+      }),
+      refetchOnMountOrArgChange: true,
+    })
+
+    function PokemonList({
+      api,
+      arg = 'fire',
+      initialPageParam = 0,
+    }: {
+      api: typeof pokemonApi
+      arg?: string
+      initialPageParam?: number
+    }) {
+      const {
+        data,
+        isFetching,
+        isUninitialized,
+        fetchNextPage,
+        fetchPreviousPage,
+        refetch,
+      } = api.useGetInfinitePokemonInfiniteQuery(arg, {
+        initialPageParam,
+      })
+
+      const handlePreviousPage = async () => {
+        const res = await fetchPreviousPage()
+      }
+
+      const handleNextPage = async () => {
+        const res = await fetchNextPage()
+      }
+
+      const handleRefetch = async () => {
+        const res = await refetch()
+      }
+
+      return (
+        <div>
+          <div data-testid="isUninitialized">{String(isUninitialized)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div>Type: {arg}</div>
+          <div data-testid="data">
+            {data?.pages.map((page, i: number | null | undefined) => (
+              <div key={i}>{page.name}</div>
+            ))}
+          </div>
+          <button data-testid="prevPage" onClick={() => handlePreviousPage()}>
+            previousPage
+          </button>
+          <button data-testid="nextPage" onClick={() => handleNextPage()}>
+            nextPage
+          </button>
+          <button data-testid="refetch" onClick={() => handleRefetch()}>
+            refetch
+          </button>
+        </div>
+      )
+    }
+
+    beforeEach(() => {
+      server.use(
+        http.get('https://example.com/listItems', ({ request }) => {
+          const url = new URL(request.url)
+          const pageString = url.searchParams.get('page')
+          const pageNum = parseInt(pageString || '0')
+
+          const results: Pokemon = {
+            id: `${pageNum}`,
+            name: `Pokemon ${pageNum}`,
+          }
+
+          return HttpResponse.json(results)
+        }),
+      )
+    })
+
+    test.each([
+      ['no refetch', pokemonApi],
+      ['with refetch', pokemonApiWithRefetch],
+    ])(`useInfiniteQuery %s`, async (_, pokemonApi) => {
+      const storeRef = setupApiStore(pokemonApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const { takeRender, render, getCurrentRender } = createRenderStream({
+        snapshotDOM: true,
+      })
+
+      const checkNumQueries = (count: number) => {
+        const cacheEntries = Object.keys(storeRef.store.getState().api.queries)
+        const queries = cacheEntries.length
+
+        expect(queries).toBe(count)
+      }
+
+      const checkEntryFlags = (
+        arg: string,
+        expectedFlags: Partial<InfiniteQueryResultFlags>,
+      ) => {
+        const selector = pokemonApi.endpoints.getInfinitePokemon.select(arg)
+        const entry = selector(storeRef.store.getState())
+
+        const actualFlags: InfiniteQueryResultFlags = {
+          hasNextPage: false,
+          hasPreviousPage: false,
+          isFetchingNextPage: false,
+          isFetchingPreviousPage: false,
+          isFetchNextPageError: false,
+          isFetchPreviousPageError: false,
+          ...expectedFlags,
+        }
+
+        expect(entry).toMatchObject(actualFlags)
+      }
+
+      const checkPageRows = (
+        withinDOM: () => SyncScreen,
+        type: string,
+        ids: number[],
+      ) => {
+        expect(withinDOM().getByText(`Type: ${type}`)).toBeTruthy()
+        for (const id of ids) {
+          expect(withinDOM().getByText(`Pokemon ${id}`)).toBeTruthy()
+        }
+      }
+
+      async function waitForFetch(handleExtraMiddleRender = false) {
+        {
+          const { withinDOM } = await takeRender()
+          expect(withinDOM().getByTestId('isFetching').textContent).toBe('true')
+        }
+
+        // We seem to do an extra render when fetching an uninitialized entry
+        if (handleExtraMiddleRender) {
+          {
+            const { withinDOM } = await takeRender()
+            expect(withinDOM().getByTestId('isFetching').textContent).toBe(
+              'true',
+            )
+          }
+        }
+
+        {
+          // Second fetch complete
+          const { withinDOM } = await takeRender()
+          expect(withinDOM().getByTestId('isFetching').textContent).toBe(
+            'false',
+          )
+        }
+      }
+
+      const utils = render(<PokemonList api={pokemonApi} />, {
+        wrapper: storeRef.wrapper,
+      })
+      checkNumQueries(1)
+      checkEntryFlags('fire', {})
+      await waitForFetch(true)
+      checkNumQueries(1)
+      checkPageRows(getCurrentRender().withinDOM, 'fire', [0])
+      checkEntryFlags('fire', {
+        hasNextPage: true,
+      })
+
+      fireEvent.click(screen.getByTestId('nextPage'), {})
+      checkEntryFlags('fire', {
+        hasNextPage: true,
+        isFetchingNextPage: true,
+      })
+      await waitForFetch()
+      checkPageRows(getCurrentRender().withinDOM, 'fire', [0, 1])
+      checkEntryFlags('fire', {
+        hasNextPage: true,
+      })
+
+      fireEvent.click(screen.getByTestId('nextPage'))
+      await waitForFetch()
+      checkPageRows(getCurrentRender().withinDOM, 'fire', [0, 1, 2])
+
+      utils.rerender(
+        <PokemonList api={pokemonApi} arg="water" initialPageParam={3} />,
+      )
+      checkEntryFlags('water', {})
+      await waitForFetch(true)
+      checkNumQueries(2)
+      checkPageRows(getCurrentRender().withinDOM, 'water', [3])
+      checkEntryFlags('water', {
+        hasNextPage: true,
+        hasPreviousPage: true,
+      })
+
+      fireEvent.click(screen.getByTestId('nextPage'))
+      checkEntryFlags('water', {
+        hasNextPage: true,
+        hasPreviousPage: true,
+        isFetchingNextPage: true,
+      })
+      await waitForFetch()
+      checkPageRows(getCurrentRender().withinDOM, 'water', [3, 4])
+      checkEntryFlags('water', {
+        hasNextPage: true,
+        hasPreviousPage: true,
+      })
+
+      fireEvent.click(screen.getByTestId('prevPage'))
+      checkEntryFlags('water', {
+        hasNextPage: true,
+        hasPreviousPage: true,
+        isFetchingPreviousPage: true,
+      })
+      await waitForFetch()
+      checkPageRows(getCurrentRender().withinDOM, 'water', [2, 3, 4])
+      checkEntryFlags('water', {
+        hasNextPage: true,
+        hasPreviousPage: true,
+      })
+
+      fireEvent.click(screen.getByTestId('refetch'))
+      checkEntryFlags('water', {
+        hasNextPage: true,
+        hasPreviousPage: true,
+      })
+      await waitForFetch()
+      checkPageRows(getCurrentRender().withinDOM, 'water', [2, 3, 4])
+      checkEntryFlags('water', {
+        hasNextPage: true,
+        hasPreviousPage: true,
+      })
+    })
+
+    test('Object page params does not keep forcing refetching', async () => {
+      type Project = {
+        id: number
+        createdAt: string
+      }
+
+      type ProjectsResponse = {
+        projects: Project[]
+        numFound: number
+        serverTime: string
+      }
+
+      interface ProjectsInitialPageParam {
+        offset: number
+        limit: number
+      }
+
+      const apiWithInfiniteScroll = createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/' }),
+        endpoints: (builder) => ({
+          projectsLimitOffset: builder.infiniteQuery<
+            ProjectsResponse,
+            void,
+            ProjectsInitialPageParam
+          >({
+            infiniteQueryOptions: {
+              initialPageParam: {
+                offset: 0,
+                limit: 20,
+              },
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => {
+                const nextOffset = lastPageParam.offset + lastPageParam.limit
+                const remainingItems = lastPage?.numFound - nextOffset
+
+                if (remainingItems <= 0) {
+                  return undefined
+                }
+
+                return {
+                  ...lastPageParam,
+                  offset: nextOffset,
+                }
+              },
+              getPreviousPageParam: (
+                firstPage,
+                allPages,
+                firstPageParam,
+                allPageParams,
+              ) => {
+                const prevOffset = firstPageParam.offset - firstPageParam.limit
+                if (prevOffset < 0) return undefined
+
+                return {
+                  ...firstPageParam,
+                  offset: firstPageParam.offset - firstPageParam.limit,
+                }
+              },
+            },
+            query: ({ pageParam }) => {
+              const { offset, limit } = pageParam
+              return {
+                url: `https://example.com/api/projectsLimitOffset?offset=${offset}&limit=${limit}`,
+                method: 'GET',
+              }
+            },
+          }),
+        }),
+      })
+
+      const projects = Array.from({ length: 50 }, (_, i) => {
+        return {
+          id: i,
+          createdAt: Date.now() + i * 1000,
+        }
+      })
+
+      let numRequests = 0
+
+      server.use(
+        http.get(
+          'https://example.com/api/projectsLimitOffset',
+          async ({ request }) => {
+            const url = new URL(request.url)
+            const limit = parseInt(url.searchParams.get('limit') ?? '5', 10)
+            let offset = parseInt(url.searchParams.get('offset') ?? '0', 10)
+
+            numRequests++
+
+            if (isNaN(offset) || offset < 0) {
+              offset = 0
+            }
+            if (isNaN(limit) || limit <= 0) {
+              return HttpResponse.json(
+                {
+                  message:
+                    "Invalid 'limit' parameter. It must be a positive integer.",
+                } as any,
+                { status: 400 },
+              )
+            }
+
+            const result = projects.slice(offset, offset + limit)
+
+            await delay(10)
+            return HttpResponse.json({
+              projects: result,
+              serverTime: Date.now(),
+              numFound: projects.length,
+            })
+          },
+        ),
+      )
+
+      function LimitOffsetExample() {
+        const {
+          data,
+          hasPreviousPage,
+          hasNextPage,
+          error,
+          isFetching,
+          isLoading,
+          isError,
+          fetchNextPage,
+          fetchPreviousPage,
+          isFetchingNextPage,
+          isFetchingPreviousPage,
+          status,
+        } = apiWithInfiniteScroll.useProjectsLimitOffsetInfiniteQuery(
+          undefined,
+          {
+            initialPageParam: {
+              offset: 10,
+              limit: 10,
+            },
+          },
+        )
+
+        const [counter, setCounter] = useState(0)
+
+        const combinedData = useMemo(() => {
+          return data?.pages?.map((item) => item?.projects)?.flat()
+        }, [data])
+
+        return (
+          <div>
+            <h2>Limit and Offset Infinite Scroll</h2>
+            <button onClick={() => setCounter((c) => c + 1)}>Increment</button>
+            <div>Counter: {counter}</div>
+            {isLoading ? (
+              <p>Loading...</p>
+            ) : isError ? (
+              <span>Error: {error.message}</span>
+            ) : null}
+
+            <>
+              <div>
+                <button
+                  onClick={() => fetchPreviousPage()}
+                  disabled={!hasPreviousPage || isFetchingPreviousPage}
+                >
+                  {isFetchingPreviousPage
+                    ? 'Loading more...'
+                    : hasPreviousPage
+                      ? 'Load Older'
+                      : 'Nothing more to load'}
+                </button>
+              </div>
+              <div data-testid="projects">
+                {combinedData?.map((project, index, arr) => {
+                  return (
+                    <div key={project.id}>
+                      <div data-testid="project">
+                        <div>{`Project ${project.id} (created at: ${project.createdAt})`}</div>
+                      </div>
+                    </div>
+                  )
+                })}
+              </div>
+              <div>
+                <button
+                  onClick={() => fetchNextPage()}
+                  disabled={!hasNextPage || isFetchingNextPage}
+                >
+                  {isFetchingNextPage
+                    ? 'Loading more...'
+                    : hasNextPage
+                      ? 'Load Newer'
+                      : 'Nothing more to load'}
+                </button>
+              </div>
+              <div>
+                {isFetching && !isFetchingPreviousPage && !isFetchingNextPage
+                  ? 'Background Updating...'
+                  : null}
+              </div>
+            </>
+          </div>
+        )
+      }
+
+      const storeRef = setupApiStore(
+        apiWithInfiniteScroll,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      const { takeRender, render, totalRenderCount } = createRenderStream({
+        snapshotDOM: true,
+      })
+
+      render(<LimitOffsetExample />, {
+        wrapper: storeRef.wrapper,
+      })
+
+      {
+        const { withinDOM } = await takeRender()
+        withinDOM().getByText('Counter: 0')
+        withinDOM().getByText('Loading...')
+      }
+
+      {
+        const { withinDOM } = await takeRender()
+        withinDOM().getByText('Counter: 0')
+        withinDOM().getByText('Loading...')
+      }
+
+      {
+        const { withinDOM } = await takeRender()
+        withinDOM().getByText('Counter: 0')
+
+        expect(withinDOM().getAllByTestId('project').length).toBe(10)
+        expect(withinDOM().queryByTestId('Loading...')).toBeNull()
+      }
+
+      expect(totalRenderCount()).toBe(3)
+      expect(numRequests).toBe(1)
+    })
+
+    test.each([
+      ['skip token', true],
+      ['skip option', false],
+    ])(
+      'useInfiniteQuery hook does not fetch when skipped via %s',
+      async (_, useSkipToken) => {
+        function Pokemon() {
+          const [value, setValue] = useState(0)
+
+          const shouldFetch = value > 0
+
+          const arg = shouldFetch || !useSkipToken ? 'fire' : skipToken
+          const skip = useSkipToken ? undefined : shouldFetch ? undefined : true
+
+          const { isFetching } = pokemonApi.useGetInfinitePokemonInfiniteQuery(
+            arg,
+            {
+              skip,
+            },
+          )
+          getRenderCount = useRenderCounter()
+
+          return (
+            <div>
+              <div data-testid="isFetching">{String(isFetching)}</div>
+              <button onClick={() => setValue((val) => val + 1)}>
+                Increment value
+              </button>
+            </div>
+          )
+        }
+
+        render(<Pokemon />, { wrapper: storeRef.wrapper })
+        expect(getRenderCount()).toBe(1)
+
+        await waitFor(() =>
+          expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+        )
+        fireEvent.click(screen.getByText('Increment value'))
+        await waitFor(() =>
+          expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+        )
+        expect(getRenderCount()).toBe(2)
+      },
+    )
+
+    test('useInfiniteQuery hook option refetchCachedPages: false only refetches first page', async () => {
+      const storeRef = setupApiStore(pokemonApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      function PokemonList() {
+        const { data, fetchNextPage, refetch } =
+          pokemonApi.useGetInfinitePokemonInfiniteQuery('fire', {
+            refetchCachedPages: false,
+          })
+
+        return (
+          <div>
+            <div data-testid="data">
+              {data?.pages.map((page, i) => (
+                <div key={i} data-testid={`page-${i}`}>
+                  {page.name}
+                </div>
+              ))}
+            </div>
+            <button data-testid="nextPage" onClick={() => fetchNextPage()}>
+              Next Page
+            </button>
+            <button data-testid="refetch" onClick={() => refetch()}>
+              Refetch
+            </button>
+          </div>
+        )
+      }
+
+      render(<PokemonList />, { wrapper: storeRef.wrapper })
+
+      // Wait for initial page to load
+      await waitFor(() => {
+        expect(screen.getByTestId('page-0').textContent).toBe('Pokemon 0')
+      })
+
+      // Fetch second page
+      fireEvent.click(screen.getByTestId('nextPage'))
+      await waitFor(() => {
+        expect(screen.getByTestId('page-1').textContent).toBe('Pokemon 1')
+      })
+
+      // Fetch third page
+      fireEvent.click(screen.getByTestId('nextPage'))
+      await waitFor(() => {
+        expect(screen.getByTestId('page-2').textContent).toBe('Pokemon 2')
+      })
+
+      // Now we have 3 pages. Refetch with refetchCachedPages: false should only refetch page 0
+      fireEvent.click(screen.getByTestId('refetch'))
+
+      await waitFor(
+        () => {
+          // Should only have 1 page
+          expect(screen.queryByTestId('page-0')).toBeTruthy()
+          expect(screen.queryByTestId('page-1')).toBeNull()
+          expect(screen.queryByTestId('page-2')).toBeNull()
+        },
+        { timeout: 1000 },
+      )
+
+      // Verify we only have 1 page (not refetched all)
+      const pages = screen.getAllByTestId(/^page-/)
+      expect(pages).toHaveLength(1)
+    })
+
+    test('useInfiniteQuery refetch() method option refetchCachedPages: false only refetches first page', async () => {
+      const storeRef = setupApiStore(pokemonApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      function PokemonList() {
+        const { data, fetchNextPage, refetch } =
+          pokemonApi.useGetInfinitePokemonInfiniteQuery('fire')
+
+        return (
+          <div>
+            <div data-testid="data">
+              {data?.pages.map((page, i) => (
+                <div key={i} data-testid={`page-${i}`}>
+                  {page.name}
+                </div>
+              ))}
+            </div>
+            <button data-testid="nextPage" onClick={() => fetchNextPage()}>
+              Next Page
+            </button>
+            <button
+              data-testid="refetch"
+              onClick={() => refetch({ refetchCachedPages: false })}
+            >
+              Refetch
+            </button>
+          </div>
+        )
+      }
+
+      render(<PokemonList />, { wrapper: storeRef.wrapper })
+
+      // Wait for initial page to load
+      await waitFor(() => {
+        expect(screen.getByTestId('page-0').textContent).toBe('Pokemon 0')
+      })
+
+      // Fetch second page
+      fireEvent.click(screen.getByTestId('nextPage'))
+      await waitFor(() => {
+        expect(screen.getByTestId('page-1').textContent).toBe('Pokemon 1')
+      })
+
+      // Fetch third page
+      fireEvent.click(screen.getByTestId('nextPage'))
+      await waitFor(() => {
+        expect(screen.getByTestId('page-2').textContent).toBe('Pokemon 2')
+      })
+
+      // Now we have 3 pages. Refetch with refetchCachedPages: false should only refetch page 0
+      fireEvent.click(screen.getByTestId('refetch'))
+
+      await waitFor(() => {
+        // Should only have 1 page
+        expect(screen.queryByTestId('page-0')).toBeTruthy()
+        expect(screen.queryByTestId('page-1')).toBeNull()
+        expect(screen.queryByTestId('page-2')).toBeNull()
+      })
+
+      // Verify we only have 1 page (not refetched all)
+      const pages = screen.getAllByTestId(/^page-/)
+      expect(pages).toHaveLength(1)
+    })
+  })
+
+  describe('useMutation', () => {
+    test('useMutation hook sets and unsets the isLoading flag when running', async () => {
+      function User() {
+        const [updateUser, { isLoading }] =
+          api.endpoints.updateUser.useMutation()
+
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <button onClick={() => updateUser({ name: 'Banana' })}>
+              Update User
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+      fireEvent.click(screen.getByText('Update User'))
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+    })
+
+    test('useMutation hook sets data to the resolved response on success', async () => {
+      const result = { name: 'Banana' }
+
+      function User() {
+        const [updateUser, { data }] = api.endpoints.updateUser.useMutation()
+
+        return (
+          <div>
+            <div data-testid="result">{JSON.stringify(data)}</div>
+            <button onClick={() => updateUser({ name: 'Banana' })}>
+              Update User
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      fireEvent.click(screen.getByText('Update User'))
+      await waitFor(() =>
+        expect(screen.getByTestId('result').textContent).toBe(
+          JSON.stringify(result),
+        ),
+      )
+    })
+
+    test('useMutation hook callback returns various properties to handle the result', async () => {
+      const user = userEvent.setup()
+
+      function User() {
+        const [updateUser] = api.endpoints.updateUser.useMutation()
+        const [successMsg, setSuccessMsg] = useState('')
+        const [errMsg, setErrMsg] = useState('')
+        const [isAborted, setIsAborted] = useState(false)
+
+        const handleClick = async () => {
+          const res = updateUser({ name: 'Banana' })
+
+          // abort the mutation immediately to force an error
+          res.abort()
+          res
+            .unwrap()
+            .then((result) => {
+              setSuccessMsg(`Successfully updated user ${result.name}`)
+            })
+            .catch((err) => {
+              setErrMsg(
+                `An error has occurred updating user ${res.arg.originalArgs.name}`,
+              )
+              if (err.name === 'AbortError') {
+                setIsAborted(true)
+              }
+            })
+        }
+
+        return (
+          <div>
+            <button onClick={handleClick}>Update User and abort</button>
+            <div>{successMsg}</div>
+            <div>{errMsg}</div>
+            <div>{isAborted ? 'Request was aborted' : ''}</div>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      expect(screen.queryByText(/An error has occurred/i)).toBeNull()
+      expect(screen.queryByText(/Successfully updated user/i)).toBeNull()
+      expect(screen.queryByText('Request was aborted')).toBeNull()
+
+      await user.click(
+        screen.getByRole('button', { name: 'Update User and abort' }),
+      )
+      await screen.findByText('An error has occurred updating user Banana')
+      expect(screen.queryByText(/Successfully updated user/i)).toBeNull()
+      screen.getByText('Request was aborted')
+    })
+
+    test('useMutation return value contains originalArgs', async () => {
+      const { result } = renderHook(
+        () => api.endpoints.updateUser.useMutation(),
+        {
+          wrapper: storeRef.wrapper,
+        },
+      )
+      const arg = { name: 'Foo' }
+
+      const firstRenderResult = result.current
+      expect(firstRenderResult[1].originalArgs).toBe(undefined)
+      await act(async () => {
+        await firstRenderResult[0](arg)
+      })
+      const secondRenderResult = result.current
+      expect(firstRenderResult[1].originalArgs).toBe(undefined)
+      expect(secondRenderResult[1].originalArgs).toBe(arg)
+    })
+
+    test('`reset` sets state back to original state', async () => {
+      const user = userEvent.setup()
+
+      function User() {
+        const [updateUser, result] = api.endpoints.updateUser.useMutation()
+        return (
+          <>
+            <span>
+              {result.isUninitialized
+                ? 'isUninitialized'
+                : result.isSuccess
+                  ? 'isSuccess'
+                  : 'other'}
+            </span>
+            <span>{result.originalArgs?.name}</span>
+            <button onClick={() => updateUser({ name: 'Yay' })}>trigger</button>
+            <button onClick={result.reset}>reset</button>
+          </>
+        )
+      }
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      await screen.findByText(/isUninitialized/i)
+      expect(screen.queryByText('Yay')).toBeNull()
+      expect(countObjectKeys(storeRef.store.getState().api.mutations)).toBe(0)
+
+      await user.click(screen.getByRole('button', { name: 'trigger' }))
+
+      await screen.findByText(/isSuccess/i)
+      expect(screen.queryByText('Yay')).not.toBeNull()
+      expect(countObjectKeys(storeRef.store.getState().api.mutations)).toBe(1)
+
+      await user.click(screen.getByRole('button', { name: 'reset' }))
+
+      await screen.findByText(/isUninitialized/i)
+      expect(screen.queryByText('Yay')).toBeNull()
+      expect(countObjectKeys(storeRef.store.getState().api.mutations)).toBe(0)
+    })
+  })
+
+  describe('usePrefetch', () => {
+    test('usePrefetch respects force arg', async () => {
+      const user = userEvent.setup()
+
+      const { usePrefetch } = api
+      const USER_ID = 4
+      function User() {
+        const { isFetching } = api.endpoints.getUser.useQuery(USER_ID)
+        const prefetchUser = usePrefetch('getUser', { force: true })
+
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button
+              onMouseEnter={() => prefetchUser(USER_ID, { force: true })}
+              data-testid="highPriority"
+            >
+              High priority action intent
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      // Resolve initial query
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      await user.hover(screen.getByTestId('highPriority'))
+
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
+      ).toEqual({
+        data: { name: 'Timmy' },
+        endpointName: 'getUser',
+        error: undefined,
+        fulfilledTimeStamp: expect.any(Number),
+        isError: false,
+        isLoading: true,
+        isSuccess: false,
+        isUninitialized: false,
+        originalArgs: USER_ID,
+        requestId: expect.any(String),
+        startedTimeStamp: expect.any(Number),
+        status: QueryStatus.pending,
+      })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
+      ).toEqual({
+        data: { name: 'Timmy' },
+        endpointName: 'getUser',
+        fulfilledTimeStamp: expect.any(Number),
+        isError: false,
+        isLoading: false,
+        isSuccess: true,
+        isUninitialized: false,
+        originalArgs: USER_ID,
+        requestId: expect.any(String),
+        startedTimeStamp: expect.any(Number),
+        status: QueryStatus.fulfilled,
+      })
+    })
+
+    test('usePrefetch does not make an additional request if already in the cache and force=false', async () => {
+      const user = userEvent.setup()
+
+      const { usePrefetch } = api
+      const USER_ID = 2
+
+      function User() {
+        // Load the initial query
+        const { isFetching } = api.endpoints.getUser.useQuery(USER_ID)
+        const prefetchUser = usePrefetch('getUser', { force: false })
+
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button
+              onMouseEnter={() => prefetchUser(USER_ID)}
+              data-testid="lowPriority"
+            >
+              Low priority user action intent
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      // Let the initial query resolve
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      // Try to prefetch what we just loaded
+      await user.hover(screen.getByTestId('lowPriority'))
+
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
+      ).toEqual({
+        data: { name: 'Timmy' },
+        endpointName: 'getUser',
+        fulfilledTimeStamp: expect.any(Number),
+        isError: false,
+        isLoading: false,
+        isSuccess: true,
+        isUninitialized: false,
+        originalArgs: USER_ID,
+        requestId: expect.any(String),
+        startedTimeStamp: expect.any(Number),
+        status: QueryStatus.fulfilled,
+      })
+
+      await waitMs()
+
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
+      ).toEqual({
+        data: { name: 'Timmy' },
+        endpointName: 'getUser',
+        fulfilledTimeStamp: expect.any(Number),
+        isError: false,
+        isLoading: false,
+        isSuccess: true,
+        isUninitialized: false,
+        originalArgs: USER_ID,
+        requestId: expect.any(String),
+        startedTimeStamp: expect.any(Number),
+        status: QueryStatus.fulfilled,
+      })
+    })
+
+    test('usePrefetch respects ifOlderThan when it evaluates to true', async () => {
+      const user = userEvent.setup()
+
+      const { usePrefetch } = api
+      const USER_ID = 47
+
+      function User() {
+        // Load the initial query
+        const { isFetching } = api.endpoints.getUser.useQuery(USER_ID)
+        const prefetchUser = usePrefetch('getUser', { ifOlderThan: 0.2 })
+
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button
+              onMouseEnter={() => prefetchUser(USER_ID)}
+              data-testid="lowPriority"
+            >
+              Low priority user action intent
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      // Wait 400ms, making it respect ifOlderThan
+      await waitMs(400)
+
+      // This should run the query being that we're past the threshold
+      await user.hover(screen.getByTestId('lowPriority'))
+
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
+      ).toEqual({
+        data: { name: 'Timmy' },
+        endpointName: 'getUser',
+        fulfilledTimeStamp: expect.any(Number),
+        isError: false,
+        isLoading: true,
+        isSuccess: false,
+        isUninitialized: false,
+        originalArgs: USER_ID,
+        requestId: expect.any(String),
+        startedTimeStamp: expect.any(Number),
+        status: QueryStatus.pending,
+      })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
+      ).toEqual({
+        data: { name: 'Timmy' },
+        endpointName: 'getUser',
+        fulfilledTimeStamp: expect.any(Number),
+        isError: false,
+        isLoading: false,
+        isSuccess: true,
+        isUninitialized: false,
+        originalArgs: USER_ID,
+        requestId: expect.any(String),
+        startedTimeStamp: expect.any(Number),
+        status: QueryStatus.fulfilled,
+      })
+    })
+
+    test('usePrefetch returns the last success result when ifOlderThan evaluates to false', async () => {
+      const user = userEvent.setup()
+
+      const { usePrefetch } = api
+      const USER_ID = 2
+
+      function User() {
+        // Load the initial query
+        const { isFetching } = api.endpoints.getUser.useQuery(USER_ID)
+        const prefetchUser = usePrefetch('getUser', { ifOlderThan: 10 })
+
+        return (
+          <div>
+            <div data-testid="isFetching">{String(isFetching)}</div>
+            <button
+              onMouseEnter={() => prefetchUser(USER_ID)}
+              data-testid="lowPriority"
+            >
+              Low priority user action intent
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      await waitFor(() =>
+        expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+      )
+      await waitMs()
+
+      // Get a snapshot of the last result
+      const latestQueryData = api.endpoints.getUser.select(USER_ID)(
+        storeRef.store.getState() as any,
+      )
+
+      await user.hover(screen.getByTestId('lowPriority'))
+
+      //  Serve up the result from the cache being that the condition wasn't met
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),
+      ).toEqual(latestQueryData)
+    })
+
+    test('usePrefetch executes a query even if conditions fail when the cache is empty', async () => {
+      const user = userEvent.setup()
+
+      const { usePrefetch } = api
+      const USER_ID = 2
+
+      function User() {
+        const prefetchUser = usePrefetch('getUser', { ifOlderThan: 10 })
+
+        return (
+          <div>
+            <button
+              onMouseEnter={() => prefetchUser(USER_ID)}
+              data-testid="lowPriority"
+            >
+              Low priority user action intent
+            </button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+
+      await user.hover(screen.getByTestId('lowPriority'))
+
+      expect(
+        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState()),
+      ).toEqual({
+        endpointName: 'getUser',
+        isError: false,
+        isLoading: true,
+        isSuccess: false,
+        isUninitialized: false,
+        originalArgs: USER_ID,
+        requestId: expect.any(String),
+        startedTimeStamp: expect.any(Number),
+        status: 'pending',
+      })
+    })
+
+    it('should create subscription when hook mounts after prefetch', async () => {
+      const api = createApi({
+        baseQuery: async () => ({ data: 'test data' }),
+        endpoints: (build) => ({
+          getTest: build.query<string, void>({
+            query: () => '',
+          }),
+        }),
+      })
+      const storeRef = setupApiStore(api, undefined, { withoutListeners: true })
+
+      // 1. Prefetch data (no subscription)
+      await storeRef.store.dispatch(api.util.prefetch('getTest', undefined))
+
+      // Verify data is cached
+      await waitFor(() => {
+        let state = storeRef.store.getState()
+        expect(state.api.queries['getTest(undefined)']?.data).toBe('test data')
+      })
+
+      // Verify no subscription exists
+      const subscriptions = storeRef.store.dispatch(
+        api.internalActions.internal_getRTKQSubscriptions(),
+      ) as any
+      expect(subscriptions.getSubscriptionCount('getTest(undefined)')).toBe(0)
+
+      // 2. Mount component with useQuery hook
+      function TestComponent() {
+        const result = api.endpoints.getTest.useQuery()
+        return <div>{result.data}</div>
+      }
+
+      const { unmount } = render(<TestComponent />, {
+        wrapper: storeRef.wrapper,
+      })
+
+      // Wait for hook to initialize
+      await waitFor(() => {
+        // EXPECTED: Subscription should be created
+        expect(subscriptions.getSubscriptionCount('getTest(undefined)')).toBe(1)
+      })
+
+      // 3. Verify data is still available
+      let state = storeRef.store.getState()
+      expect(state.api.queries['getTest(undefined)']?.data).toBe('test data')
+
+      // 4. Unmount and verify subscription is removed
+      unmount()
+
+      await waitFor(() => {
+        expect(subscriptions.getSubscriptionCount('getTest(undefined)')).toBe(0)
+      })
+    })
+  })
+
+  describe('useQuery and useMutation invalidation behavior', () => {
+    const api = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+      tagTypes: ['User'],
+      endpoints: (build) => ({
+        checkSession: build.query<any, void>({
+          query: () => '/me',
+          providesTags: ['User'],
+        }),
+        login: build.mutation<any, any>({
+          query: () => ({ url: '/login', method: 'POST' }),
+          invalidatesTags: ['User'],
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, { ...actionsReducer })
+    test('initially failed useQueries that provide an tag will refetch after a mutation invalidates it', async () => {
+      const checkSessionData = { name: 'matt' }
+      server.use(
+        http.get(
+          'https://example.com/me',
+          () => {
+            return HttpResponse.json(null, { status: 500 })
+          },
+          { once: true },
+        ),
+        http.get('https://example.com/me', () => {
+          return HttpResponse.json(checkSessionData)
+        }),
+        http.post('https://example.com/login', () => {
+          return HttpResponse.json(null, { status: 200 })
+        }),
+      )
+      let data, isLoading, isError
+      function User() {
+        ;({ data, isError, isLoading } = api.endpoints.checkSession.useQuery())
+        const [login, { isLoading: loginLoading }] =
+          api.endpoints.login.useMutation()
+
+        return (
+          <div>
+            <div data-testid="isLoading">{String(isLoading)}</div>
+            <div data-testid="isError">{String(isError)}</div>
+            <div data-testid="user">{JSON.stringify(data)}</div>
+            <div data-testid="loginLoading">{String(loginLoading)}</div>
+            <button onClick={() => login(null)}>Login</button>
+          </div>
+        )
+      }
+
+      render(<User />, { wrapper: storeRef.wrapper })
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('isError').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('user').textContent).toBe(''),
+      )
+
+      fireEvent.click(screen.getByRole('button', { name: /Login/i }))
+
+      await waitFor(() =>
+        expect(screen.getByTestId('loginLoading').textContent).toBe('true'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('loginLoading').textContent).toBe('false'),
+      )
+      // login mutation will cause the original errored out query to refire, clearing the error and setting the user
+      await waitFor(() =>
+        expect(screen.getByTestId('isError').textContent).toBe('false'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('user').textContent).toBe(
+          JSON.stringify(checkSessionData),
+        ),
+      )
+
+      const { checkSession, login } = api.endpoints
+      expect(storeRef.store.getState().actions).toMatchSequence(
+        api.internalActions.middlewareRegistered.match,
+        checkSession.matchPending,
+        checkSession.matchRejected,
+        login.matchPending,
+        login.matchFulfilled,
+        checkSession.matchPending,
+        checkSession.matchFulfilled,
+      )
+    })
+  })
+})
+
+describe('hooks with createApi defaults set', () => {
+  const defaultApi = createApi({
+    baseQuery: async (arg: any) => {
+      await waitMs()
+      if ('amount' in arg?.body) {
+        amount += 1
+      }
+      return {
+        data: arg?.body
+          ? { ...arg.body, ...(amount ? { amount } : {}) }
+          : undefined,
+      }
+    },
+    endpoints: (build) => ({
+      getIncrementedAmount: build.query<any, void>({
+        query: () => ({
+          url: '',
+          body: {
+            amount,
+          },
+        }),
+      }),
+    }),
+    refetchOnMountOrArgChange: true,
+  })
+
+  const storeRef = setupApiStore(defaultApi)
+  test('useQuery hook respects refetchOnMountOrArgChange: true when set in createApi options', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery())
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    const { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    unmount()
+
+    function OtherUser() {
+      ;({ data, isFetching } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnMountOrArgChange: true,
+        }))
+      return (
+        <div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    render(<OtherUser />, { wrapper: storeRef.wrapper })
+    // Let's make sure we actually fetch, and we increment
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('2'),
+    )
+  })
+
+  test('useQuery hook overrides default refetchOnMountOrArgChange: false that was set by createApi', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery())
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    let { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    unmount()
+
+    function OtherUser() {
+      ;({ data, isFetching } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnMountOrArgChange: false,
+        }))
+      return (
+        <div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    render(<OtherUser />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+  })
+
+  describe('selectFromResult (query) behaviors', () => {
+    let startingId = 3
+    const initialPosts = [
+      { id: 1, name: 'A sample post', fetched_at: new Date().toUTCString() },
+      {
+        id: 2,
+        name: 'A post about rtk-query',
+        fetched_at: new Date().toUTCString(),
+      },
+    ]
+    let posts = [] as typeof initialPosts
+
+    beforeEach(() => {
+      startingId = 3
+      posts = [...initialPosts]
+
+      const handlers = [
+        http.get('https://example.com/posts', () => {
+          return HttpResponse.json(posts)
+        }),
+        http.put<{ id: string }, Partial<Post>>(
+          'https://example.com/post/:id',
+          async ({ request, params }) => {
+            const body = await request.json()
+            const id = Number(params.id)
+            const idx = posts.findIndex((post) => post.id === id)
+
+            const newPosts = posts.map((post, index) =>
+              index !== idx
+                ? post
+                : {
+                    ...body,
+                    id,
+                    name: body?.name || post.name,
+                    fetched_at: new Date().toUTCString(),
+                  },
+            )
+            posts = [...newPosts]
+
+            return HttpResponse.json(posts)
+          },
+        ),
+        http.post<any, Omit<Post, 'id'>>(
+          'https://example.com/post',
+          async ({ request }) => {
+            const body = await request.json()
+            const post = body
+            startingId += 1
+            posts.concat({
+              ...post,
+              fetched_at: new Date().toISOString(),
+              id: startingId,
+            })
+            return HttpResponse.json(posts)
+          },
+        ),
+      ]
+
+      server.use(...handlers)
+    })
+
+    interface Post {
+      id: number
+      name: string
+      fetched_at: string
+    }
+
+    type PostsResponse = Post[]
+
+    const api = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/' }),
+      tagTypes: ['Posts'],
+      endpoints: (build) => ({
+        getPosts: build.query<PostsResponse, void>({
+          query: () => ({ url: 'posts' }),
+          providesTags: (result) =>
+            result ? result.map(({ id }) => ({ type: 'Posts', id })) : [],
+        }),
+        updatePost: build.mutation<Post, Partial<Post>>({
+          query: ({ id, ...body }) => ({
+            url: `post/${id}`,
+            method: 'PUT',
+            body,
+          }),
+          invalidatesTags: (result, error, { id }) => [{ type: 'Posts', id }],
+        }),
+        addPost: build.mutation<Post, Partial<Post>>({
+          query: (body) => ({
+            url: `post`,
+            method: 'POST',
+            body,
+          }),
+          invalidatesTags: ['Posts'],
+        }),
+      }),
+    })
+
+    const counterSlice = createSlice({
+      name: 'counter',
+      initialState: { count: 0 },
+      reducers: {
+        increment(state) {
+          state.count++
+        },
+      },
+    })
+
+    const storeRef = setupApiStore(api, {
+      counter: counterSlice.reducer,
+    })
+
+    test('useQueryState serves a deeply memoized value and does not rerender unnecessarily', async () => {
+      function Posts() {
+        const { data: posts } = api.endpoints.getPosts.useQuery()
+        const [addPost] = api.endpoints.addPost.useMutation()
+        return (
+          <div>
+            <button
+              data-testid="addPost"
+              onClick={() => addPost({ name: `some text ${posts?.length}` })}
+            >
+              Add random post
+            </button>
+          </div>
+        )
+      }
+
+      function SelectedPost() {
+        const { post } = api.endpoints.getPosts.useQueryState(undefined, {
+          selectFromResult: ({ data }) => ({
+            post: data?.find((post) => post.id === 1),
+          }),
+        })
+        getRenderCount = useRenderCounter()
+
+        /**
+         * Notes on the renderCount behavior
+         *
+         * We initialize at 0, and the first render will bump that 1 while post is `undefined`.
+         * Once the request resolves, it will be at 2. What we're looking for is to make sure that
+         * any requests that don't directly change the value of the selected item will have no impact
+         * on rendering.
+         */
+
+        return <div />
+      }
+
+      render(
+        <div>
+          <Posts />
+          <SelectedPost />
+        </div>,
+        { wrapper: storeRef.wrapper },
+      )
+
+      expect(getRenderCount()).toBe(1)
+
+      const addBtn = screen.getByTestId('addPost')
+
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+      // We fire off a few requests that would typically cause a rerender as JSON.parse() on a request would always be a new object.
+      fireEvent.click(addBtn)
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+      // Being that it didn't rerender, we can be assured that the behavior is correct
+    })
+
+    /**
+     * This test shows that even though a user can select a specific post, the fetching/loading flags
+     * will still cause rerenders for the query. This should show that if you're using selectFromResult,
+     * the 'performance' value comes with selecting _only_ the data.
+     */
+    test('useQuery with selectFromResult with all flags destructured rerenders like the default useQuery behavior', async () => {
+      function Posts() {
+        const { data: posts } = api.endpoints.getPosts.useQuery()
+        const [addPost] = api.endpoints.addPost.useMutation()
+        getRenderCount = useRenderCounter()
+        return (
+          <div>
+            <button
+              data-testid="addPost"
+              onClick={() =>
+                addPost({
+                  name: `some text ${posts?.length}`,
+                  fetched_at: new Date().toISOString(),
+                })
+              }
+            >
+              Add random post
+            </button>
+          </div>
+        )
+      }
+
+      function SelectedPost() {
+        getRenderCount = useRenderCounter()
+
+        const { post } = api.endpoints.getPosts.useQuery(undefined, {
+          selectFromResult: ({
+            data,
+            isUninitialized,
+            isLoading,
+            isFetching,
+            isSuccess,
+            isError,
+          }) => ({
+            post: data?.find((post) => post.id === 1),
+            isUninitialized,
+            isLoading,
+            isFetching,
+            isSuccess,
+            isError,
+          }),
+        })
+
+        return <div />
+      }
+
+      render(
+        <div>
+          <Posts />
+          <SelectedPost />
+        </div>,
+        { wrapper: storeRef.wrapper },
+      )
+      expect(getRenderCount()).toBe(2)
+
+      const addBtn = screen.getByTestId('addPost')
+
+      await waitFor(() => expect(getRenderCount()).toBe(3))
+
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(5))
+      fireEvent.click(addBtn)
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(7))
+    })
+
+    test('useQuery with selectFromResult option serves a deeply memoized value and does not rerender unnecessarily', async () => {
+      function Posts() {
+        const { data: posts } = api.endpoints.getPosts.useQuery()
+        const [addPost] = api.endpoints.addPost.useMutation()
+        return (
+          <div>
+            <button
+              data-testid="addPost"
+              onClick={() =>
+                addPost({
+                  name: `some text ${posts?.length}`,
+                  fetched_at: new Date().toISOString(),
+                })
+              }
+            >
+              Add random post
+            </button>
+          </div>
+        )
+      }
+
+      function SelectedPost() {
+        getRenderCount = useRenderCounter()
+        const { post } = api.endpoints.getPosts.useQuery(undefined, {
+          selectFromResult: ({ data }) => ({
+            post: data?.find((post) => post.id === 1),
+          }),
+        })
+
+        return <div />
+      }
+
+      render(
+        <div>
+          <Posts />
+          <SelectedPost />
+        </div>,
+        { wrapper: storeRef.wrapper },
+      )
+      expect(getRenderCount()).toBe(1)
+
+      const addBtn = screen.getByTestId('addPost')
+
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+      fireEvent.click(addBtn)
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+    })
+
+    test('useQuery with selectFromResult option serves a deeply memoized value, then ONLY updates when the underlying data changes', async () => {
+      let expectablePost: Post | undefined
+      function Posts() {
+        const { data: posts } = api.endpoints.getPosts.useQuery()
+        const [addPost] = api.endpoints.addPost.useMutation()
+        const [updatePost] = api.endpoints.updatePost.useMutation()
+
+        return (
+          <div>
+            <button
+              data-testid="addPost"
+              onClick={() =>
+                addPost({
+                  name: `some text ${posts?.length}`,
+                  fetched_at: new Date().toISOString(),
+                })
+              }
+            >
+              Add random post
+            </button>
+            <button
+              data-testid="updatePost"
+              onClick={() => updatePost({ id: 1, name: 'supercoooll!' })}
+            >
+              Update post
+            </button>
+          </div>
+        )
+      }
+
+      function SelectedPost() {
+        const { post } = api.endpoints.getPosts.useQuery(undefined, {
+          selectFromResult: ({ data }) => ({
+            post: data?.find((post) => post.id === 1),
+          }),
+        })
+        getRenderCount = useRenderCounter()
+
+        useEffect(() => {
+          expectablePost = post
+        }, [post])
+
+        return (
+          <div>
+            <div data-testid="postName">{post?.name}</div>
+          </div>
+        )
+      }
+
+      render(
+        <div>
+          <Posts />
+          <SelectedPost />
+        </div>,
+        { wrapper: storeRef.wrapper },
+      )
+      expect(getRenderCount()).toBe(1)
+
+      const addBtn = screen.getByTestId('addPost')
+      const updateBtn = screen.getByTestId('updatePost')
+
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+      fireEvent.click(addBtn)
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+
+      fireEvent.click(updateBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(3))
+      expect(expectablePost?.name).toBe('supercoooll!')
+
+      fireEvent.click(addBtn)
+      await waitFor(() => expect(getRenderCount()).toBe(3))
+    })
+
+    test('useQuery with selectFromResult option does not update when unrelated data in the store changes', async () => {
+      function Posts() {
+        const { posts } = api.endpoints.getPosts.useQuery(undefined, {
+          selectFromResult: ({ data }) => ({
+            // Intentionally use an unstable reference to force a rerender
+            posts: data?.filter((post) => post.name.includes('post')),
+          }),
+        })
+
+        getRenderCount = useRenderCounter()
+
+        return (
+          <div>
+            {posts?.map((post) => <div key={post.id}>{post.name}</div>)}
+          </div>
+        )
+      }
+
+      function CounterButton() {
+        return (
+          <div
+            data-testid="incrementButton"
+            onClick={() =>
+              storeRef.store.dispatch(counterSlice.actions.increment())
+            }
+          >
+            Increment Count
+          </div>
+        )
+      }
+
+      render(
+        <div>
+          <Posts />
+          <CounterButton />
+        </div>,
+        { wrapper: storeRef.wrapper },
+      )
+
+      await waitFor(() => expect(getRenderCount()).toBe(2))
+
+      const incrementBtn = screen.getByTestId('incrementButton')
+      fireEvent.click(incrementBtn)
+      expect(getRenderCount()).toBe(2)
+    })
+
+    test('useQuery with selectFromResult option has a type error if the result is not an object', async () => {
+      function SelectedPost() {
+        const res2 = api.endpoints.getPosts.useQuery(undefined, {
+          // selectFromResult must always return an object
+          selectFromResult: ({ data }) => ({ size: data?.length ?? 0 }),
+        })
+
+        return (
+          <div>
+            <div data-testid="size2">{res2.size}</div>
+          </div>
+        )
+      }
+
+      render(
+        <div>
+          <SelectedPost />
+        </div>,
+        { wrapper: storeRef.wrapper },
+      )
+
+      expect(screen.getByTestId('size2').textContent).toBe('0')
+    })
+  })
+
+  describe('selectFromResult (mutation) behavior', () => {
+    const api = createApi({
+      baseQuery: async (arg: any) => {
+        await waitMs()
+        if ('amount' in arg?.body) {
+          amount += 1
+        }
+        return {
+          data: arg?.body
+            ? { ...arg.body, ...(amount ? { amount } : {}) }
+            : undefined,
+        }
+      },
+      endpoints: (build) => ({
+        increment: build.mutation<{ amount: number }, number>({
+          query: (amount) => ({
+            url: '',
+            method: 'POST',
+            body: {
+              amount,
+            },
+          }),
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, {
+      ...actionsReducer,
+    })
+
+    it('causes no more than one rerender when using selectFromResult with an empty object', async () => {
+      function Counter() {
+        const [increment] = api.endpoints.increment.useMutation({
+          selectFromResult: () => ({}),
+        })
+        getRenderCount = useRenderCounter()
+
+        return (
+          <div>
+            <button
+              data-testid="incrementButton"
+              onClick={() => increment(1)}
+            ></button>
+          </div>
+        )
+      }
+
+      render(<Counter />, { wrapper: storeRef.wrapper })
+
+      expect(getRenderCount()).toBe(1)
+
+      fireEvent.click(screen.getByTestId('incrementButton'))
+      await waitMs(200) // give our baseQuery a chance to return
+      expect(getRenderCount()).toBe(2)
+
+      fireEvent.click(screen.getByTestId('incrementButton'))
+      await waitMs(200)
+      expect(getRenderCount()).toBe(3)
+
+      const { increment } = api.endpoints
+
+      expect(storeRef.store.getState().actions).toMatchSequence(
+        api.internalActions.middlewareRegistered.match,
+        increment.matchPending,
+        increment.matchFulfilled,
+        increment.matchPending,
+        api.internalActions.removeMutationResult.match,
+        increment.matchFulfilled,
+      )
+    })
+
+    it('causes rerenders when only selected data changes', async () => {
+      function Counter() {
+        const [increment, { data }] = api.endpoints.increment.useMutation({
+          selectFromResult: ({ data }) => ({ data }),
+        })
+        getRenderCount = useRenderCounter()
+
+        return (
+          <div>
+            <button
+              data-testid="incrementButton"
+              onClick={() => increment(1)}
+            ></button>
+            <div data-testid="data">{JSON.stringify(data)}</div>
+          </div>
+        )
+      }
+
+      render(<Counter />, { wrapper: storeRef.wrapper })
+
+      expect(getRenderCount()).toBe(1)
+
+      fireEvent.click(screen.getByTestId('incrementButton'))
+      await waitFor(() =>
+        expect(screen.getByTestId('data').textContent).toBe(
+          JSON.stringify({ amount: 1 }),
+        ),
+      )
+      expect(getRenderCount()).toBe(3)
+
+      fireEvent.click(screen.getByTestId('incrementButton'))
+      await waitFor(() =>
+        expect(screen.getByTestId('data').textContent).toBe(
+          JSON.stringify({ amount: 2 }),
+        ),
+      )
+      expect(getRenderCount()).toBe(5)
+    })
+
+    it('causes the expected # of rerenders when NOT using selectFromResult', async () => {
+      function Counter() {
+        const [increment, data] = api.endpoints.increment.useMutation()
+        getRenderCount = useRenderCounter()
+
+        return (
+          <div>
+            <button
+              data-testid="incrementButton"
+              onClick={() => increment(1)}
+            ></button>
+            <div data-testid="status">{String(data.status)}</div>
+          </div>
+        )
+      }
+
+      render(<Counter />, { wrapper: storeRef.wrapper })
+
+      expect(getRenderCount()).toBe(1) // mount, uninitialized status in substate
+
+      fireEvent.click(screen.getByTestId('incrementButton'))
+
+      expect(getRenderCount()).toBe(2) // will be pending, isLoading: true,
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('pending'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('fulfilled'),
+      )
+      expect(getRenderCount()).toBe(3)
+
+      fireEvent.click(screen.getByTestId('incrementButton'))
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('pending'),
+      )
+      await waitFor(() =>
+        expect(screen.getByTestId('status').textContent).toBe('fulfilled'),
+      )
+      expect(getRenderCount()).toBe(5)
+    })
+
+    it('useMutation with selectFromResult option has a type error if the result is not an object', async () => {
+      function Counter() {
+        const [increment] = api.endpoints.increment.useMutation({
+          // selectFromResult must always return an object
+          // @ts-expect-error
+          selectFromResult: () => 42,
+        })
+
+        return (
+          <div>
+            <button
+              data-testid="incrementButton"
+              onClick={() => increment(1)}
+            ></button>
+          </div>
+        )
+      }
+
+      render(<Counter />, { wrapper: storeRef.wrapper })
+    })
+  })
+})
+
+describe('skip behavior', () => {
+  const uninitialized = {
+    status: QueryStatus.uninitialized,
+    refetch: expect.any(Function),
+    data: undefined,
+    isError: false,
+    isFetching: false,
+    isLoading: false,
+    isSuccess: false,
+    isUninitialized: true,
+  }
+
+  test('normal skip', async () => {
+    const { result, rerender } = renderHook(
+      ([arg, options]: Parameters<typeof api.endpoints.getUser.useQuery>) =>
+        api.endpoints.getUser.useQuery(arg, options),
+      {
+        wrapper: storeRef.wrapper,
+        initialProps: [1, { skip: true }],
+      },
+    )
+
+    expect(result.current).toEqual(uninitialized)
+    await waitMs(1)
+    expect(getSubscriptionCount('getUser(1)')).toBe(0)
+
+    rerender([1])
+
+    await act(async () => {
+      await waitForFakeTimer(150)
+    })
+
+    expect(result.current).toMatchObject({ status: QueryStatus.fulfilled })
+    await waitMs(1)
+    expect(getSubscriptionCount('getUser(1)')).toBe(1)
+
+    rerender([1, { skip: true }])
+
+    expect(result.current).toEqual({
+      ...uninitialized,
+      isSuccess: true,
+      currentData: undefined,
+      data: { name: 'Timmy' },
+    })
+    await waitMs(1)
+    expect(getSubscriptionCount('getUser(1)')).toBe(0)
+  })
+
+  test('skipToken', async () => {
+    const { result, rerender } = renderHook(
+      ([arg, options]: Parameters<typeof api.endpoints.getUser.useQuery>) =>
+        api.endpoints.getUser.useQuery(arg, options),
+      {
+        wrapper: storeRef.wrapper,
+        initialProps: [skipToken],
+      },
+    )
+
+    expect(result.current).toEqual(uninitialized)
+    await waitMs(1)
+
+    expect(getSubscriptionCount('getUser(1)')).toBe(0)
+    // also no subscription on `getUser(skipToken)` or similar:
+    expect(getSubscriptions().size).toBe(0)
+
+    rerender([1])
+
+    await act(async () => {
+      await waitForFakeTimer(150)
+    })
+
+    expect(result.current).toMatchObject({ status: QueryStatus.fulfilled })
+    await waitMs(1)
+    expect(getSubscriptionCount('getUser(1)')).toBe(1)
+    expect(getSubscriptions().size).toBe(1)
+
+    rerender([skipToken])
+
+    expect(result.current).toEqual({
+      ...uninitialized,
+      isSuccess: true,
+      currentData: undefined,
+      data: { name: 'Timmy' },
+    })
+    await waitMs(1)
+    expect(getSubscriptionCount('getUser(1)')).toBe(0)
+  })
+
+  test('skipToken does not break serializeQueryArgs', async () => {
+    const { result, rerender } = renderHook(
+      ([arg, options]: Parameters<
+        typeof api.endpoints.queryWithDeepArg.useQuery
+      >) => api.endpoints.queryWithDeepArg.useQuery(arg, options),
+      {
+        wrapper: storeRef.wrapper,
+        initialProps: [skipToken],
+      },
+    )
+
+    expect(result.current).toEqual(uninitialized)
+    await waitMs(1)
+
+    expect(getSubscriptionCount('nestedValue')).toBe(0)
+    // also no subscription on `getUser(skipToken)` or similar:
+    expect(getSubscriptions().size).toBe(0)
+
+    rerender([{ param: { nested: 'nestedValue' } }])
+
+    await act(async () => {
+      await waitForFakeTimer(150)
+    })
+
+    expect(result.current).toMatchObject({ status: QueryStatus.fulfilled })
+    await waitMs(1)
+
+    expect(getSubscriptionCount('nestedValue')).toBe(1)
+    expect(getSubscriptions().size).toBe(1)
+
+    rerender([skipToken])
+
+    expect(result.current).toEqual({
+      ...uninitialized,
+      isSuccess: true,
+      currentData: undefined,
+      data: {},
+    })
+    await waitMs(1)
+    expect(getSubscriptionCount('nestedValue')).toBe(0)
+  })
+
+  test('skipping a previously fetched query retains the existing value as `data`, but clears `currentData`', async () => {
+    const { result, rerender } = renderHook(
+      ([arg, options]: Parameters<typeof api.endpoints.getUser.useQuery>) =>
+        api.endpoints.getUser.useQuery(arg, options),
+      {
+        wrapper: storeRef.wrapper,
+        initialProps: [1],
+      },
+    )
+
+    await act(async () => {
+      await waitForFakeTimer(150)
+    })
+
+    // Normal fulfilled result, with both `data` and `currentData`
+    expect(result.current).toMatchObject({
+      status: QueryStatus.fulfilled,
+      isSuccess: true,
+      data: { name: 'Timmy' },
+      currentData: { name: 'Timmy' },
+    })
+
+    rerender([1, { skip: true }])
+
+    // After skipping, the query is "uninitialized", but still retains the last fetched `data`
+    // even though it's skipped. `currentData` is undefined, since that matches the current arg.
+    expect(result.current).toMatchObject({
+      status: QueryStatus.uninitialized,
+      isSuccess: true,
+      data: { name: 'Timmy' },
+      currentData: undefined,
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildInitiate.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildInitiate.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildInitiate.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,306 @@
+import { setupApiStore } from '@internal/tests/utils/helpers'
+import { createApi } from '../core'
+import type { SubscriptionSelectors } from '../core/buildMiddleware/types'
+import { fakeBaseQuery } from '../fakeBaseQuery'
+import { delay } from '@internal/utils'
+
+let calls = 0
+const api = createApi({
+  baseQuery: fakeBaseQuery(),
+  endpoints: (build) => ({
+    increment: build.query<number, void>({
+      async queryFn() {
+        const data = calls++
+        await Promise.resolve()
+        return { data }
+      },
+    }),
+    incrementKeep0: build.query<number, void>({
+      async queryFn() {
+        const data = calls++
+        await delay(10)
+        return { data }
+      },
+      keepUnusedDataFor: 0,
+    }),
+    failing: build.query<void, void>({
+      async queryFn() {
+        await Promise.resolve()
+        return { error: { status: 500, data: 'error' } }
+      },
+    }),
+  }),
+})
+
+const storeRef = setupApiStore(api)
+
+let getSubscriptions: SubscriptionSelectors['getSubscriptions']
+let isRequestSubscribed: SubscriptionSelectors['isRequestSubscribed']
+
+beforeEach(() => {
+  ;({ getSubscriptions, isRequestSubscribed } = storeRef.store.dispatch(
+    api.internalActions.internal_getRTKQSubscriptions(),
+  ) as unknown as SubscriptionSelectors)
+})
+
+test('multiple synchonrous initiate calls with pre-existing cache entry', async () => {
+  const { store, api } = storeRef
+  // seed the store
+  const firstValue = await store.dispatch(api.endpoints.increment.initiate())
+
+  expect(firstValue).toMatchObject({ data: 0, status: 'fulfilled' })
+
+  // dispatch another increment
+  const secondValuePromise = store.dispatch(api.endpoints.increment.initiate())
+  // and one with a forced refresh
+  const thirdValuePromise = store.dispatch(
+    api.endpoints.increment.initiate(undefined, { forceRefetch: true }),
+  )
+  // and another increment
+  const fourthValuePromise = store.dispatch(api.endpoints.increment.initiate())
+
+  const secondValue = await secondValuePromise
+  const thirdValue = await thirdValuePromise
+  const fourthValue = await fourthValuePromise
+
+  expect(secondValue).toMatchObject({
+    data: firstValue.data,
+    status: 'fulfilled',
+    requestId: firstValue.requestId,
+  })
+
+  expect(thirdValue).toMatchObject({ data: 1, status: 'fulfilled' })
+  expect(thirdValue.requestId).not.toBe(firstValue.requestId)
+  expect(fourthValue).toMatchObject({
+    data: thirdValue.data,
+    status: 'fulfilled',
+    requestId: thirdValue.requestId,
+  })
+})
+
+describe('calling initiate without a cache entry, with subscribe: false still returns correct values', () => {
+  test('successful query', async () => {
+    const { store, api } = storeRef
+    calls = 0
+    const promise = store.dispatch(
+      api.endpoints.increment.initiate(undefined, { subscribe: false }),
+    )
+    expect(isRequestSubscribed('increment(undefined)', promise.requestId)).toBe(
+      false,
+    )
+
+    await expect(promise).resolves.toMatchObject({
+      data: 0,
+      status: 'fulfilled',
+    })
+  })
+
+  test('successful query with keepUnusedDataFor: 0', async () => {
+    const { store, api } = storeRef
+    calls = 0
+    const promise = store.dispatch(
+      api.endpoints.incrementKeep0.initiate(undefined, { subscribe: false }),
+    )
+    expect(isRequestSubscribed('increment(undefined)', promise.requestId)).toBe(
+      false,
+    )
+
+    await expect(promise.unwrap()).resolves.toBe(0)
+  })
+
+  test('rejected query', async () => {
+    const { store, api } = storeRef
+    calls = 0
+    const promise = store.dispatch(
+      api.endpoints.failing.initiate(undefined, { subscribe: false }),
+    )
+    expect(isRequestSubscribed('failing(undefined)', promise.requestId)).toBe(
+      false,
+    )
+
+    await expect(promise).resolves.toMatchObject({
+      status: 'rejected',
+    })
+  })
+})
+
+describe('calling initiate should have resulting queryCacheKey match baseQuery queryCacheKey', () => {
+  const baseQuery = vi.fn(() => ({ data: 'success' }))
+  function getNewApi() {
+    return createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        query: build.query<void, { arg1: string; arg2: string }>({
+          query: (args) => `queryUrl/${args.arg1}/${args.arg2}`,
+        }),
+        mutation: build.mutation<void, { arg1: string; arg2: string }>({
+          query: () => 'mutationUrl',
+        }),
+      }),
+    })
+  }
+  let api = getNewApi()
+  beforeEach(() => {
+    baseQuery.mockClear()
+    api = getNewApi()
+  })
+
+  test('should be a string and matching on queries', () => {
+    const { store: storeApi } = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    const promise = storeApi.dispatch(
+      api.endpoints.query.initiate({ arg2: 'secondArg', arg1: 'firstArg' }),
+    )
+    expect(baseQuery).toHaveBeenCalledWith(
+      expect.any(String),
+      expect.objectContaining({
+        queryCacheKey: promise.queryCacheKey,
+      }),
+      undefined,
+    )
+  })
+
+  test('should be undefined and matching on mutations', () => {
+    const { store: storeApi } = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeApi.dispatch(
+      api.endpoints.mutation.initiate({ arg2: 'secondArg', arg1: 'firstArg' }),
+    )
+    expect(baseQuery).toHaveBeenCalledWith(
+      expect.any(String),
+      expect.objectContaining({
+        queryCacheKey: undefined,
+      }),
+      undefined,
+    )
+  })
+})
+
+describe('getRunningQueryThunk with multiple stores', () => {
+  test('should isolate running queries between different store instances using the same API', async () => {
+    // Create a shared API instance
+    const sharedApi = createApi({
+      baseQuery: fakeBaseQuery(),
+      endpoints: (build) => ({
+        testQuery: build.query<string, string>({
+          async queryFn(arg) {
+            // Add delay to ensure queries are running when we check
+            await new Promise((resolve) => setTimeout(resolve, 50))
+            return { data: `result-${arg}` }
+          },
+        }),
+      }),
+    })
+
+    // Create two separate stores using the same API instance
+    const store1 = setupApiStore(sharedApi, undefined, {
+      withoutTestLifecycles: true,
+    }).store
+    const store2 = setupApiStore(sharedApi, undefined, {
+      withoutTestLifecycles: true,
+    }).store
+
+    // Start queries on both stores
+    const query1Promise = store1.dispatch(
+      sharedApi.endpoints.testQuery.initiate('arg1'),
+    )
+    const query2Promise = store2.dispatch(
+      sharedApi.endpoints.testQuery.initiate('arg2'),
+    )
+
+    // Verify that getRunningQueryThunk returns the correct query for each store
+    const runningQuery1 = store1.dispatch(
+      sharedApi.util.getRunningQueryThunk('testQuery', 'arg1'),
+    )
+    const runningQuery2 = store2.dispatch(
+      sharedApi.util.getRunningQueryThunk('testQuery', 'arg2'),
+    )
+
+    // Each store should only see its own running query
+    expect(runningQuery1).toBeDefined()
+    expect(runningQuery2).toBeDefined()
+    expect(runningQuery1?.requestId).toBe(query1Promise.requestId)
+    expect(runningQuery2?.requestId).toBe(query2Promise.requestId)
+
+    // Cross-store queries should not be visible
+    const crossQuery1 = store1.dispatch(
+      sharedApi.util.getRunningQueryThunk('testQuery', 'arg2'),
+    )
+    const crossQuery2 = store2.dispatch(
+      sharedApi.util.getRunningQueryThunk('testQuery', 'arg1'),
+    )
+
+    expect(crossQuery1).toBeUndefined()
+    expect(crossQuery2).toBeUndefined()
+
+    // Wait for queries to complete
+    await Promise.all([query1Promise, query2Promise])
+
+    // After completion, getRunningQueryThunk should return undefined for both stores
+    const completedQuery1 = store1.dispatch(
+      sharedApi.util.getRunningQueryThunk('testQuery', 'arg1'),
+    )
+    const completedQuery2 = store2.dispatch(
+      sharedApi.util.getRunningQueryThunk('testQuery', 'arg2'),
+    )
+
+    expect(completedQuery1).toBeUndefined()
+    expect(completedQuery2).toBeUndefined()
+  })
+
+  test('should handle same query args on different stores independently', async () => {
+    // Create a shared API instance
+    const sharedApi = createApi({
+      baseQuery: fakeBaseQuery(),
+      endpoints: (build) => ({
+        sameArgQuery: build.query<string, string>({
+          async queryFn(arg) {
+            await new Promise((resolve) => setTimeout(resolve, 50))
+            return { data: `result-${arg}-${Math.random()}` }
+          },
+        }),
+      }),
+    })
+
+    // Create two separate stores
+    const store1 = setupApiStore(sharedApi, undefined, {
+      withoutTestLifecycles: true,
+    }).store
+    const store2 = setupApiStore(sharedApi, undefined, {
+      withoutTestLifecycles: true,
+    }).store
+
+    // Start the same query on both stores
+    const sameArg = 'shared-arg'
+    const query1Promise = store1.dispatch(
+      sharedApi.endpoints.sameArgQuery.initiate(sameArg),
+    )
+    const query2Promise = store2.dispatch(
+      sharedApi.endpoints.sameArgQuery.initiate(sameArg),
+    )
+
+    // Both stores should see their own running query with the same cache key
+    const runningQuery1 = store1.dispatch(
+      sharedApi.util.getRunningQueryThunk('sameArgQuery', sameArg),
+    )
+    const runningQuery2 = store2.dispatch(
+      sharedApi.util.getRunningQueryThunk('sameArgQuery', sameArg),
+    )
+
+    expect(runningQuery1).toBeDefined()
+    expect(runningQuery2).toBeDefined()
+    expect(runningQuery1?.requestId).toBe(query1Promise.requestId)
+    expect(runningQuery2?.requestId).toBe(query2Promise.requestId)
+
+    // The request IDs should be different even though the cache key is the same
+    expect(runningQuery1?.requestId).not.toBe(runningQuery2?.requestId)
+
+    // But the cache keys should be the same
+    expect(runningQuery1?.queryCacheKey).toBe(runningQuery2?.queryCacheKey)
+
+    // Wait for completion
+    await Promise.all([query1Promise, query2Promise])
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildMiddleware.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildMiddleware.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildMiddleware.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,83 @@
+import { createApi } from '@reduxjs/toolkit/query'
+
+const baseQuery = (args?: any) => ({ data: args })
+
+const api = createApi({
+  baseQuery,
+  tagTypes: ['Banana', 'Bread'],
+  endpoints: (build) => ({
+    getBanana: build.query<unknown, number>({
+      query(id) {
+        return { url: `banana/${id}` }
+      },
+      providesTags: ['Banana'],
+    }),
+    getBananas: build.query<unknown, void>({
+      query() {
+        return { url: 'bananas' }
+      },
+      providesTags: ['Banana'],
+    }),
+    getBread: build.query<unknown, number>({
+      query(id) {
+        return { url: `bread/${id}` }
+      },
+      providesTags: ['Bread'],
+    }),
+  }),
+})
+
+describe('type tests', () => {
+  it('should allow for an array of string TagTypes', () => {
+    api.util.invalidateTags(['Banana', 'Bread'])
+  })
+
+  it('should allow for an array of full TagTypes descriptions', () => {
+    api.util.invalidateTags([{ type: 'Banana' }, { type: 'Bread', id: 1 }])
+  })
+
+  it('should allow for a mix of full descriptions as well as plain strings', () => {
+    api.util.invalidateTags(['Banana', { type: 'Bread', id: 1 }])
+  })
+
+  it('should error when using non-existing TagTypes', () => {
+    // @ts-expect-error
+    api.util.invalidateTags(['Missing Tag'])
+  })
+
+  it('should error when using non-existing TagTypes in the full format', () => {
+    // @ts-expect-error
+    api.util.invalidateTags([{ type: 'Missing' }])
+  })
+
+  it('should allow pre-fetching for an endpoint that takes an arg', () => {
+    api.util.prefetch('getBanana', 5, { force: true })
+    api.util.prefetch('getBanana', 5, { force: false })
+    api.util.prefetch('getBanana', 5, { ifOlderThan: false })
+    api.util.prefetch('getBanana', 5, { ifOlderThan: 30 })
+    api.util.prefetch('getBanana', 5, {})
+  })
+
+  it('should error when pre-fetching with the incorrect arg type', () => {
+    // @ts-expect-error arg should be number, not string
+    api.util.prefetch('getBanana', '5', { force: true })
+  })
+
+  it('should allow pre-fetching for an endpoint with a void arg', () => {
+    api.util.prefetch('getBananas', undefined, { force: true })
+    api.util.prefetch('getBananas', undefined, { force: false })
+    api.util.prefetch('getBananas', undefined, { ifOlderThan: false })
+    api.util.prefetch('getBananas', undefined, { ifOlderThan: 30 })
+    api.util.prefetch('getBananas', undefined, {})
+  })
+
+  it('should error when pre-fetching with a defined arg when expecting void', () => {
+    // @ts-expect-error arg should be void, not number
+    api.util.prefetch('getBananas', 5, { force: true })
+  })
+
+  it('should error when pre-fetching for an incorrect endpoint name', () => {
+    // @ts-expect-error endpoint name does not exist
+    api.util.prefetch('getPomegranates', undefined, { force: true })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildMiddleware.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildMiddleware.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildMiddleware.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,266 @@
+import { createApi } from '@reduxjs/toolkit/query'
+import { delay } from 'msw'
+import { actionsReducer, setupApiStore } from '../../tests/utils/helpers'
+import { vi } from 'vitest'
+
+const baseQuery = (args?: any) => ({ data: args })
+const api = createApi({
+  baseQuery,
+  tagTypes: ['Banana', 'Bread'],
+  endpoints: (build) => ({
+    getBanana: build.query<unknown, number>({
+      query(id) {
+        return { url: `banana/${id}` }
+      },
+      providesTags: ['Banana'],
+    }),
+    getBananas: build.query<unknown, void>({
+      query() {
+        return { url: 'bananas' }
+      },
+      providesTags: ['Banana'],
+    }),
+    getBread: build.query<unknown, number>({
+      query(id) {
+        return { url: `bread/${id}` }
+      },
+      providesTags: ['Bread'],
+    }),
+    invalidateFruit: build.mutation({
+      query: (fruit?: 'Banana' | 'Bread' | null) => ({
+        url: `invalidate/fruit/${fruit || ''}`,
+      }),
+      invalidatesTags(result, error, arg) {
+        return [arg]
+      },
+    }),
+  }),
+})
+const { getBanana, getBread, invalidateFruit } = api.endpoints
+
+const storeRef = setupApiStore(api, {
+  ...actionsReducer,
+})
+
+it('invalidates the specified tags', async () => {
+  await storeRef.store.dispatch(getBanana.initiate(1))
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    getBanana.matchPending,
+    getBanana.matchFulfilled,
+  )
+
+  await storeRef.store.dispatch(api.util.invalidateTags(['Banana', 'Bread']))
+
+  // Slight pause to let the middleware run and such
+  await delay(20)
+
+  const firstSequence = [
+    api.internalActions.middlewareRegistered.match,
+    getBanana.matchPending,
+    getBanana.matchFulfilled,
+    api.util.invalidateTags.match,
+    getBanana.matchPending,
+    getBanana.matchFulfilled,
+  ]
+  expect(storeRef.store.getState().actions).toMatchSequence(...firstSequence)
+
+  await storeRef.store.dispatch(getBread.initiate(1))
+  await storeRef.store.dispatch(api.util.invalidateTags([{ type: 'Bread' }]))
+
+  await delay(20)
+
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    ...firstSequence,
+    getBread.matchPending,
+    getBread.matchFulfilled,
+    api.util.invalidateTags.match,
+    getBread.matchPending,
+    getBread.matchFulfilled,
+  )
+})
+
+it('invalidates tags correctly when null or undefined are provided as tags', async () => {
+  await storeRef.store.dispatch(getBanana.initiate(1))
+  await storeRef.store.dispatch(
+    api.util.invalidateTags([undefined, null, 'Banana']),
+  )
+
+  // Slight pause to let the middleware run and such
+  await delay(20)
+
+  const apiActions = [
+    api.internalActions.middlewareRegistered.match,
+    getBanana.matchPending,
+    getBanana.matchFulfilled,
+    api.util.invalidateTags.match,
+    getBanana.matchPending,
+    getBanana.matchFulfilled,
+  ]
+
+  expect(storeRef.store.getState().actions).toMatchSequence(...apiActions)
+})
+
+it.each([
+  {
+    tags: [undefined, null, 'Bread'] as Parameters<
+      typeof api.util.invalidateTags
+    >['0'],
+  },
+  { tags: [undefined, null] },
+  { tags: [] },
+])(
+  'does not invalidate with tags=$tags if no query matches',
+  async ({ tags }) => {
+    await storeRef.store.dispatch(getBanana.initiate(1))
+    await storeRef.store.dispatch(api.util.invalidateTags(tags))
+
+    // Slight pause to let the middleware run and such
+    await delay(20)
+
+    const apiActions = [
+      api.internalActions.middlewareRegistered.match,
+      getBanana.matchPending,
+      getBanana.matchFulfilled,
+      api.util.invalidateTags.match,
+    ]
+
+    expect(storeRef.store.getState().actions).toMatchSequence(...apiActions)
+  },
+)
+
+it.each([
+  { mutationArg: 'Bread' as 'Bread' | null | undefined },
+  { mutationArg: undefined },
+  { mutationArg: null },
+])(
+  'does not invalidate queries when a mutation with tags=[$mutationArg] runs and does not match anything',
+  async ({ mutationArg }) => {
+    await storeRef.store.dispatch(getBanana.initiate(1))
+    await storeRef.store.dispatch(invalidateFruit.initiate(mutationArg))
+
+    // Slight pause to let the middleware run and such
+    await delay(20)
+
+    const apiActions = [
+      api.internalActions.middlewareRegistered.match,
+      getBanana.matchPending,
+      getBanana.matchFulfilled,
+      invalidateFruit.matchPending,
+      invalidateFruit.matchFulfilled,
+    ]
+
+    expect(storeRef.store.getState().actions).toMatchSequence(...apiActions)
+  },
+)
+
+it('correctly stringifies subscription state and dispatches subscriptionsUpdated', async () => {
+  // Create a fresh store for this test to avoid interference
+  const testStoreRef = setupApiStore(
+    api,
+    {
+      ...actionsReducer,
+    },
+    { withoutListeners: true },
+  )
+
+  // Start multiple subscriptions
+  const subscription1 = testStoreRef.store.dispatch(
+    getBanana.initiate(1, {
+      subscriptionOptions: { pollingInterval: 1000 },
+    }),
+  )
+  const subscription2 = testStoreRef.store.dispatch(
+    getBanana.initiate(2, {
+      subscriptionOptions: { refetchOnFocus: true },
+    }),
+  )
+  const subscription3 = testStoreRef.store.dispatch(
+    api.endpoints.getBananas.initiate(),
+  )
+
+  // Wait for the subscriptions to be established
+  await Promise.all([subscription1, subscription2, subscription3])
+
+  // Wait for the subscription sync timer (500ms + buffer)
+  await delay(600)
+
+  // Check the final subscription state in the store
+  const finalState = testStoreRef.store.getState()
+  const subscriptionState = finalState[api.reducerPath].subscriptions
+
+  // Should have subscriptions for getBanana(1), getBanana(2), and getBananas()
+  expect(subscriptionState).toMatchObject({
+    'getBanana(1)': {
+      [subscription1.requestId]: { pollingInterval: 1000 },
+    },
+    'getBanana(2)': {
+      [subscription2.requestId]: { refetchOnFocus: true },
+    },
+    'getBananas(undefined)': {
+      [subscription3.requestId]: {},
+    },
+  })
+
+  // Verify the subscription entries have the expected structure
+  expect(Object.keys(subscriptionState)).toHaveLength(3)
+  expect(subscriptionState['getBanana(1)']?.[subscription1.requestId]).toEqual({
+    pollingInterval: 1000,
+  })
+  expect(subscriptionState['getBanana(2)']?.[subscription2.requestId]).toEqual({
+    refetchOnFocus: true,
+  })
+  expect(
+    subscriptionState['getBananas(undefined)']?.[subscription3.requestId],
+  ).toEqual({})
+})
+
+it('does not leak subscription state between multiple stores using the same API instance (SSR scenario)', async () => {
+  vi.useFakeTimers()
+  // Simulate SSR: create API once at module level
+  const sharedApi = createApi({
+    baseQuery: (args?: any) => ({ data: args }),
+    tagTypes: ['Test'],
+    endpoints: (build) => ({
+      getTest: build.query<unknown, number>({
+        query(id) {
+          return { url: `test/${id}` }
+        },
+      }),
+    }),
+  })
+
+  // Create first store (simulating first SSR request)
+  const store1Ref = setupApiStore(sharedApi, {}, { withoutListeners: true })
+
+  // Add subscription in store1
+  const sub1 = store1Ref.store.dispatch(
+    sharedApi.endpoints.getTest.initiate(1, {
+      subscriptionOptions: { pollingInterval: 1000 },
+    }),
+  )
+  vi.advanceTimersByTime(10)
+  await sub1
+
+  // Wait for subscription sync (500ms + buffer)
+  vi.advanceTimersByTime(600)
+
+  // Verify store1 has the subscription
+  const store1SubscriptionSelectors = store1Ref.store.dispatch(
+    sharedApi.internalActions.internal_getRTKQSubscriptions(),
+  ) as any
+  const store1InternalSubs = store1SubscriptionSelectors.getSubscriptions()
+  expect(store1InternalSubs.size).toBe(1)
+
+  // Create second store (simulating second SSR request)
+  const store2Ref = setupApiStore(sharedApi, {}, { withoutListeners: true })
+
+  // Check subscriptions via internal action
+  const store2SubscriptionSelectors = store2Ref.store.dispatch(
+    sharedApi.internalActions.internal_getRTKQSubscriptions(),
+  ) as any
+
+  const store2InternalSubs = store2SubscriptionSelectors.getSubscriptions()
+
+  expect(store2InternalSubs.size).toBe(0)
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildSelector.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildSelector.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildSelector.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,111 @@
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+
+import { configureStore, createSelector } from '@reduxjs/toolkit'
+
+describe('type tests', () => {
+  test('buildSelector type test', () => {
+    interface Todo {
+      userId: number
+      id: number
+      title: string
+      completed: boolean
+    }
+
+    type Todos = Array<Todo>
+
+    const exampleApi = createApi({
+      reducerPath: 'api',
+      baseQuery: fetchBaseQuery({
+        baseUrl: 'https://jsonplaceholder.typicode.com',
+      }),
+      endpoints: (build) => ({
+        getTodos: build.query<Todos, string>({
+          query: () => '/todos',
+        }),
+      }),
+    })
+
+    const exampleQuerySelector = exampleApi.endpoints.getTodos.select('/')
+
+    const todosSelector = createSelector(
+      [exampleQuerySelector],
+      (queryState) => {
+        return queryState?.data?.[0] ?? ({} as Todo)
+      },
+    )
+
+    const firstTodoTitleSelector = createSelector(
+      [todosSelector],
+      (todo) => todo?.title,
+    )
+
+    const store = configureStore({
+      reducer: {
+        [exampleApi.reducerPath]: exampleApi.reducer,
+        other: () => 1,
+      },
+    })
+
+    const todoTitle = firstTodoTitleSelector(store.getState())
+
+    // This only compiles if we carried the types through
+    const upperTitle = todoTitle.toUpperCase()
+
+    expectTypeOf(upperTitle).toBeString()
+  })
+
+  test('selectCachedArgsForQuery type test', () => {
+    interface Todo {
+      userId: number
+      id: number
+      title: string
+      completed: boolean
+    }
+
+    type Todos = Array<Todo>
+
+    const exampleApi = createApi({
+      reducerPath: 'api',
+      baseQuery: fetchBaseQuery({
+        baseUrl: 'https://jsonplaceholder.typicode.com',
+      }),
+      endpoints: (build) => ({
+        getTodos: build.query<Todos, string>({
+          query: () => '/todos',
+        }),
+        getInfiniteTodos: build.infiniteQuery<Todos, string, number>({
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            maxPages: 3,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+          },
+          query({ pageParam }) {
+            return `/todos?page=${pageParam}`
+          },
+        }),
+      }),
+    })
+
+    const store = configureStore({
+      reducer: {
+        [exampleApi.reducerPath]: exampleApi.reducer,
+        other: () => 1,
+      },
+    })
+
+    expectTypeOf(
+      exampleApi.util.selectCachedArgsForQuery(store.getState(), 'getTodos'),
+    ).toEqualTypeOf<string[]>()
+    expectTypeOf(
+      exampleApi.util.selectCachedArgsForQuery(
+        store.getState(),
+        'getInfiniteTodos',
+      ),
+    ).toEqualTypeOf<string[]>()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildSlice.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildSlice.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildSlice.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,239 @@
+import { createSlice, createAction } from '@reduxjs/toolkit'
+import type { CombinedState } from '@reduxjs/toolkit/query'
+import { createApi } from '@reduxjs/toolkit/query'
+import { delay } from 'msw'
+import { setupApiStore } from '../../tests/utils/helpers'
+
+let shouldApiResponseSuccess = true
+
+const rehydrateAction = createAction<{ api: CombinedState<any, any, any> }>(
+  'persist/REHYDRATE',
+)
+
+const baseQuery = (args?: any) => ({ data: args })
+const api = createApi({
+  baseQuery,
+  tagTypes: ['SUCCEED', 'FAILED'],
+  endpoints: (build) => ({
+    getUser: build.query<{ url: string; success: boolean }, number>({
+      query(id) {
+        return { url: `user/${id}`, success: shouldApiResponseSuccess }
+      },
+      providesTags: (result) => (result?.success ? ['SUCCEED'] : ['FAILED']),
+    }),
+  }),
+  extractRehydrationInfo(action, { reducerPath }) {
+    if (rehydrateAction.match(action)) {
+      return action.payload?.[reducerPath]
+    }
+    return undefined
+  },
+})
+const { getUser } = api.endpoints
+
+const authSlice = createSlice({
+  name: 'auth',
+  initialState: {
+    token: '1234',
+  },
+  reducers: {
+    setToken(state, action) {
+      state.token = action.payload
+    },
+  },
+})
+
+const storeRef = setupApiStore(api, { auth: authSlice.reducer })
+
+describe('buildSlice', () => {
+  beforeEach(() => {
+    shouldApiResponseSuccess = true
+  })
+
+  it('only resets the api state when resetApiState is dispatched', async () => {
+    storeRef.store.dispatch({ type: 'unrelated' }) // trigger "registered middleware" into place
+    const initialState = storeRef.store.getState()
+
+    await storeRef.store.dispatch(
+      getUser.initiate(1, { subscriptionOptions: { pollingInterval: 10 } }),
+    )
+
+    const initialQueryState = {
+      api: {
+        config: {
+          focused: true,
+          invalidationBehavior: 'delayed',
+          keepUnusedDataFor: 60,
+          middlewareRegistered: true,
+          online: true,
+          reducerPath: 'api',
+          refetchOnFocus: false,
+          refetchOnMountOrArgChange: false,
+          refetchOnReconnect: false,
+        },
+        mutations: {},
+        provided: expect.any(Object),
+        queries: {
+          'getUser(1)': {
+            data: {
+              success: true,
+              url: 'user/1',
+            },
+            endpointName: 'getUser',
+            fulfilledTimeStamp: expect.any(Number),
+            originalArgs: 1,
+            requestId: expect.any(String),
+            startedTimeStamp: expect.any(Number),
+            status: 'fulfilled',
+          },
+        },
+        // Filled some time later
+        subscriptions: {},
+      },
+      auth: {
+        token: '1234',
+      },
+    }
+
+    expect(storeRef.store.getState()).toEqual(initialQueryState)
+
+    storeRef.store.dispatch(api.util.resetApiState())
+
+    expect(storeRef.store.getState()).toEqual(initialState)
+  })
+
+  it('replaces previous tags with new provided tags', async () => {
+    await storeRef.store.dispatch(getUser.initiate(1))
+
+    expect(
+      api.util.selectInvalidatedBy(storeRef.store.getState(), ['SUCCEED']),
+    ).toHaveLength(1)
+    expect(
+      api.util.selectInvalidatedBy(storeRef.store.getState(), ['FAILED']),
+    ).toHaveLength(0)
+
+    shouldApiResponseSuccess = false
+
+    storeRef.store.dispatch(getUser.initiate(1)).refetch()
+
+    await delay(10)
+
+    expect(
+      api.util.selectInvalidatedBy(storeRef.store.getState(), ['SUCCEED']),
+    ).toHaveLength(0)
+    expect(
+      api.util.selectInvalidatedBy(storeRef.store.getState(), ['FAILED']),
+    ).toHaveLength(1)
+  })
+
+  it('handles extractRehydrationInfo correctly', async () => {
+    await storeRef.store.dispatch(getUser.initiate(1))
+    await storeRef.store.dispatch(getUser.initiate(2))
+
+    const stateWithUser = storeRef.store.getState()
+
+    storeRef.store.dispatch(api.util.resetApiState())
+
+    storeRef.store.dispatch(rehydrateAction({ api: stateWithUser.api }))
+
+    const rehydratedState = storeRef.store.getState()
+    expect(rehydratedState).toEqual(stateWithUser)
+  })
+})
+
+describe('`merge` callback', () => {
+  const baseQuery = (args?: any) => ({ data: args })
+
+  interface Todo {
+    id: string
+    text: string
+  }
+
+  it('Calls `merge` once there is existing data, and allows mutations of cache state', async () => {
+    let mergeCalled = false
+    let queryFnCalls = 0
+    const todoTexts = ['A', 'B', 'C', 'D']
+
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        getTodos: build.query<Todo[], void>({
+          async queryFn() {
+            const text = todoTexts[queryFnCalls]
+            return { data: [{ id: `${queryFnCalls++}`, text }] }
+          },
+          merge(currentCacheValue, responseData) {
+            mergeCalled = true
+            currentCacheValue.push(...responseData)
+          },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    const selectTodoEntry = api.endpoints.getTodos.select()
+
+    const res = storeRef.store.dispatch(api.endpoints.getTodos.initiate())
+    await res
+    expect(mergeCalled).toBe(false)
+    const todoEntry1 = selectTodoEntry(storeRef.store.getState())
+    expect(todoEntry1.data).toEqual([{ id: '0', text: 'A' }])
+
+    res.refetch()
+
+    await delay(10)
+
+    expect(mergeCalled).toBe(true)
+    const todoEntry2 = selectTodoEntry(storeRef.store.getState())
+
+    expect(todoEntry2.data).toEqual([
+      { id: '0', text: 'A' },
+      { id: '1', text: 'B' },
+    ])
+  })
+
+  it('Allows returning a different value from `merge`', async () => {
+    let firstQueryFnCall = true
+
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        getTodos: build.query<Todo[], void>({
+          async queryFn() {
+            const item = firstQueryFnCall
+              ? { id: '0', text: 'A' }
+              : { id: '1', text: 'B' }
+            firstQueryFnCall = false
+            return { data: [item] }
+          },
+          merge(currentCacheValue, responseData) {
+            return responseData
+          },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    const selectTodoEntry = api.endpoints.getTodos.select()
+
+    const res = storeRef.store.dispatch(api.endpoints.getTodos.initiate())
+    await res
+
+    const todoEntry1 = selectTodoEntry(storeRef.store.getState())
+    expect(todoEntry1.data).toEqual([{ id: '0', text: 'A' }])
+
+    res.refetch()
+
+    await delay(10)
+
+    const todoEntry2 = selectTodoEntry(storeRef.store.getState())
+
+    expect(todoEntry2.data).toEqual([{ id: '1', text: 'B' }])
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/buildThunks.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/buildThunks.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/buildThunks.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,420 @@
+import { configureStore } from '@reduxjs/toolkit'
+import { createApi } from '@reduxjs/toolkit/query/react'
+import { renderHook, waitFor } from '@testing-library/react'
+import {
+  actionsReducer,
+  setupApiStore,
+  withProvider,
+} from '../../tests/utils/helpers'
+import type { BaseQueryApi } from '../baseQueryTypes'
+
+describe('baseline thunk behavior', () => {
+  test('handles a non-async baseQuery without error', async () => {
+    const baseQuery = (args?: any) => ({ data: args })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        getUser: build.query<unknown, number>({
+          query(id) {
+            return { url: `user/${id}` }
+          },
+        }),
+      }),
+    })
+    const { getUser } = api.endpoints
+    const store = configureStore({
+      reducer: {
+        [api.reducerPath]: api.reducer,
+      },
+      middleware: (gDM) => gDM().concat(api.middleware),
+    })
+
+    const promise = store.dispatch(getUser.initiate(1))
+    const { data } = await promise
+
+    expect(data).toEqual({
+      url: 'user/1',
+    })
+
+    const storeResult = getUser.select(1)(store.getState())
+    expect(storeResult).toEqual({
+      data: {
+        url: 'user/1',
+      },
+      endpointName: 'getUser',
+      isError: false,
+      isLoading: false,
+      isSuccess: true,
+      isUninitialized: false,
+      originalArgs: 1,
+      requestId: expect.any(String),
+      status: 'fulfilled',
+      startedTimeStamp: expect.any(Number),
+      fulfilledTimeStamp: expect.any(Number),
+    })
+  })
+
+  test('passes the extraArgument property to the baseQueryApi', async () => {
+    const baseQuery = (_args: any, api: BaseQueryApi) => ({ data: api.extra })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        getUser: build.query<unknown, void>({
+          query: () => '',
+        }),
+      }),
+    })
+    const store = configureStore({
+      reducer: {
+        [api.reducerPath]: api.reducer,
+      },
+      middleware: (gDM) =>
+        gDM({ thunk: { extraArgument: 'cakes' } }).concat(api.middleware),
+    })
+    const { getUser } = api.endpoints
+    const { data } = await store.dispatch(getUser.initiate())
+    expect(data).toBe('cakes')
+  })
+
+  test('only triggers transformResponse when a query method is actually used', async () => {
+    const baseQuery = (args?: any) => ({ data: args })
+    const transformResponse = vi.fn((response: any) => response)
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        hasQuery: build.query<string, string>({
+          query: (arg) => 'test',
+          transformResponse,
+        }),
+        hasQueryFn: build.query<string, void>(
+          // @ts-expect-error
+          {
+            queryFn: () => ({ data: 'test' }),
+            transformResponse,
+          },
+        ),
+      }),
+    })
+
+    const store = configureStore({
+      reducer: {
+        [api.reducerPath]: api.reducer,
+      },
+      middleware: (gDM) =>
+        gDM({ thunk: { extraArgument: 'cakes' } }).concat(api.middleware),
+    })
+
+    await store.dispatch(api.util.upsertQueryData('hasQuery', 'a', 'test'))
+    expect(transformResponse).not.toHaveBeenCalled()
+
+    transformResponse.mockReset()
+
+    await store.dispatch(api.endpoints.hasQuery.initiate('b'))
+    expect(transformResponse).toHaveBeenCalledTimes(1)
+
+    transformResponse.mockReset()
+
+    await store.dispatch(api.endpoints.hasQueryFn.initiate())
+    expect(transformResponse).not.toHaveBeenCalled()
+  })
+})
+
+describe('re-triggering behavior on arg change', () => {
+  const api = createApi({
+    baseQuery: () => ({ data: null }),
+    endpoints: (build) => ({
+      getUser: build.query<any, any>({
+        query: (obj) => obj,
+      }),
+    }),
+  })
+  const { getUser } = api.endpoints
+  const store = configureStore({
+    reducer: { [api.reducerPath]: api.reducer },
+    middleware: (gDM) => gDM().concat(api.middleware),
+  })
+
+  const spy = vi.spyOn(getUser, 'initiate')
+  beforeEach(() => void spy.mockClear())
+
+  test('re-trigger on literal value change', async () => {
+    const { result, rerender } = renderHook(
+      (props) => getUser.useQuery(props),
+      {
+        wrapper: withProvider(store),
+        initialProps: 5,
+      },
+    )
+
+    await waitFor(() => {
+      expect(result.current.status).not.toBe('pending')
+    })
+
+    expect(spy).toHaveBeenCalledOnce()
+
+    for (let x = 1; x < 3; x++) {
+      rerender(6)
+      await waitFor(() => {
+        expect(result.current.status).not.toBe('pending')
+      })
+      expect(spy).toHaveBeenCalledTimes(2)
+    }
+
+    for (let x = 1; x < 3; x++) {
+      rerender(7)
+      await waitFor(() => {
+        expect(result.current.status).not.toBe('pending')
+      })
+      expect(spy).toHaveBeenCalledTimes(3)
+    }
+  })
+
+  test('only re-trigger on shallow-equal arg change', async () => {
+    const { result, rerender } = renderHook(
+      (props) => getUser.useQuery(props),
+      {
+        wrapper: withProvider(store),
+        initialProps: { name: 'Bob', likes: 'iceCream' },
+      },
+    )
+
+    await waitFor(() => {
+      expect(result.current.status).not.toBe('pending')
+    })
+    expect(spy).toHaveBeenCalledOnce()
+
+    for (let x = 1; x < 3; x++) {
+      rerender({ name: 'Bob', likes: 'waffles' })
+      await waitFor(() => {
+        expect(result.current.status).not.toBe('pending')
+      })
+      expect(spy).toHaveBeenCalledTimes(2)
+    }
+
+    for (let x = 1; x < 3; x++) {
+      rerender({ name: 'Alice', likes: 'waffles' })
+      await waitFor(() => {
+        expect(result.current.status).not.toBe('pending')
+      })
+      expect(spy).toHaveBeenCalledTimes(3)
+    }
+  })
+
+  test('re-triggers every time on deeper value changes', async () => {
+    const name = 'Tim'
+
+    const { result, rerender } = renderHook(
+      (props) => getUser.useQuery(props),
+      {
+        wrapper: withProvider(store),
+        initialProps: { person: { name } },
+      },
+    )
+
+    await waitFor(() => {
+      expect(result.current.status).not.toBe('pending')
+    })
+    expect(spy).toHaveBeenCalledOnce()
+
+    for (let x = 1; x < 3; x++) {
+      rerender({ person: { name: name + x } })
+      await waitFor(() => {
+        expect(result.current.status).not.toBe('pending')
+      })
+      expect(spy).toHaveBeenCalledTimes(x + 1)
+    }
+  })
+
+  test('do not re-trigger if the order of keys change while maintaining the same values', async () => {
+    const { result, rerender } = renderHook(
+      (props) => getUser.useQuery(props),
+      {
+        wrapper: withProvider(store),
+        initialProps: { name: 'Tim', likes: 'Bananas' },
+      },
+    )
+
+    await waitFor(() => {
+      expect(result.current.status).not.toBe('pending')
+    })
+    expect(spy).toHaveBeenCalledOnce()
+
+    for (let x = 1; x < 3; x++) {
+      rerender({ likes: 'Bananas', name: 'Tim' })
+      await waitFor(() => {
+        expect(result.current.status).not.toBe('pending')
+      })
+      expect(spy).toHaveBeenCalledOnce()
+    }
+  })
+})
+
+describe('prefetch', () => {
+  const baseQuery = () => ({ data: { name: 'Test User' } })
+
+  const api = createApi({
+    baseQuery,
+    tagTypes: ['User'],
+    endpoints: (build) => ({
+      getUser: build.query<any, number>({
+        query: (id) => ({ url: `user/${id}` }),
+        providesTags: (result, error, id) => [{ type: 'User', id }],
+      }),
+      updateUser: build.mutation<any, { id: number; name: string }>({
+        query: ({ id, name }) => ({
+          url: `user/${id}`,
+          method: 'PUT',
+          body: { name },
+        }),
+        invalidatesTags: (result, error, { id }) => [{ type: 'User', id }],
+      }),
+    }),
+    keepUnusedDataFor: 0.1, // 100ms for faster test cleanup
+  })
+
+  let storeRef = setupApiStore(
+    api,
+    { ...actionsReducer },
+    {
+      withoutListeners: true,
+    },
+  )
+
+  let getSubscriptions: () => Map<string, any>
+  let getSubscriptionCount: (queryCacheKey: string) => number
+
+  beforeEach(() => {
+    storeRef = setupApiStore(
+      api,
+      { ...actionsReducer },
+      {
+        withoutListeners: true,
+      },
+    )
+    // Get subscription helpers
+    const subscriptionSelectors = storeRef.store.dispatch(
+      api.internalActions.internal_getRTKQSubscriptions(),
+    ) as any
+    getSubscriptions = subscriptionSelectors.getSubscriptions
+    getSubscriptionCount = subscriptionSelectors.getSubscriptionCount
+  })
+
+  describe('subscription behavior', () => {
+    it('prefetch should NOT create a subscription', async () => {
+      const queryCacheKey = 'getUser(1)'
+
+      // Initially no subscriptions
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+
+      // Dispatch prefetch
+      storeRef.store.dispatch(api.util.prefetch('getUser', 1, {}))
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+    })
+
+    it('prefetch allows cache cleanup after keepUnusedDataFor', async () => {
+      const queryCacheKey = 'getUser(1)'
+
+      // Prefetch the data
+      storeRef.store.dispatch(api.util.prefetch('getUser', 1, {}))
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+
+      // Verify data is in cache
+      let state = api.endpoints.getUser.select(1)(storeRef.store.getState())
+      expect(state.data).toEqual({ name: 'Test User' })
+
+      // Wait longer than keepUnusedDataFor
+      await new Promise((resolve) => setTimeout(resolve, 150))
+
+      state = api.endpoints.getUser.select(1)(storeRef.store.getState())
+      expect(state.status).toBe('uninitialized')
+      expect(state.data).toBeUndefined()
+    })
+
+    it('prefetch does NOT trigger refetch on tag invalidation', async () => {
+      // Prefetch user 1
+      storeRef.store.dispatch(api.util.prefetch('getUser', 1, {}))
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+
+      // Verify data is in cache
+      let state = api.endpoints.getUser.select(1)(storeRef.store.getState())
+      expect(state.data).toEqual({ name: 'Test User' })
+
+      // Invalidate the tag by updating the user
+      await storeRef.store.dispatch(
+        api.endpoints.updateUser.initiate({ id: 1, name: 'Updated' }),
+      )
+
+      // Since there's no subscription, the cache entry gets removed on invalidation
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+
+      // Cache entry should be cleared (no subscription to keep it alive)
+      state = api.endpoints.getUser.select(1)(storeRef.store.getState())
+      expect(state.status).toBe('uninitialized')
+      expect(state.data).toBeUndefined()
+    })
+
+    it('multiple prefetches do not accumulate subscriptions', async () => {
+      const queryCacheKey = 'getUser(1)'
+
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+
+      // First prefetch
+      storeRef.store.dispatch(api.util.prefetch('getUser', 1, {}))
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+
+      // Second prefetch (force refetch)
+      storeRef.store.dispatch(api.util.prefetch('getUser', 1, { force: true }))
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+
+      // Still no subscriptions
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+
+      // Third prefetch
+      storeRef.store.dispatch(api.util.prefetch('getUser', 1, { force: true }))
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+    })
+
+    it('prefetch followed by regular query should work correctly', async () => {
+      const queryCacheKey = 'getUser(1)'
+
+      // Prefetch first
+      storeRef.store.dispatch(api.util.prefetch('getUser', 1, {}))
+      await Promise.all(
+        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),
+      )
+
+      // No subscription from prefetch
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+
+      // Now create a real subscription via initiate
+      const promise = storeRef.store.dispatch(api.endpoints.getUser.initiate(1))
+
+      // Should have 1 subscription from the initiate call
+      expect(getSubscriptionCount(queryCacheKey)).toBe(1)
+
+      // Unsubscribe
+      promise.unsubscribe()
+
+      // Subscription should be cleaned up
+      expect(getSubscriptionCount(queryCacheKey)).toBe(0)
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/cacheCollection.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/cacheCollection.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/cacheCollection.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,231 @@
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+import { configureStore } from '@reduxjs/toolkit'
+import { vi } from 'vitest'
+import type { Middleware, Reducer } from 'redux'
+import {
+  THIRTY_TWO_BIT_MAX_INT,
+  THIRTY_TWO_BIT_MAX_TIMER_SECONDS,
+} from '../core/buildMiddleware/cacheCollection'
+import { countObjectKeys } from '../utils/countObjectKeys'
+
+beforeAll(() => {
+  vi.useFakeTimers()
+})
+
+const onCleanup = vi.fn()
+
+beforeEach(() => {
+  onCleanup.mockClear()
+})
+
+test(`query: await cleanup, defaults`, async () => {
+  const { store, api } = storeForApi(
+    createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+      endpoints: (build) => ({
+        query: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+    }),
+  )
+
+  const promise = store.dispatch(api.endpoints.query.initiate('arg'))
+  await promise
+  promise.unsubscribe()
+  vi.advanceTimersByTime(59000)
+  expect(onCleanup).not.toHaveBeenCalled()
+  vi.advanceTimersByTime(2000)
+  expect(onCleanup).toHaveBeenCalled()
+})
+
+test(`query: await cleanup, keepUnusedDataFor set`, async () => {
+  const { store, api } = storeForApi(
+    createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+      endpoints: (build) => ({
+        query: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+      keepUnusedDataFor: 29,
+    }),
+  )
+
+  const promise = store.dispatch(api.endpoints.query.initiate('arg'))
+  await promise
+  promise.unsubscribe()
+  vi.advanceTimersByTime(28000)
+  expect(onCleanup).not.toHaveBeenCalled()
+  vi.advanceTimersByTime(2000)
+  expect(onCleanup).toHaveBeenCalled()
+})
+
+test(`query: handles large keepUnuseDataFor values over 32-bit ms`, async () => {
+  const { store, api } = storeForApi(
+    createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+      endpoints: (build) => ({
+        query: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+      keepUnusedDataFor: THIRTY_TWO_BIT_MAX_TIMER_SECONDS - 10,
+    }),
+  )
+
+  const promise = store.dispatch(api.endpoints.query.initiate('arg'))
+  await promise
+  promise.unsubscribe()
+
+  // Shouldn't have been called right away
+  vi.advanceTimersByTime(1000)
+  expect(onCleanup).not.toHaveBeenCalled()
+
+  // Shouldn't have been called any time in the next few minutes
+  vi.advanceTimersByTime(1_000_000)
+  expect(onCleanup).not.toHaveBeenCalled()
+
+  // _Should_ be called _wayyyy_ in the future (like 24.8 days from now)
+  vi.advanceTimersByTime(THIRTY_TWO_BIT_MAX_TIMER_SECONDS * 1000),
+    expect(onCleanup).toHaveBeenCalled()
+})
+
+describe(`query: await cleanup, keepUnusedDataFor set`, () => {
+  const { store, api } = storeForApi(
+    createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+      endpoints: (build) => ({
+        query: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+        query2: build.query<unknown, string>({
+          query: () => '/success',
+          keepUnusedDataFor: 35,
+        }),
+        query3: build.query<unknown, string>({
+          query: () => '/success',
+          keepUnusedDataFor: 0,
+        }),
+        query4: build.query<unknown, string>({
+          query: () => '/success',
+          keepUnusedDataFor: Infinity,
+        }),
+      }),
+      keepUnusedDataFor: 29,
+    }),
+  )
+
+  test('global keepUnusedDataFor', async () => {
+    const promise = store.dispatch(api.endpoints.query.initiate('arg'))
+    await promise
+    promise.unsubscribe()
+    vi.advanceTimersByTime(28000)
+    expect(onCleanup).not.toHaveBeenCalled()
+    vi.advanceTimersByTime(2000)
+    expect(onCleanup).toHaveBeenCalled()
+  })
+
+  test('endpoint keepUnusedDataFor', async () => {
+    const promise = store.dispatch(api.endpoints.query2.initiate('arg'))
+    await promise
+    promise.unsubscribe()
+
+    vi.advanceTimersByTime(34000)
+    expect(onCleanup).not.toHaveBeenCalled()
+    vi.advanceTimersByTime(2000)
+    expect(onCleanup).toHaveBeenCalled()
+  })
+
+  test('endpoint keepUnusedDataFor: 0 ', async () => {
+    expect(onCleanup).not.toHaveBeenCalled()
+    const promise = store.dispatch(api.endpoints.query3.initiate('arg'))
+    await promise
+    promise.unsubscribe()
+    expect(onCleanup).not.toHaveBeenCalled()
+    vi.advanceTimersByTime(1)
+    expect(onCleanup).toHaveBeenCalled()
+  })
+
+  test('endpoint keepUnusedDataFor: Infinity', async () => {
+    expect(onCleanup).not.toHaveBeenCalled()
+    store.dispatch(api.endpoints.query4.initiate('arg')).unsubscribe()
+    expect(onCleanup).not.toHaveBeenCalled()
+    vi.advanceTimersByTime(THIRTY_TWO_BIT_MAX_INT)
+    expect(onCleanup).not.toHaveBeenCalled()
+  })
+})
+
+describe('resetApiState cleanup', () => {
+  test('resetApiState aborts multiple running queries and mutations', async () => {
+    const { store, api } = storeForApi(
+      createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        endpoints: (build) => ({
+          query1: build.query<unknown, string>({
+            query: () => '/success',
+          }),
+          query2: build.query<unknown, string>({
+            query: () => '/success',
+          }),
+          mutation: build.mutation<unknown, string>({
+            query: () => ({
+              url: '/success',
+              method: 'POST',
+            }),
+          }),
+        }),
+      }),
+    )
+
+    // Start multiple queries and a mutation
+    const queryPromise1 = store.dispatch(api.endpoints.query1.initiate('arg1'))
+    const queryPromise2 = store.dispatch(api.endpoints.query2.initiate('arg2'))
+    const mutationPromise = store.dispatch(
+      api.endpoints.mutation.initiate('arg'),
+    )
+
+    // Spy on abort methods
+    queryPromise1.abort = vi.fn(queryPromise1.abort)
+    queryPromise2.abort = vi.fn(queryPromise2.abort)
+    mutationPromise.abort = vi.fn(mutationPromise.abort)
+
+    // Dispatch resetApiState
+    store.dispatch(api.util.resetApiState())
+
+    // Verify all aborts were called
+    expect(queryPromise1.abort).toHaveBeenCalled()
+    expect(queryPromise2.abort).toHaveBeenCalled()
+    expect(mutationPromise.abort).toHaveBeenCalled()
+  })
+})
+
+function storeForApi<
+  A extends {
+    reducerPath: 'api'
+    reducer: Reducer<any, any>
+    middleware: Middleware
+    util: { resetApiState(): any }
+  },
+>(api: A) {
+  const store = configureStore({
+    reducer: { api: api.reducer },
+    middleware: (gdm) =>
+      gdm({ serializableCheck: false, immutableCheck: false }).concat(
+        api.middleware,
+      ),
+    enhancers: (gde) =>
+      gde({
+        autoBatch: false,
+      }),
+  })
+  let hadQueries = false
+  store.subscribe(() => {
+    const queryState = store.getState().api.queries
+    if (hadQueries && countObjectKeys(queryState) === 0) {
+      onCleanup()
+    }
+    hadQueries = hadQueries || countObjectKeys(queryState) > 0
+  })
+  return { api, store }
+}
Index: node_modules/@reduxjs/toolkit/src/query/tests/cacheLifecycle.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/cacheLifecycle.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/cacheLifecycle.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,31 @@
+import type { FetchBaseQueryMeta } from '@reduxjs/toolkit/query'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+
+const api = createApi({
+  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+  endpoints: () => ({}),
+})
+
+describe('type tests', () => {
+  test(`mutation: await cacheDataLoaded, await cacheEntryRemoved (success)`, () => {
+    const extended = api.injectEndpoints({
+      overrideExisting: true,
+      endpoints: (build) => ({
+        injected: build.mutation<number, string>({
+          query: () => '/success',
+          async onCacheEntryAdded(
+            arg,
+            { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },
+          ) {
+            const firstValue = await cacheDataLoaded
+
+            expectTypeOf(firstValue).toMatchTypeOf<{
+              data: number
+              meta?: FetchBaseQueryMeta
+            }>()
+          },
+        }),
+      }),
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/cacheLifecycle.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/cacheLifecycle.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/cacheLifecycle.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,708 @@
+import {
+  DEFAULT_DELAY_MS,
+  fakeTimerWaitFor,
+  setupApiStore,
+} from '@internal/tests/utils/helpers'
+import type { QueryActionCreatorResult } from '@reduxjs/toolkit/query'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+
+beforeAll(() => {
+  vi.useFakeTimers()
+})
+
+const api = createApi({
+  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+  endpoints: () => ({}),
+})
+const storeRef = setupApiStore(api)
+
+const onNewCacheEntry = vi.fn()
+const gotFirstValue = vi.fn()
+const onCleanup = vi.fn()
+const onCatch = vi.fn()
+
+beforeEach(() => {
+  onNewCacheEntry.mockClear()
+  gotFirstValue.mockClear()
+  onCleanup.mockClear()
+  onCatch.mockClear()
+})
+
+describe.each([['query'], ['mutation']] as const)(
+  'generic cases: %s',
+  (type) => {
+    test(`${type}: new cache entry only`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/success',
+            onCacheEntryAdded(arg, { dispatch, getState }) {
+              onNewCacheEntry(arg)
+            },
+          }),
+        }),
+      })
+      storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))
+      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')
+    })
+
+    test(`${type}: await cacheEntryRemoved`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          // Lying to TS here
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/success',
+            async onCacheEntryAdded(
+              arg,
+              { dispatch, getState, cacheEntryRemoved },
+            ) {
+              onNewCacheEntry(arg)
+              await cacheEntryRemoved
+              onCleanup()
+            },
+          }),
+        }),
+      })
+      const promise = storeRef.store.dispatch(
+        extended.endpoints.injected.initiate('arg'),
+      )
+
+      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')
+      expect(onCleanup).not.toHaveBeenCalled()
+
+      await promise
+      if (type === 'mutation') {
+        promise.reset()
+      } else {
+        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()
+      }
+      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)
+      if (type === 'query') {
+        await vi.advanceTimersByTimeAsync(59000)
+        expect(onCleanup).not.toHaveBeenCalled()
+        await vi.advanceTimersByTimeAsync(2000)
+      }
+
+      expect(onCleanup).toHaveBeenCalled()
+    })
+
+    test(`${type}: await cacheDataLoaded, await cacheEntryRemoved (success)`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<number, string>({
+            query: () => '/success',
+            async onCacheEntryAdded(
+              arg,
+              { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },
+            ) {
+              onNewCacheEntry(arg)
+              const firstValue = await cacheDataLoaded
+              gotFirstValue(firstValue)
+              await cacheEntryRemoved
+              onCleanup()
+            },
+          }),
+        }),
+      })
+      const promise = storeRef.store.dispatch(
+        extended.endpoints.injected.initiate('arg'),
+      )
+
+      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')
+
+      expect(gotFirstValue).not.toHaveBeenCalled()
+      expect(onCleanup).not.toHaveBeenCalled()
+
+      await fakeTimerWaitFor(() => {
+        expect(gotFirstValue).toHaveBeenCalled()
+      })
+      expect(gotFirstValue).toHaveBeenCalledWith({
+        data: { value: 'success' },
+        meta: {
+          request: expect.any(Request),
+          response: expect.any(Object), // Response is not available in jest env
+        },
+      })
+      expect(onCleanup).not.toHaveBeenCalled()
+
+      if (type === 'mutation') {
+        promise.reset()
+      } else {
+        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()
+      }
+      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)
+      if (type === 'query') {
+        await vi.advanceTimersByTimeAsync(59000)
+        expect(onCleanup).not.toHaveBeenCalled()
+        await vi.advanceTimersByTimeAsync(2000)
+      }
+
+      expect(onCleanup).toHaveBeenCalled()
+    })
+
+    test(`${type}: await cacheDataLoaded, await cacheEntryRemoved (cacheDataLoaded never resolves)`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/error', // we will initiate only once and that one time will be an error -> cacheDataLoaded will never resolve
+            async onCacheEntryAdded(
+              arg,
+              { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },
+            ) {
+              onNewCacheEntry(arg)
+              // this will wait until cacheEntryRemoved, then reject => nothing past that line will execute
+              // but since this special "cacheEntryRemoved" rejection is handled outside, there will be no
+              // uncaught rejection error
+              const firstValue = await cacheDataLoaded
+              gotFirstValue(firstValue)
+              await cacheEntryRemoved
+              onCleanup()
+            },
+          }),
+        }),
+      })
+      const promise = storeRef.store.dispatch(
+        extended.endpoints.injected.initiate('arg'),
+      )
+      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')
+
+      if (type === 'mutation') {
+        promise.reset()
+      } else {
+        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()
+      }
+      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)
+      if (type === 'query') {
+        await vi.advanceTimersByTimeAsync(120000)
+      }
+      expect(gotFirstValue).not.toHaveBeenCalled()
+      expect(onCleanup).not.toHaveBeenCalled()
+    })
+
+    test(`${type}: try { await cacheDataLoaded }, await cacheEntryRemoved (cacheDataLoaded never resolves)`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/error', // we will initiate only once and that one time will be an error -> cacheDataLoaded will never resolve
+            async onCacheEntryAdded(
+              arg,
+              { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },
+            ) {
+              onNewCacheEntry(arg)
+
+              try {
+                // this will wait until cacheEntryRemoved, then reject => nothing else in this try..catch block will execute
+                const firstValue = await cacheDataLoaded
+                gotFirstValue(firstValue)
+              } catch (e) {
+                onCatch(e)
+              }
+              await cacheEntryRemoved
+              onCleanup()
+            },
+          }),
+        }),
+      })
+      const promise = storeRef.store.dispatch(
+        extended.endpoints.injected.initiate('arg'),
+      )
+
+      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')
+      await promise
+      if (type === 'mutation') {
+        promise.reset()
+      } else {
+        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()
+      }
+      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)
+
+      if (type === 'query') {
+        await vi.advanceTimersByTimeAsync(59000)
+        expect(onCleanup).not.toHaveBeenCalled()
+        await vi.advanceTimersByTimeAsync(2000)
+      }
+
+      expect(onCleanup).toHaveBeenCalled()
+      expect(gotFirstValue).not.toHaveBeenCalled()
+      expect(onCatch.mock.calls[0][0]).toMatchObject({
+        message: 'Promise never resolved before cacheEntryRemoved.',
+      })
+    })
+
+    test(`${type}: try { await cacheDataLoaded, await cacheEntryRemoved } (cacheDataLoaded never resolves)`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/error', // we will initiate only once and that one time will be an error -> cacheDataLoaded will never resolve
+            async onCacheEntryAdded(
+              arg,
+              { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },
+            ) {
+              onNewCacheEntry(arg)
+
+              try {
+                // this will wait until cacheEntryRemoved, then reject => nothing else in this try..catch block will execute
+                const firstValue = await cacheDataLoaded
+                gotFirstValue(firstValue)
+                // cleanup in this scenario only needs to be done for stuff within this try..catch block - totally valid scenario
+                await cacheEntryRemoved
+                onCleanup()
+              } catch (e) {
+                onCatch(e)
+              }
+            },
+          }),
+        }),
+      })
+      const promise = storeRef.store.dispatch(
+        extended.endpoints.injected.initiate('arg'),
+      )
+
+      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')
+      await promise
+
+      if (type === 'mutation') {
+        promise.reset()
+      } else {
+        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()
+      }
+      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)
+      if (type === 'query') {
+        await vi.advanceTimersByTimeAsync(59000)
+        expect(onCleanup).not.toHaveBeenCalled()
+        await vi.advanceTimersByTimeAsync(2000)
+      }
+      expect(onCleanup).not.toHaveBeenCalled()
+      expect(gotFirstValue).not.toHaveBeenCalled()
+      expect(onCatch.mock.calls[0][0]).toMatchObject({
+        message: 'Promise never resolved before cacheEntryRemoved.',
+      })
+    })
+
+    test(`${type}: try { await cacheDataLoaded } finally { await cacheEntryRemoved } (cacheDataLoaded never resolves)`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/error', // we will initiate only once and that one time will be an error -> cacheDataLoaded will never resolve
+            async onCacheEntryAdded(
+              arg,
+              { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },
+            ) {
+              onNewCacheEntry(arg)
+
+              try {
+                // this will wait until cacheEntryRemoved, then reject => nothing else in this try..catch block will execute
+                const firstValue = await cacheDataLoaded
+                gotFirstValue(firstValue)
+              } catch (e) {
+                onCatch(e)
+              } finally {
+                await cacheEntryRemoved
+                onCleanup()
+              }
+            },
+          }),
+        }),
+      })
+      const promise = storeRef.store.dispatch(
+        extended.endpoints.injected.initiate('arg'),
+      )
+
+      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')
+
+      await promise
+      if (type === 'mutation') {
+        promise.reset()
+      } else {
+        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()
+      }
+      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)
+      if (type === 'query') {
+        await vi.advanceTimersByTimeAsync(59000)
+        expect(onCleanup).not.toHaveBeenCalled()
+        await vi.advanceTimersByTimeAsync(2000)
+      }
+      expect(onCleanup).toHaveBeenCalled()
+      expect(gotFirstValue).not.toHaveBeenCalled()
+      expect(onCatch.mock.calls[0][0]).toMatchObject({
+        message: 'Promise never resolved before cacheEntryRemoved.',
+      })
+    })
+  },
+)
+
+test(`query: getCacheEntry`, async () => {
+  const snapshot = vi.fn()
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<unknown, string>({
+        query: () => '/success',
+        async onCacheEntryAdded(
+          arg,
+          {
+            dispatch,
+            getState,
+            getCacheEntry,
+            cacheEntryRemoved,
+            cacheDataLoaded,
+          },
+        ) {
+          snapshot(getCacheEntry())
+          gotFirstValue(await cacheDataLoaded)
+          snapshot(getCacheEntry())
+          await cacheEntryRemoved
+          snapshot(getCacheEntry())
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+  await promise
+  promise.unsubscribe()
+
+  await fakeTimerWaitFor(() => {
+    expect(gotFirstValue).toHaveBeenCalled()
+  })
+
+  await vi.advanceTimersByTimeAsync(120000)
+
+  expect(snapshot).toHaveBeenCalledTimes(3)
+  expect(snapshot.mock.calls[0][0]).toMatchObject({
+    endpointName: 'injected',
+    isError: false,
+    isLoading: true,
+    isSuccess: false,
+    isUninitialized: false,
+    originalArgs: 'arg',
+    requestId: promise.requestId,
+    startedTimeStamp: expect.any(Number),
+    status: 'pending',
+  })
+  expect(snapshot.mock.calls[1][0]).toMatchObject({
+    data: {
+      value: 'success',
+    },
+    endpointName: 'injected',
+    fulfilledTimeStamp: expect.any(Number),
+    isError: false,
+    isLoading: false,
+    isSuccess: true,
+    isUninitialized: false,
+    originalArgs: 'arg',
+    requestId: promise.requestId,
+    startedTimeStamp: expect.any(Number),
+    status: 'fulfilled',
+  })
+  expect(snapshot.mock.calls[2][0]).toMatchObject({
+    isError: false,
+    isLoading: false,
+    isSuccess: false,
+    isUninitialized: true,
+    status: 'uninitialized',
+  })
+})
+
+test(`mutation: getCacheEntry`, async () => {
+  const snapshot = vi.fn()
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.mutation<unknown, string>({
+        query: () => '/success',
+        async onCacheEntryAdded(
+          arg,
+          {
+            dispatch,
+            getState,
+            getCacheEntry,
+            cacheEntryRemoved,
+            cacheDataLoaded,
+          },
+        ) {
+          snapshot(getCacheEntry())
+          gotFirstValue(await cacheDataLoaded)
+          snapshot(getCacheEntry())
+          await cacheEntryRemoved
+          snapshot(getCacheEntry())
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+  await fakeTimerWaitFor(() => {
+    expect(gotFirstValue).toHaveBeenCalled()
+  })
+
+  promise.reset()
+  await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)
+
+  expect(snapshot).toHaveBeenCalledTimes(3)
+  expect(snapshot.mock.calls[0][0]).toMatchObject({
+    endpointName: 'injected',
+    isError: false,
+    isLoading: true,
+    isSuccess: false,
+    isUninitialized: false,
+    startedTimeStamp: expect.any(Number),
+    status: 'pending',
+  })
+  expect(snapshot.mock.calls[1][0]).toMatchObject({
+    data: {
+      value: 'success',
+    },
+    endpointName: 'injected',
+    fulfilledTimeStamp: expect.any(Number),
+    isError: false,
+    isLoading: false,
+    isSuccess: true,
+    isUninitialized: false,
+    startedTimeStamp: expect.any(Number),
+    status: 'fulfilled',
+  })
+  expect(snapshot.mock.calls[2][0]).toMatchObject({
+    isError: false,
+    isLoading: false,
+    isSuccess: false,
+    isUninitialized: true,
+    status: 'uninitialized',
+  })
+})
+
+test('query: updateCachedData', async () => {
+  const trackCalls = vi.fn()
+
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<{ value: string }, string>({
+        query: () => '/success',
+        async onCacheEntryAdded(
+          arg,
+          {
+            dispatch,
+            getState,
+            getCacheEntry,
+            updateCachedData,
+            cacheEntryRemoved,
+            cacheDataLoaded,
+          },
+        ) {
+          expect(getCacheEntry().data).toEqual(undefined)
+          // calling `updateCachedData` when there is no data yet should not do anything
+          updateCachedData((draft) => {
+            draft.value = 'TEST'
+            trackCalls()
+          })
+          expect(trackCalls).not.toHaveBeenCalled()
+          expect(getCacheEntry().data).toEqual(undefined)
+
+          gotFirstValue(await cacheDataLoaded)
+
+          expect(getCacheEntry().data).toEqual({ value: 'success' })
+          updateCachedData((draft) => {
+            draft.value = 'TEST'
+            trackCalls()
+          })
+          expect(trackCalls).toHaveBeenCalledOnce()
+          expect(getCacheEntry().data).toEqual({ value: 'TEST' })
+
+          await cacheEntryRemoved
+
+          expect(getCacheEntry().data).toEqual(undefined)
+          // calling `updateCachedData` when there is no data any more should not do anything
+          updateCachedData((draft) => {
+            draft.value = 'TEST2'
+            trackCalls()
+          })
+          expect(trackCalls).toHaveBeenCalledOnce()
+          expect(getCacheEntry().data).toEqual(undefined)
+
+          onCleanup()
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+  await promise
+  promise.unsubscribe()
+
+  await fakeTimerWaitFor(() => {
+    expect(gotFirstValue).toHaveBeenCalled()
+  })
+
+  await vi.advanceTimersByTimeAsync(61000)
+
+  await fakeTimerWaitFor(() => {
+    expect(onCleanup).toHaveBeenCalled()
+  })
+})
+
+test('updateCachedData - infinite query', async () => {
+  const trackCalls = vi.fn()
+
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      infiniteInjected: build.infiniteQuery<{ value: string }, string, number>({
+        query: () => '/success',
+        infiniteQueryOptions: {
+          initialPageParam: 1,
+          getNextPageParam: (
+            lastPage,
+            allPages,
+            lastPageParam,
+            allPageParams,
+          ) => lastPageParam + 1,
+        },
+        async onCacheEntryAdded(
+          arg,
+          {
+            dispatch,
+            getState,
+            getCacheEntry,
+            updateCachedData,
+            cacheEntryRemoved,
+            cacheDataLoaded,
+          },
+        ) {
+          expect(getCacheEntry().data).toEqual(undefined)
+          // calling `updateCachedData` when there is no data yet should not do anything
+          updateCachedData((draft) => {
+            draft.pages = [{ value: 'TEST' }]
+            draft.pageParams = [1]
+            trackCalls()
+          })
+          expect(trackCalls).not.toHaveBeenCalled()
+          expect(getCacheEntry().data).toEqual(undefined)
+
+          gotFirstValue(await cacheDataLoaded)
+
+          expect(getCacheEntry().data).toEqual({
+            pages: [{ value: 'success' }],
+            pageParams: [1],
+          })
+          updateCachedData((draft) => {
+            draft.pages = [{ value: 'TEST' }]
+            draft.pageParams = [1]
+            trackCalls()
+          })
+          expect(trackCalls).toHaveBeenCalledOnce()
+          expect(getCacheEntry().data).toEqual({
+            pages: [{ value: 'TEST' }],
+            pageParams: [1],
+          })
+
+          await cacheEntryRemoved
+
+          expect(getCacheEntry().data).toEqual(undefined)
+          // calling `updateCachedData` when there is no data any more should not do anything
+          updateCachedData((draft) => {
+            draft.pages = [{ value: 'TEST' }, { value: 'TEST2' }]
+            draft.pageParams = [1, 2]
+            trackCalls()
+          })
+          expect(trackCalls).toHaveBeenCalledOnce()
+          expect(getCacheEntry().data).toEqual(undefined)
+
+          onCleanup()
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.infiniteInjected.initiate('arg'),
+  )
+  await promise
+  promise.unsubscribe()
+
+  await fakeTimerWaitFor(() => {
+    expect(gotFirstValue).toHaveBeenCalled()
+  })
+
+  await vi.advanceTimersByTimeAsync(61000)
+
+  await fakeTimerWaitFor(() => {
+    expect(onCleanup).toHaveBeenCalled()
+  })
+})
+
+test('dispatching further actions does not trigger another lifecycle', async () => {
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<unknown, void>({
+        query: () => '/success',
+        async onCacheEntryAdded() {
+          onNewCacheEntry()
+        },
+      }),
+    }),
+  })
+  await storeRef.store.dispatch(extended.endpoints.injected.initiate())
+  expect(onNewCacheEntry).toHaveBeenCalledOnce()
+
+  await storeRef.store.dispatch(extended.endpoints.injected.initiate())
+  expect(onNewCacheEntry).toHaveBeenCalledOnce()
+
+  await storeRef.store.dispatch(
+    extended.endpoints.injected.initiate(undefined, { forceRefetch: true }),
+  )
+  expect(onNewCacheEntry).toHaveBeenCalledOnce()
+})
+
+test('dispatching a query initializer with `subscribe: false` does also start a lifecycle', async () => {
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<unknown, void>({
+        query: () => '/success',
+        async onCacheEntryAdded() {
+          onNewCacheEntry()
+        },
+      }),
+    }),
+  })
+  await storeRef.store.dispatch(
+    extended.endpoints.injected.initiate(undefined, { subscribe: false }),
+  )
+  expect(onNewCacheEntry).toHaveBeenCalledOnce()
+
+  // will not be called a second time though
+  await storeRef.store.dispatch(extended.endpoints.injected.initiate(undefined))
+  expect(onNewCacheEntry).toHaveBeenCalledOnce()
+})
+
+test('dispatching a mutation initializer with `track: false` does not start a lifecycle', async () => {
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.mutation<unknown, void>({
+        query: () => '/success',
+        async onCacheEntryAdded() {
+          onNewCacheEntry()
+        },
+      }),
+    }),
+  })
+  await storeRef.store.dispatch(
+    extended.endpoints.injected.initiate(undefined, { track: false }),
+  )
+  expect(onNewCacheEntry).not.toHaveBeenCalled()
+
+  await storeRef.store.dispatch(extended.endpoints.injected.initiate(undefined))
+  expect(onNewCacheEntry).toHaveBeenCalledOnce()
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/cleanup.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/cleanup.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/cleanup.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,200 @@
+// tests for "cleanup-after-unsubscribe" behavior
+import React from 'react'
+
+import { createListenerMiddleware } from '@reduxjs/toolkit'
+import { createApi, QueryStatus } from '@reduxjs/toolkit/query/react'
+import { act, render, screen, waitFor } from '@testing-library/react'
+import { setupApiStore } from '../../tests/utils/helpers'
+import type { SubscriptionSelectors } from '../core/buildMiddleware/types'
+
+const api = createApi({
+  baseQuery: () => ({ data: 42 }),
+  endpoints: (build) => ({
+    a: build.query<unknown, void>({ query: () => '' }),
+    b: build.query<unknown, void>({ query: () => '' }),
+  }),
+})
+const storeRef = setupApiStore(api)
+
+const getSubStateA = () => storeRef.store.getState().api.queries['a(undefined)']
+const getSubStateB = () => storeRef.store.getState().api.queries['b(undefined)']
+
+function UsingA() {
+  const { data } = api.endpoints.a.useQuery()
+
+  return <>Result: {data as React.ReactNode} </>
+}
+
+function UsingB() {
+  api.endpoints.b.useQuery()
+
+  return <></>
+}
+
+function UsingAB() {
+  api.endpoints.a.useQuery()
+  api.endpoints.b.useQuery()
+
+  return <></>
+}
+
+beforeAll(() => {
+  vi.useFakeTimers({ shouldAdvanceTime: true })
+})
+
+test('data stays in store when component stays rendered', async () => {
+  expect(getSubStateA()).toBeUndefined()
+
+  render(<UsingA />, { wrapper: storeRef.wrapper })
+  await waitFor(() =>
+    expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled),
+  )
+
+  vi.advanceTimersByTime(120_000)
+
+  expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled)
+})
+
+test('data is removed from store after 60 seconds', async () => {
+  expect(getSubStateA()).toBeUndefined()
+
+  const { unmount } = render(<UsingA />, { wrapper: storeRef.wrapper })
+  await waitFor(() =>
+    expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled),
+  )
+
+  unmount()
+
+  vi.advanceTimersByTime(59_000)
+
+  expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled)
+
+  vi.advanceTimersByTime(2000)
+
+  expect(getSubStateA()).toBeUndefined()
+})
+
+test('data stays in store when component stays rendered while data for another component is removed after it unmounted', async () => {
+  expect(getSubStateA()).toBeUndefined()
+  expect(getSubStateB()).toBeUndefined()
+
+  const { rerender } = render(
+    <>
+      <UsingA />
+      <UsingB />
+    </>,
+    { wrapper: storeRef.wrapper },
+  )
+  await waitFor(() => {
+    expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled)
+    expect(getSubStateB()?.status).toBe(QueryStatus.fulfilled)
+  })
+
+  const statusA = getSubStateA()
+
+  await act(async () => {
+    rerender(<UsingA />)
+
+    vi.advanceTimersByTime(10)
+  })
+
+  vi.advanceTimersByTime(120_000)
+
+  expect(getSubStateA()).toEqual(statusA)
+  expect(getSubStateB()).toBeUndefined()
+})
+
+test('data stays in store when one component requiring the data stays in the store', async () => {
+  expect(getSubStateA()).toBeUndefined()
+  expect(getSubStateB()).toBeUndefined()
+
+  const { rerender } = render(
+    <>
+      <UsingA key="a" />
+      <UsingAB key="ab" />
+    </>,
+    { wrapper: storeRef.wrapper },
+  )
+  await waitFor(() => {
+    expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled)
+    expect(getSubStateB()?.status).toBe(QueryStatus.fulfilled)
+  })
+
+  const statusA = getSubStateA()
+  const statusB = getSubStateB()
+
+  await act(async () => {
+    rerender(<UsingAB key="ab" />)
+    vi.advanceTimersByTime(10)
+    vi.runAllTimers()
+  })
+
+  await act(async () => {
+    vi.advanceTimersByTime(120000)
+    vi.runAllTimers()
+  })
+
+  expect(getSubStateA()).toEqual(statusA)
+  expect(getSubStateB()).toEqual(statusB)
+})
+
+test('Minimizes the number of subscription dispatches when multiple components ask for the same data', async () => {
+  const listenerMiddleware = createListenerMiddleware()
+  const storeRef = setupApiStore(api, undefined, {
+    middleware: {
+      concat: [listenerMiddleware.middleware],
+    },
+    withoutTestLifecycles: true,
+  })
+
+  const actionTypes: unknown[] = []
+
+  listenerMiddleware.startListening({
+    predicate: () => true,
+    effect: (action) => {
+      if (
+        action.type.includes('subscriptionsUpdated') ||
+        action.type.includes('internal_')
+      ) {
+        return
+      }
+
+      actionTypes.push(action.type)
+    },
+  })
+
+  const { getSubscriptionCount } = storeRef.store.dispatch(
+    api.internalActions.internal_getRTKQSubscriptions(),
+  ) as unknown as SubscriptionSelectors
+
+  const NUM_LIST_ITEMS = 1000
+
+  function ParentComponent() {
+    const listItems = Array.from({ length: NUM_LIST_ITEMS }).map((_, i) => (
+      <UsingA key={i} />
+    ))
+
+    return <>{listItems}</>
+  }
+
+  render(<ParentComponent />, {
+    wrapper: storeRef.wrapper,
+  })
+
+  await act(async () => {
+    vi.advanceTimersByTime(10)
+    vi.runAllTimers()
+  })
+
+  await waitFor(() => {
+    return screen.getAllByText(/42/).length > 0
+  })
+
+  expect(getSubscriptionCount('a(undefined)')).toBe(NUM_LIST_ITEMS)
+
+  expect(actionTypes).toEqual([
+    'api/config/middlewareRegistered',
+    'api/executeQuery/pending',
+    'api/executeQuery/fulfilled',
+  ])
+}, 25_000)
Index: node_modules/@reduxjs/toolkit/src/query/tests/copyWithStructuralSharing.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/copyWithStructuralSharing.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/copyWithStructuralSharing.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,88 @@
+import { copyWithStructuralSharing } from '@reduxjs/toolkit/query'
+
+test('equal object from JSON Object', () => {
+  const json = JSON.stringify({
+    a: { b: { c: { d: 1, e: '2', f: true }, g: false }, h: null },
+    i: null,
+  })
+  const objA = JSON.parse(json)
+  const objB = JSON.parse(json)
+  expect(objA).toStrictEqual(objB)
+  expect(objA).not.toBe(objB)
+  const newCopy = copyWithStructuralSharing(objA, objB)
+  expect(newCopy).toBe(objA)
+  expect(newCopy).not.toBe(objB)
+  expect(newCopy).toStrictEqual(objB)
+})
+
+test('equal object from JSON Object', () => {
+  const json = JSON.stringify({
+    a: { b: { c: { d: 1, e: '2', f: true }, g: false }, h: null },
+    i: null,
+  })
+  const objA = JSON.parse(json)
+  const objB = JSON.parse(json)
+  objB.a.h = 4
+  expect(objA).not.toStrictEqual(objB)
+  expect(objA).not.toBe(objB)
+  expect(objA.a.b).toStrictEqual(objB.a.b)
+  expect(objA.a.b).not.toBe(objB.a.b)
+
+  const newCopy = copyWithStructuralSharing(objA, objB)
+  expect(newCopy).not.toBe(objA)
+  expect(newCopy).not.toStrictEqual(objA)
+  expect(newCopy).toStrictEqual(objB)
+
+  expect(newCopy.a.b).toBe(objA.a.b)
+  expect(newCopy.a.b).not.toBe(objB.a.b)
+  expect(newCopy.a.b).toStrictEqual(objB.a.b)
+})
+
+test('equal object from JSON Array', () => {
+  const json = JSON.stringify([
+    1,
+    'a',
+    { 2: 'b' },
+    { 3: { 4: 'c' }, d: null },
+    null,
+    5,
+  ])
+  const objA = JSON.parse(json)
+  const objB = JSON.parse(json)
+
+  expect(objA).toStrictEqual(objB)
+  expect(objA).not.toBe(objB)
+  const newCopy = copyWithStructuralSharing(objA, objB)
+  expect(newCopy).toBe(objA)
+  expect(newCopy).not.toBe(objB)
+  expect(newCopy).toStrictEqual(objB)
+})
+
+test('equal object from JSON Array', () => {
+  const json = JSON.stringify([
+    1,
+    'a',
+    { 2: 'b' },
+    { 3: { 4: 'c' }, d: null },
+    null,
+    5,
+  ])
+  const objA = JSON.parse(json)
+  const objB = JSON.parse(json)
+  objB[2][2] = 'x'
+
+  expect(objA).not.toStrictEqual(objB)
+  expect(objA).not.toBe(objB)
+  const newCopy = copyWithStructuralSharing(objA, objB)
+  expect(newCopy).not.toBe(objA)
+  expect(newCopy).not.toBe(objB)
+  expect(newCopy).toStrictEqual(objB)
+
+  expect(newCopy[3]).toBe(objA[3])
+  expect(newCopy[3]).not.toBe(objB[3])
+  expect(newCopy[3]).toStrictEqual(objB[3])
+
+  expect(newCopy[2]).not.toBe(objA[2])
+  expect(newCopy[2]).not.toBe(objB[2])
+  expect(newCopy[2]).toStrictEqual(objB[2])
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/createApi.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/createApi.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/createApi.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,521 @@
+import { setupApiStore } from '@internal/tests/utils/helpers'
+import type { EntityState, SerializedError } from '@reduxjs/toolkit'
+import { configureStore, createEntityAdapter } from '@reduxjs/toolkit'
+import type {
+  DefinitionsFromApi,
+  FetchBaseQueryError,
+  FetchBaseQueryMeta,
+  MutationDefinition,
+  OverrideResultType,
+  QueryDefinition,
+  TagDescription,
+  TagTypesFromApi,
+} from '@reduxjs/toolkit/query'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+import * as v from 'valibot'
+import type { Post } from './mocks/handlers'
+
+describe('type tests', () => {
+  test('sensible defaults', () => {
+    const api = createApi({
+      baseQuery: fetchBaseQuery(),
+      endpoints: (build) => ({
+        getUser: build.query<unknown, void>({
+          query(id) {
+            return { url: `user/${id}` }
+          },
+        }),
+        updateUser: build.mutation<unknown, void>({
+          query: () => '',
+        }),
+      }),
+    })
+
+    configureStore({
+      reducer: {
+        [api.reducerPath]: api.reducer,
+      },
+      middleware: (gDM) => gDM().concat(api.middleware),
+    })
+
+    expectTypeOf(api.reducerPath).toEqualTypeOf<'api'>()
+
+    expectTypeOf(api.util.invalidateTags)
+      .parameter(0)
+      .toEqualTypeOf<(null | undefined | TagDescription<never>)[]>()
+  })
+
+  describe('endpoint definition typings', () => {
+    const api = createApi({
+      baseQuery: (from: 'From'): { data: 'To' } | Promise<{ data: 'To' }> => ({
+        data: 'To',
+      }),
+      endpoints: () => ({}),
+      tagTypes: ['typeA', 'typeB'],
+    })
+
+    test('query: query & transformResponse types', () => {
+      api.injectEndpoints({
+        endpoints: (build) => ({
+          query: build.query<'RetVal', 'Arg'>({
+            query: (x: 'Arg') => 'From' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          }),
+          query1: build.query<'RetVal', 'Arg'>({
+            // @ts-expect-error
+            query: (x: 'Error') => 'From' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          }),
+          query2: build.query<'RetVal', 'Arg'>({
+            // @ts-expect-error
+            query: (x: 'Arg') => 'Error' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          }),
+          query3: build.query<'RetVal', 'Arg'>({
+            query: (x: 'Arg') => 'From' as const,
+            // @ts-expect-error
+            transformResponse(r: 'Error') {
+              return 'RetVal' as const
+            },
+          }),
+          query4: build.query<'RetVal', 'Arg'>({
+            query: (x: 'Arg') => 'From' as const,
+            // @ts-expect-error
+            transformResponse(r: 'To') {
+              return 'Error' as const
+            },
+          }),
+          queryInference1: build.query<'RetVal', 'Arg'>({
+            query: (x) => {
+              expectTypeOf(x).toEqualTypeOf<'Arg'>()
+
+              return 'From'
+            },
+            transformResponse(r) {
+              expectTypeOf(r).toEqualTypeOf<'To'>()
+
+              return 'RetVal'
+            },
+          }),
+          queryInference2: (() => {
+            const query = build.query({
+              query: (x: 'Arg') => 'From' as const,
+              transformResponse(r: 'To') {
+                return 'RetVal' as const
+              },
+            })
+
+            expectTypeOf(query).toMatchTypeOf<
+              QueryDefinition<'Arg', any, any, 'RetVal'>
+            >()
+
+            return query
+          })(),
+        }),
+      })
+    })
+
+    test('mutation: query & transformResponse types', () => {
+      api.injectEndpoints({
+        endpoints: (build) => ({
+          query: build.mutation<'RetVal', 'Arg'>({
+            query: (x: 'Arg') => 'From' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          }),
+          query1: build.mutation<'RetVal', 'Arg'>({
+            // @ts-expect-error
+            query: (x: 'Error') => 'From' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          }),
+          query2: build.mutation<'RetVal', 'Arg'>({
+            // @ts-expect-error
+            query: (x: 'Arg') => 'Error' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          }),
+          query3: build.mutation<'RetVal', 'Arg'>({
+            query: (x: 'Arg') => 'From' as const,
+            // @ts-expect-error
+            transformResponse(r: 'Error') {
+              return 'RetVal' as const
+            },
+          }),
+          query4: build.mutation<'RetVal', 'Arg'>({
+            query: (x: 'Arg') => 'From' as const,
+            // @ts-expect-error
+            transformResponse(r: 'To') {
+              return 'Error' as const
+            },
+          }),
+          mutationInference1: build.mutation<'RetVal', 'Arg'>({
+            query: (x) => {
+              expectTypeOf(x).toEqualTypeOf<'Arg'>()
+
+              return 'From'
+            },
+            transformResponse(r) {
+              expectTypeOf(r).toEqualTypeOf<'To'>()
+
+              return 'RetVal'
+            },
+          }),
+          mutationInference2: (() => {
+            const query = build.mutation({
+              query: (x: 'Arg') => 'From' as const,
+              transformResponse(r: 'To') {
+                return 'RetVal' as const
+              },
+            })
+
+            expectTypeOf(query).toMatchTypeOf<
+              MutationDefinition<'Arg', any, any, 'RetVal'>
+            >()
+
+            return query
+          })(),
+        }),
+      })
+    })
+
+    describe('enhancing endpoint definitions', () => {
+      const baseQuery = (x: string) => ({ data: 'success' })
+
+      function getNewApi() {
+        return createApi({
+          baseQuery,
+          tagTypes: ['old'],
+          endpoints: (build) => ({
+            query1: build.query<'out1', 'in1'>({ query: (id) => `${id}` }),
+            query2: build.query<'out2', 'in2'>({ query: (id) => `${id}` }),
+            mutation1: build.mutation<'out1', 'in1'>({
+              query: (id) => `${id}`,
+            }),
+            mutation2: build.mutation<'out2', 'in2'>({
+              query: (id) => `${id}`,
+            }),
+          }),
+        })
+      }
+
+      const api1 = getNewApi()
+
+      test('warn on wrong tagType', () => {
+        const storeRef = setupApiStore(api1, undefined, {
+          withoutTestLifecycles: true,
+        })
+
+        api1.enhanceEndpoints({
+          endpoints: {
+            query1: {
+              // @ts-expect-error
+              providesTags: ['new'],
+            },
+            query2: {
+              // @ts-expect-error
+              providesTags: ['missing'],
+            },
+          },
+        })
+
+        const enhanced = api1.enhanceEndpoints({
+          addTagTypes: ['new'],
+          endpoints: {
+            query1: {
+              providesTags: ['new'],
+            },
+            query2: {
+              // @ts-expect-error
+              providesTags: ['missing'],
+            },
+          },
+        })
+
+        storeRef.store.dispatch(api1.endpoints.query1.initiate('in1'))
+
+        storeRef.store.dispatch(api1.endpoints.query2.initiate('in2'))
+
+        enhanced.enhanceEndpoints({
+          endpoints: {
+            query1: {
+              // returned `enhanced` api contains "new" entityType
+              providesTags: ['new'],
+            },
+            query2: {
+              // @ts-expect-error
+              providesTags: ['missing'],
+            },
+          },
+        })
+      })
+
+      test('modify', () => {
+        const storeRef = setupApiStore(api1, undefined, {
+          withoutTestLifecycles: true,
+        })
+
+        api1.enhanceEndpoints({
+          endpoints: {
+            query1: {
+              query: (x) => {
+                expectTypeOf(x).toEqualTypeOf<'in1'>()
+
+                return 'modified1'
+              },
+            },
+            query2(definition) {
+              definition.query = (x) => {
+                expectTypeOf(x).toEqualTypeOf<'in2'>()
+
+                return 'modified2'
+              }
+            },
+            mutation1: {
+              query: (x) => {
+                expectTypeOf(x).toEqualTypeOf<'in1'>()
+
+                return 'modified1'
+              },
+            },
+            mutation2(definition) {
+              definition.query = (x) => {
+                expectTypeOf(x).toEqualTypeOf<'in2'>()
+
+                return 'modified2'
+              }
+            },
+            // @ts-expect-error
+            nonExisting: {},
+          },
+        })
+
+        storeRef.store.dispatch(api1.endpoints.query1.initiate('in1'))
+        storeRef.store.dispatch(api1.endpoints.query2.initiate('in2'))
+        storeRef.store.dispatch(api1.endpoints.mutation1.initiate('in1'))
+        storeRef.store.dispatch(api1.endpoints.mutation2.initiate('in2'))
+      })
+
+      test('updated transform response types', async () => {
+        const baseApi = createApi({
+          baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+          tagTypes: ['old'],
+          endpoints: (build) => ({
+            query1: build.query<'out1', void>({ query: () => 'success' }),
+            mutation1: build.mutation<'out1', void>({ query: () => 'success' }),
+          }),
+        })
+
+        type Transformed = { value: string }
+
+        type Definitions = DefinitionsFromApi<typeof api1>
+
+        type TagTypes = TagTypesFromApi<typeof api1>
+
+        type Q1Definition = OverrideResultType<
+          Definitions['query1'],
+          Transformed
+        >
+
+        type M1Definition = OverrideResultType<
+          Definitions['mutation1'],
+          Transformed
+        >
+
+        type UpdatedDefinitions = Omit<Definitions, 'query1' | 'mutation1'> & {
+          query1: Q1Definition
+          mutation1: M1Definition
+        }
+
+        const enhancedApi = baseApi.enhanceEndpoints<
+          TagTypes,
+          UpdatedDefinitions
+        >({
+          endpoints: {
+            query1: {
+              transformResponse: (a, b, c) => ({
+                value: 'transformed',
+              }),
+            },
+            mutation1: {
+              transformResponse: (a, b, c) => ({
+                value: 'transformed',
+              }),
+            },
+          },
+        })
+
+        const storeRef = setupApiStore(enhancedApi, undefined, {
+          withoutTestLifecycles: true,
+        })
+
+        const queryResponse = await storeRef.store.dispatch(
+          enhancedApi.endpoints.query1.initiate(),
+        )
+
+        expectTypeOf(queryResponse.data).toMatchTypeOf<
+          Transformed | undefined
+        >()
+
+        const mutationResponse = await storeRef.store.dispatch(
+          enhancedApi.endpoints.mutation1.initiate(),
+        )
+
+        expectTypeOf(mutationResponse).toMatchTypeOf<
+          | { data: Transformed }
+          | { error: FetchBaseQueryError | SerializedError }
+        >()
+      })
+    })
+    describe('endpoint schemas', () => {
+      const argSchema = v.object({ id: v.number() })
+      const postSchema = v.object({
+        id: v.number(),
+        title: v.string(),
+        body: v.string(),
+      }) satisfies v.GenericSchema<Post>
+      const errorResponseSchema = v.object({
+        status: v.number(),
+        data: v.unknown(),
+      }) satisfies v.GenericSchema<FetchBaseQueryError>
+      const metaSchema = v.object({
+        request: v.instance(Request),
+        response: v.optional(v.instance(Response)),
+      }) satisfies v.GenericSchema<FetchBaseQueryMeta>
+      test('schemas must match', () => {
+        createApi({
+          baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+          endpoints: (build) => ({
+            query: build.query<Post, { id: number }>({
+              query: ({ id }) => `/post/${id}`,
+              argSchema,
+              responseSchema: postSchema,
+              errorResponseSchema,
+              metaSchema,
+            }),
+            bothMismatch: build.query<Post, { id: number }>({
+              query: ({ id }) => `/post/${id}`,
+              // @ts-expect-error wrong schema
+              argSchema: v.object({ id: v.string() }),
+              // @ts-expect-error wrong schema
+              responseSchema: v.object({ id: v.string() }),
+              // @ts-expect-error wrong schema
+              errorResponseSchema: v.object({ status: v.string() }),
+              // @ts-expect-error wrong schema
+              metaSchema: v.object({ request: v.string() }),
+            }),
+            inputMismatch: build.query<Post, { id: number }>({
+              query: ({ id }) => `/post/${id}`,
+              // @ts-expect-error can't expect different input
+              argSchema: v.object({
+                id: v.pipe(v.string(), v.transform(Number), v.number()),
+              }),
+              // @ts-expect-error can't expect different input
+              responseSchema: v.object({
+                ...postSchema.entries,
+                id: v.pipe(v.string(), v.transform(Number)),
+              }) satisfies v.GenericSchema<any, Post>,
+              // @ts-expect-error can't expect different input
+              errorResponseSchema: v.object({
+                ...errorResponseSchema.entries,
+                status: v.pipe(v.string(), v.transform(Number)),
+              }) satisfies v.GenericSchema<any, FetchBaseQueryError>,
+              // @ts-expect-error can't expect different input
+              metaSchema: v.object({
+                ...metaSchema.entries,
+                request: v.pipe(
+                  v.string(),
+                  v.transform((url) => new Request(url)),
+                ),
+              }) satisfies v.GenericSchema<any, FetchBaseQueryMeta>,
+            }),
+            outputMismatch: build.query<Post, { id: number }>({
+              query: ({ id }) => `/post/${id}`,
+              // @ts-expect-error can't provide different output
+              argSchema: v.object({
+                id: v.pipe(v.number(), v.transform(String)),
+              }),
+              // @ts-expect-error can't provide different output
+              responseSchema: v.object({
+                ...postSchema.entries,
+                id: v.pipe(v.number(), v.transform(String)),
+              }) satisfies v.GenericSchema<Post, any>,
+              // @ts-expect-error can't provide different output
+              errorResponseSchema: v.object({
+                ...errorResponseSchema.entries,
+                status: v.pipe(v.number(), v.transform(String)),
+              }) satisfies v.GenericSchema<FetchBaseQueryError, any>,
+              // @ts-expect-error can't provide different output
+              metaSchema: v.object({
+                ...metaSchema.entries,
+                request: v.pipe(
+                  v.instance(Request),
+                  v.transform((r) => r.url),
+                ),
+              }) satisfies v.GenericSchema<FetchBaseQueryMeta, any>,
+            }),
+          }),
+        })
+      })
+      test('schemas as a source of inference', () => {
+        const postAdapter = createEntityAdapter<Post>()
+        const api = createApi({
+          baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+          endpoints: (build) => ({
+            query: build.query({
+              query: ({ id }: { id: number }) => `/post/${id}`,
+              responseSchema: postSchema,
+            }),
+            query2: build.query({
+              query: (arg) => {
+                expectTypeOf(arg).toEqualTypeOf<{ id: number }>()
+                return `/post/${arg.id}`
+              },
+              argSchema,
+              responseSchema: postSchema,
+            }),
+            query3: build.query({
+              query: (_arg: void) => `/posts`,
+              rawResponseSchema: v.array(postSchema),
+              transformResponse: (posts) => {
+                expectTypeOf(posts).toEqualTypeOf<Post[]>()
+                return postAdapter.getInitialState(undefined, posts)
+              },
+            }),
+          }),
+        })
+
+        expectTypeOf(api.endpoints.query.Types.QueryArg).toEqualTypeOf<{
+          id: number
+        }>()
+        expectTypeOf(api.endpoints.query.Types.ResultType).toEqualTypeOf<Post>()
+        expectTypeOf(api.endpoints.query.Types.RawResultType).toBeAny()
+
+        expectTypeOf(api.endpoints.query2.Types.QueryArg).toEqualTypeOf<{
+          id: number
+        }>()
+        expectTypeOf(
+          api.endpoints.query2.Types.ResultType,
+        ).toEqualTypeOf<Post>()
+        expectTypeOf(api.endpoints.query2.Types.RawResultType).toBeAny()
+
+        expectTypeOf(api.endpoints.query3.Types.QueryArg).toEqualTypeOf<void>()
+        expectTypeOf(api.endpoints.query3.Types.ResultType).toEqualTypeOf<
+          EntityState<Post, Post['id']>
+        >()
+        expectTypeOf(api.endpoints.query3.Types.RawResultType).toEqualTypeOf<
+          Post[]
+        >()
+      })
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/createApi.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/createApi.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/createApi.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1833 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import { server } from '@internal/query/tests/mocks/server'
+import {
+  getSerializedHeaders,
+  setupApiStore,
+} from '@internal/tests/utils/helpers'
+import type { SerializedError } from '@reduxjs/toolkit'
+import { configureStore, createAction, createReducer } from '@reduxjs/toolkit'
+import type {
+  DefinitionsFromApi,
+  FetchBaseQueryError,
+  FetchBaseQueryMeta,
+  OverrideResultType,
+  SchemaFailureConverter,
+  SchemaType,
+  SerializeQueryArgs,
+  TagTypesFromApi,
+} from '@reduxjs/toolkit/query'
+import {
+  createApi,
+  fetchBaseQuery,
+  NamedSchemaError,
+} from '@reduxjs/toolkit/query'
+import { HttpResponse, delay, http } from 'msw'
+import nodeFetch from 'node-fetch'
+import * as v from 'valibot'
+import type { SchemaFailureHandler } from '../endpointDefinitions'
+
+beforeAll(() => {
+  vi.stubEnv('NODE_ENV', 'development')
+
+  return vi.unstubAllEnvs
+})
+
+const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+afterEach(() => {
+  vi.clearAllMocks()
+  server.resetHandlers()
+})
+
+afterAll(() => {
+  vi.restoreAllMocks()
+})
+
+function paginate<T>(array: T[], page_size: number, page_number: number) {
+  // human-readable page numbers usually start with 1, so we reduce 1 in the first argument
+  return array.slice((page_number - 1) * page_size, page_number * page_size)
+}
+
+test('sensible defaults', () => {
+  const api = createApi({
+    baseQuery: fetchBaseQuery(),
+    endpoints: (build) => ({
+      getUser: build.query<unknown, void>({
+        query(id) {
+          return { url: `user/${id}` }
+        },
+      }),
+      updateUser: build.mutation<unknown, void>({
+        query: () => '',
+      }),
+    }),
+  })
+  configureStore({
+    reducer: {
+      [api.reducerPath]: api.reducer,
+    },
+    middleware: (gDM) => gDM().concat(api.middleware),
+  })
+  expect(api.reducerPath).toBe('api')
+
+  expect(api.endpoints.getUser.name).toBe('getUser')
+  expect(api.endpoints.updateUser.name).toBe('updateUser')
+})
+
+describe('wrong tagTypes log errors', () => {
+  const baseQuery = vi.fn()
+  const api = createApi({
+    baseQuery,
+    tagTypes: ['User'],
+    endpoints: (build) => ({
+      provideNothing: build.query<unknown, void>({
+        query: () => '',
+      }),
+      provideTypeString: build.query<unknown, void>({
+        query: () => '',
+        providesTags: ['User'],
+      }),
+      provideTypeWithId: build.query<unknown, void>({
+        query: () => '',
+        providesTags: [{ type: 'User', id: 5 }],
+      }),
+      provideTypeWithIdAndCallback: build.query<unknown, void>({
+        query: () => '',
+        providesTags: () => [{ type: 'User', id: 5 }],
+      }),
+      provideWrongTypeString: build.query<unknown, void>({
+        query: () => '',
+        // @ts-expect-error
+        providesTags: ['Users'],
+      }),
+      provideWrongTypeWithId: build.query<unknown, void>({
+        query: () => '',
+        // @ts-expect-error
+        providesTags: [{ type: 'Users', id: 5 }],
+      }),
+      provideWrongTypeWithIdAndCallback: build.query<unknown, void>({
+        query: () => '',
+        // @ts-expect-error
+        providesTags: () => [{ type: 'Users', id: 5 }],
+      }),
+      invalidateNothing: build.query<unknown, void>({
+        query: () => '',
+      }),
+      invalidateTypeString: build.mutation<unknown, void>({
+        query: () => '',
+        invalidatesTags: ['User'],
+      }),
+      invalidateTypeWithId: build.mutation<unknown, void>({
+        query: () => '',
+        invalidatesTags: [{ type: 'User', id: 5 }],
+      }),
+      invalidateTypeWithIdAndCallback: build.mutation<unknown, void>({
+        query: () => '',
+        invalidatesTags: () => [{ type: 'User', id: 5 }],
+      }),
+
+      invalidateWrongTypeString: build.mutation<unknown, void>({
+        query: () => '',
+        // @ts-expect-error
+        invalidatesTags: ['Users'],
+      }),
+      invalidateWrongTypeWithId: build.mutation<unknown, void>({
+        query: () => '',
+        // @ts-expect-error
+        invalidatesTags: [{ type: 'Users', id: 5 }],
+      }),
+      invalidateWrongTypeWithIdAndCallback: build.mutation<unknown, void>({
+        query: () => '',
+        // @ts-expect-error
+        invalidatesTags: () => [{ type: 'Users', id: 5 }],
+      }),
+    }),
+  })
+  const store = configureStore({
+    reducer: {
+      [api.reducerPath]: api.reducer,
+    },
+    middleware: (gDM) => gDM().concat(api.middleware),
+  })
+
+  beforeEach(() => {
+    baseQuery.mockResolvedValue({ data: 'foo' })
+  })
+
+  test.each<[keyof typeof api.endpoints, boolean?]>([
+    ['provideNothing', false],
+    ['provideTypeString', false],
+    ['provideTypeWithId', false],
+    ['provideTypeWithIdAndCallback', false],
+    ['provideWrongTypeString', true],
+    ['provideWrongTypeWithId', true],
+    ['provideWrongTypeWithIdAndCallback', true],
+    ['invalidateNothing', false],
+    ['invalidateTypeString', false],
+    ['invalidateTypeWithId', false],
+    ['invalidateTypeWithIdAndCallback', false],
+    ['invalidateWrongTypeString', true],
+    ['invalidateWrongTypeWithId', true],
+    ['invalidateWrongTypeWithIdAndCallback', true],
+  ])(`endpoint %s should log an error? %s`, async (endpoint, shouldError) => {
+    vi.stubEnv('NODE_ENV', 'development')
+
+    // @ts-ignore
+    store.dispatch(api.endpoints[endpoint].initiate())
+    let result: { status: string }
+    do {
+      await delay(5)
+      // @ts-ignore
+      result = api.endpoints[endpoint].select()(store.getState())
+    } while (result.status === 'pending')
+
+    if (shouldError) {
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        "Tag type 'Users' was used, but not specified in `tagTypes`!",
+      )
+    } else {
+      expect(consoleErrorSpy).not.toHaveBeenCalled()
+    }
+  })
+})
+
+describe('endpoint definition typings', () => {
+  const api = createApi({
+    baseQuery: (from: 'From'): { data: 'To' } | Promise<{ data: 'To' }> => ({
+      data: 'To',
+    }),
+    endpoints: () => ({}),
+    tagTypes: ['typeA', 'typeB'],
+  })
+  test('query: query & transformResponse types', () => {
+    api.injectEndpoints({
+      endpoints: (build) => ({
+        query: build.query<'RetVal', 'Arg'>({
+          query: (x: 'Arg') => 'From' as const,
+          transformResponse(r: 'To') {
+            return 'RetVal' as const
+          },
+        }),
+        query1: build.query<'RetVal', 'Arg'>({
+          // @ts-expect-error
+          query: (x: 'Error') => 'From' as const,
+          transformResponse(r: 'To') {
+            return 'RetVal' as const
+          },
+        }),
+        query2: build.query<'RetVal', 'Arg'>({
+          // @ts-expect-error
+          query: (x: 'Arg') => 'Error' as const,
+          transformResponse(r: 'To') {
+            return 'RetVal' as const
+          },
+        }),
+        query3: build.query<'RetVal', 'Arg'>({
+          query: (x: 'Arg') => 'From' as const,
+          // @ts-expect-error
+          transformResponse(r: 'Error') {
+            return 'RetVal' as const
+          },
+        }),
+        query4: build.query<'RetVal', 'Arg'>({
+          query: (x: 'Arg') => 'From' as const,
+          // @ts-expect-error
+          transformResponse(r: 'To') {
+            return 'Error' as const
+          },
+        }),
+        queryInference1: build.query<'RetVal', 'Arg'>({
+          query: (x) => {
+            return 'From'
+          },
+          transformResponse(r) {
+            return 'RetVal'
+          },
+        }),
+        queryInference2: (() => {
+          const query = build.query({
+            query: (x: 'Arg') => 'From' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          })
+          return query
+        })(),
+      }),
+    })
+  })
+  test('mutation: query & transformResponse types', () => {
+    api.injectEndpoints({
+      endpoints: (build) => ({
+        query: build.mutation<'RetVal', 'Arg'>({
+          query: (x: 'Arg') => 'From' as const,
+          transformResponse(r: 'To') {
+            return 'RetVal' as const
+          },
+        }),
+        query1: build.mutation<'RetVal', 'Arg'>({
+          // @ts-expect-error
+          query: (x: 'Error') => 'From' as const,
+          transformResponse(r: 'To') {
+            return 'RetVal' as const
+          },
+        }),
+        query2: build.mutation<'RetVal', 'Arg'>({
+          // @ts-expect-error
+          query: (x: 'Arg') => 'Error' as const,
+          transformResponse(r: 'To') {
+            return 'RetVal' as const
+          },
+        }),
+        query3: build.mutation<'RetVal', 'Arg'>({
+          query: (x: 'Arg') => 'From' as const,
+          // @ts-expect-error
+          transformResponse(r: 'Error') {
+            return 'RetVal' as const
+          },
+        }),
+        query4: build.mutation<'RetVal', 'Arg'>({
+          query: (x: 'Arg') => 'From' as const,
+          // @ts-expect-error
+          transformResponse(r: 'To') {
+            return 'Error' as const
+          },
+        }),
+        mutationInference1: build.mutation<'RetVal', 'Arg'>({
+          query: (x) => {
+            return 'From'
+          },
+          transformResponse(r) {
+            return 'RetVal'
+          },
+        }),
+        mutationInference2: (() => {
+          const query = build.mutation({
+            query: (x: 'Arg') => 'From' as const,
+            transformResponse(r: 'To') {
+              return 'RetVal' as const
+            },
+          })
+          return query
+        })(),
+      }),
+    })
+  })
+
+  describe('enhancing endpoint definitions', () => {
+    const baseQuery = vi.fn((x: string) => ({ data: 'success' }))
+    const commonBaseQueryApi = {
+      dispatch: expect.any(Function),
+      endpoint: expect.any(String),
+      abort: expect.any(Function),
+      extra: undefined,
+      forced: expect.any(Boolean),
+      getState: expect.any(Function),
+      signal: expect.any(Object),
+      type: expect.any(String),
+      queryCacheKey: expect.any(String),
+    }
+    beforeEach(() => {
+      baseQuery.mockClear()
+    })
+    function getNewApi() {
+      return createApi({
+        baseQuery,
+        tagTypes: ['old'],
+        endpoints: (build) => ({
+          query1: build.query<'out1', 'in1'>({ query: (id) => `${id}` }),
+          query2: build.query<'out2', 'in2'>({ query: (id) => `${id}` }),
+          mutation1: build.mutation<'out1', 'in1'>({ query: (id) => `${id}` }),
+          mutation2: build.mutation<'out2', 'in2'>({ query: (id) => `${id}` }),
+        }),
+      })
+    }
+    let api = getNewApi()
+    beforeEach(() => {
+      api = getNewApi()
+    })
+
+    test('pre-modification behavior', async () => {
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      storeRef.store.dispatch(api.endpoints.query1.initiate('in1'))
+      storeRef.store.dispatch(api.endpoints.query2.initiate('in2'))
+      storeRef.store.dispatch(api.endpoints.mutation1.initiate('in1'))
+      storeRef.store.dispatch(api.endpoints.mutation2.initiate('in2'))
+
+      expect(baseQuery.mock.calls).toEqual([
+        [
+          'in1',
+          {
+            dispatch: expect.any(Function),
+            endpoint: expect.any(String),
+            getState: expect.any(Function),
+            signal: expect.any(Object),
+            abort: expect.any(Function),
+            forced: expect.any(Boolean),
+            type: expect.any(String),
+            queryCacheKey: expect.any(String),
+          },
+          undefined,
+        ],
+        [
+          'in2',
+          {
+            dispatch: expect.any(Function),
+            endpoint: expect.any(String),
+            getState: expect.any(Function),
+            signal: expect.any(Object),
+            abort: expect.any(Function),
+            forced: expect.any(Boolean),
+            type: expect.any(String),
+            queryCacheKey: expect.any(String),
+          },
+          undefined,
+        ],
+        [
+          'in1',
+          {
+            dispatch: expect.any(Function),
+            endpoint: expect.any(String),
+            getState: expect.any(Function),
+            signal: expect.any(Object),
+            abort: expect.any(Function),
+            // forced: undefined,
+            type: expect.any(String),
+          },
+          undefined,
+        ],
+        [
+          'in2',
+          {
+            dispatch: expect.any(Function),
+            endpoint: expect.any(String),
+            getState: expect.any(Function),
+            signal: expect.any(Object),
+            abort: expect.any(Function),
+            // forced: undefined,
+            type: expect.any(String),
+          },
+          undefined,
+        ],
+      ])
+    })
+
+    test('warn on wrong tagType', async () => {
+      vi.stubEnv('NODE_ENV', 'development')
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      // only type-test this part
+      if (2 > 1) {
+        api.enhanceEndpoints({
+          endpoints: {
+            query1: {
+              // @ts-expect-error
+              providesTags: ['new'],
+            },
+            query2: {
+              // @ts-expect-error
+              providesTags: ['missing'],
+            },
+          },
+        })
+      }
+
+      const enhanced = api.enhanceEndpoints({
+        addTagTypes: ['new'],
+        endpoints: {
+          query1: {
+            providesTags: ['new'],
+          },
+          query2: {
+            // @ts-expect-error
+            providesTags: ['missing'],
+          },
+        },
+      })
+
+      storeRef.store.dispatch(api.endpoints.query1.initiate('in1'))
+      await delay(1)
+      expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+      storeRef.store.dispatch(api.endpoints.query2.initiate('in2'))
+      await delay(1)
+
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        "Tag type 'missing' was used, but not specified in `tagTypes`!",
+      )
+
+      // only type-test this part
+      if (2 > 1) {
+        enhanced.enhanceEndpoints({
+          endpoints: {
+            query1: {
+              // returned `enhanced` api contains "new" enitityType
+              providesTags: ['new'],
+            },
+            query2: {
+              // @ts-expect-error
+              providesTags: ['missing'],
+            },
+          },
+        })
+      }
+    })
+
+    test('modify', () => {
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      api.enhanceEndpoints({
+        endpoints: {
+          query1: {
+            query: (x) => {
+              return 'modified1'
+            },
+          },
+          query2(definition) {
+            definition.query = (x) => {
+              return 'modified2'
+            }
+          },
+          mutation1: {
+            query: (x) => {
+              return 'modified1'
+            },
+          },
+          mutation2(definition) {
+            definition.query = (x) => {
+              return 'modified2'
+            }
+          },
+          // @ts-expect-error
+          nonExisting: {},
+        },
+      })
+
+      storeRef.store.dispatch(api.endpoints.query1.initiate('in1'))
+      storeRef.store.dispatch(api.endpoints.query2.initiate('in2'))
+      storeRef.store.dispatch(api.endpoints.mutation1.initiate('in1'))
+      storeRef.store.dispatch(api.endpoints.mutation2.initiate('in2'))
+
+      expect(baseQuery.mock.calls).toEqual([
+        ['modified1', commonBaseQueryApi, undefined],
+        ['modified2', commonBaseQueryApi, undefined],
+        [
+          'modified1',
+          {
+            ...commonBaseQueryApi,
+            forced: undefined,
+            queryCacheKey: undefined,
+          },
+          undefined,
+        ],
+        [
+          'modified2',
+          {
+            ...commonBaseQueryApi,
+            forced: undefined,
+            queryCacheKey: undefined,
+          },
+          undefined,
+        ],
+      ])
+    })
+
+    test('updated transform response types', async () => {
+      const baseApi = createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        tagTypes: ['old'],
+        endpoints: (build) => ({
+          query1: build.query<'out1', void>({ query: () => 'success' }),
+          mutation1: build.mutation<'out1', void>({ query: () => 'success' }),
+        }),
+      })
+
+      type Transformed = { value: string }
+
+      type Definitions = DefinitionsFromApi<typeof api>
+      type TagTypes = TagTypesFromApi<typeof api>
+
+      type Q1Definition = OverrideResultType<Definitions['query1'], Transformed>
+      type M1Definition = OverrideResultType<
+        Definitions['mutation1'],
+        Transformed
+      >
+
+      type UpdatedDefitions = Omit<Definitions, 'query1' | 'mutation1'> & {
+        query1: Q1Definition
+        mutation1: M1Definition
+      }
+
+      const enhancedApi = baseApi.enhanceEndpoints<TagTypes, UpdatedDefitions>({
+        endpoints: {
+          query1: {
+            transformResponse: (a, b, c) => ({
+              value: 'transformed',
+            }),
+          },
+          mutation1: {
+            transformResponse: (a, b, c) => ({
+              value: 'transformed',
+            }),
+          },
+        },
+      })
+
+      const storeRef = setupApiStore(enhancedApi, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const queryResponse = await storeRef.store.dispatch(
+        enhancedApi.endpoints.query1.initiate(),
+      )
+      expect(queryResponse.data).toEqual({ value: 'transformed' })
+
+      const mutationResponse = await storeRef.store.dispatch(
+        enhancedApi.endpoints.mutation1.initiate(),
+      )
+      expect('data' in mutationResponse && mutationResponse.data).toEqual({
+        value: 'transformed',
+      })
+    })
+  })
+})
+
+describe('additional transformResponse behaviors', () => {
+  type SuccessResponse = { value: 'success' }
+  type EchoResponseData = { banana: 'bread' }
+  type ErrorResponse = { value: 'error' }
+  const api = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+    endpoints: (build) => ({
+      echo: build.mutation({
+        query: () => ({ method: 'PUT', url: '/echo' }),
+      }),
+      mutation: build.mutation({
+        query: () => ({
+          url: '/echo',
+          method: 'POST',
+          body: { nested: { banana: 'bread' } },
+        }),
+        transformResponse: (response: { body: { nested: EchoResponseData } }) =>
+          response.body.nested,
+      }),
+      mutationWithError: build.mutation({
+        query: () => ({
+          url: '/error',
+          method: 'POST',
+        }),
+        transformErrorResponse: (response) => {
+          const data = response.data as ErrorResponse
+          return data.value
+        },
+      }),
+      mutationWithMeta: build.mutation({
+        query: () => ({
+          url: '/echo',
+          method: 'POST',
+          body: { nested: { banana: 'bread' } },
+        }),
+        transformResponse: (
+          response: { body: { nested: EchoResponseData } },
+          meta,
+        ) => {
+          return {
+            ...response.body.nested,
+            meta: {
+              request: { headers: getSerializedHeaders(meta?.request.headers) },
+              response: {
+                headers: getSerializedHeaders(meta?.response?.headers),
+              },
+            },
+          }
+        },
+      }),
+      query: build.query<SuccessResponse & EchoResponseData, void>({
+        query: () => '/success',
+        transformResponse: async (response: SuccessResponse) => {
+          const res: any = await nodeFetch('https://example.com/echo', {
+            method: 'POST',
+            body: JSON.stringify({ banana: 'bread' }),
+          }).then((res) => res.json())
+
+          const additionalData = res.body as EchoResponseData
+          return { ...response, ...additionalData }
+        },
+      }),
+      queryWithMeta: build.query<SuccessResponse, void>({
+        query: () => '/success',
+        transformResponse: async (response: SuccessResponse, meta) => {
+          return {
+            ...response,
+            meta: {
+              request: { headers: getSerializedHeaders(meta?.request.headers) },
+              response: {
+                headers: getSerializedHeaders(meta?.response?.headers),
+              },
+            },
+          }
+        },
+      }),
+    }),
+  })
+
+  const storeRef = setupApiStore(api)
+
+  test('transformResponse handles an async transformation and returns the merged data (query)', async () => {
+    const result = await storeRef.store.dispatch(api.endpoints.query.initiate())
+
+    expect(result.data).toEqual({ value: 'success', banana: 'bread' })
+  })
+
+  test('transformResponse transforms a response from a mutation', async () => {
+    const result = await storeRef.store.dispatch(
+      api.endpoints.mutation.initiate({}),
+    )
+
+    expect('data' in result && result.data).toEqual({ banana: 'bread' })
+  })
+
+  test('transformResponse transforms a response from a mutation with an error', async () => {
+    const result = await storeRef.store.dispatch(
+      api.endpoints.mutationWithError.initiate({}),
+    )
+
+    expect('error' in result && result.error).toEqual('error')
+  })
+
+  test('transformResponse can inject baseQuery meta into the end result from a mutation', async () => {
+    const result = await storeRef.store.dispatch(
+      api.endpoints.mutationWithMeta.initiate({}),
+    )
+
+    expect('data' in result && result.data).toEqual({
+      banana: 'bread',
+      meta: {
+        request: {
+          headers: {
+            accept: 'application/json',
+            'content-type': 'application/json',
+          },
+        },
+        response: {
+          headers: {
+            'content-type': 'application/json',
+          },
+        },
+      },
+    })
+  })
+
+  test('transformResponse can inject baseQuery meta into the end result from a query', async () => {
+    const result = await storeRef.store.dispatch(
+      api.endpoints.queryWithMeta.initiate(),
+    )
+
+    expect(result.data).toEqual({
+      value: 'success',
+      meta: {
+        request: {
+          headers: {
+            accept: 'application/json',
+          },
+        },
+        response: {
+          headers: {
+            'content-type': 'application/json',
+          },
+        },
+      },
+    })
+  })
+})
+
+describe('query endpoint lifecycles - onStart, onSuccess, onError', () => {
+  const initialState = {
+    count: null as null | number,
+  }
+  const setCount = createAction<number>('setCount')
+  const testReducer = createReducer(initialState, (builder) => {
+    builder.addCase(setCount, (state, action) => {
+      state.count = action.payload
+    })
+  })
+
+  type SuccessResponse = { value: 'success' }
+  const api = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+    endpoints: (build) => ({
+      echo: build.mutation({
+        query: () => ({ method: 'PUT', url: '/echo' }),
+      }),
+      query: build.query<SuccessResponse, void>({
+        query: () => '/success',
+        async onQueryStarted(_, api) {
+          api.dispatch(setCount(0))
+          try {
+            await api.queryFulfilled
+            api.dispatch(setCount(1))
+          } catch {
+            api.dispatch(setCount(-1))
+          }
+        },
+      }),
+      mutation: build.mutation<SuccessResponse, void>({
+        query: () => ({ url: '/success', method: 'POST' }),
+        async onQueryStarted(_, api) {
+          api.dispatch(setCount(0))
+          try {
+            await api.queryFulfilled
+            api.dispatch(setCount(1))
+          } catch {
+            api.dispatch(setCount(-1))
+          }
+        },
+      }),
+    }),
+  })
+
+  const storeRef = setupApiStore(api, { testReducer })
+
+  test('query lifecycle events fire properly', async () => {
+    // We intentionally fail the first request so we can test all lifecycles
+    server.use(
+      http.get(
+        'https://example.com/success',
+        () => HttpResponse.json({ value: 'failed' }, { status: 500 }),
+        { once: true },
+      ),
+    )
+
+    expect(storeRef.store.getState().testReducer.count).toBe(null)
+    const failAttempt = storeRef.store.dispatch(api.endpoints.query.initiate())
+    expect(storeRef.store.getState().testReducer.count).toBe(0)
+    await failAttempt
+    await delay(10)
+    expect(storeRef.store.getState().testReducer.count).toBe(-1)
+
+    const successAttempt = storeRef.store.dispatch(
+      api.endpoints.query.initiate(),
+    )
+    expect(storeRef.store.getState().testReducer.count).toBe(0)
+    await successAttempt
+    await delay(10)
+    expect(storeRef.store.getState().testReducer.count).toBe(1)
+  })
+
+  test('mutation lifecycle events fire properly', async () => {
+    // We intentionally fail the first request so we can test all lifecycles
+    server.use(
+      http.post(
+        'https://example.com/success',
+        () => HttpResponse.json({ value: 'failed' }, { status: 500 }),
+        { once: true },
+      ),
+    )
+
+    expect(storeRef.store.getState().testReducer.count).toBe(null)
+    const failAttempt = storeRef.store.dispatch(
+      api.endpoints.mutation.initiate(),
+    )
+    expect(storeRef.store.getState().testReducer.count).toBe(0)
+    await failAttempt
+    expect(storeRef.store.getState().testReducer.count).toBe(-1)
+
+    const successAttempt = storeRef.store.dispatch(
+      api.endpoints.mutation.initiate(),
+    )
+    expect(storeRef.store.getState().testReducer.count).toBe(0)
+    await successAttempt
+    expect(storeRef.store.getState().testReducer.count).toBe(1)
+  })
+})
+
+test('providesTags and invalidatesTags can use baseQueryMeta', async () => {
+  let _meta: FetchBaseQueryMeta | undefined
+
+  type SuccessResponse = { value: 'success' }
+
+  const api = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+    tagTypes: ['success'],
+    endpoints: (build) => ({
+      query: build.query<SuccessResponse, void>({
+        query: () => '/success',
+        providesTags: (_result, _error, _arg, meta) => {
+          _meta = meta
+          return ['success']
+        },
+      }),
+      mutation: build.mutation<SuccessResponse, void>({
+        query: () => ({ url: '/success', method: 'POST' }),
+        invalidatesTags: (_result, _error, _arg, meta) => {
+          _meta = meta
+          return ['success']
+        },
+      }),
+    }),
+  })
+
+  const storeRef = setupApiStore(api, undefined, {
+    withoutTestLifecycles: true,
+  })
+
+  await storeRef.store.dispatch(api.endpoints.query.initiate())
+  expect('request' in _meta! && 'response' in _meta!).toBe(true)
+
+  _meta = undefined
+
+  await storeRef.store.dispatch(api.endpoints.mutation.initiate())
+
+  expect('request' in _meta! && 'response' in _meta!).toBe(true)
+})
+
+describe('structuralSharing flag behaviors', () => {
+  type SuccessResponse = { value: 'success' }
+
+  const api = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+    tagTypes: ['success'],
+    endpoints: (build) => ({
+      enabled: build.query<SuccessResponse, void>({
+        query: () => '/success',
+      }),
+      disabled: build.query<SuccessResponse, void>({
+        query: () => ({ url: '/success' }),
+        structuralSharing: false,
+      }),
+    }),
+  })
+
+  const storeRef = setupApiStore(api)
+
+  it('enables structural sharing for query endpoints by default', async () => {
+    await storeRef.store.dispatch(api.endpoints.enabled.initiate())
+    const firstRef = api.endpoints.enabled.select()(storeRef.store.getState())
+
+    await storeRef.store.dispatch(
+      api.endpoints.enabled.initiate(undefined, { forceRefetch: true }),
+    )
+
+    const secondRef = api.endpoints.enabled.select()(storeRef.store.getState())
+
+    expect(firstRef.requestId).not.toEqual(secondRef.requestId)
+    expect(firstRef.data === secondRef.data).toBeTruthy()
+  })
+
+  it('allows a query endpoint to opt-out of structural sharing', async () => {
+    await storeRef.store.dispatch(api.endpoints.disabled.initiate())
+    const firstRef = api.endpoints.disabled.select()(storeRef.store.getState())
+
+    await storeRef.store.dispatch(
+      api.endpoints.disabled.initiate(undefined, { forceRefetch: true }),
+    )
+
+    const secondRef = api.endpoints.disabled.select()(storeRef.store.getState())
+
+    expect(firstRef.requestId).not.toEqual(secondRef.requestId)
+    expect(firstRef.data === secondRef.data).toBeFalsy()
+  })
+})
+
+describe('custom serializeQueryArgs per endpoint', () => {
+  const customArgsSerializer: SerializeQueryArgs<number> = ({
+    endpointName,
+    queryArgs,
+  }) => `${endpointName}-${queryArgs}`
+
+  type SuccessResponse = { value: 'success' }
+
+  const serializer1 = vi.fn(customArgsSerializer)
+
+  interface MyApiClient {
+    fetchPost: (id: string) => Promise<SuccessResponse>
+  }
+
+  const dummyClient: MyApiClient = {
+    async fetchPost() {
+      return { value: 'success' }
+    },
+  }
+
+  const api = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+    serializeQueryArgs: ({ endpointName, queryArgs }) =>
+      `base-${endpointName}-${queryArgs}`,
+    endpoints: (build) => ({
+      queryWithNoSerializer: build.query<SuccessResponse, number>({
+        query: (arg) => `${arg}`,
+      }),
+      queryWithCustomSerializer: build.query<SuccessResponse, number>({
+        query: (arg) => `${arg}`,
+        serializeQueryArgs: serializer1,
+      }),
+      queryWithCustomObjectSerializer: build.query<
+        SuccessResponse,
+        { id: number; client: MyApiClient }
+      >({
+        query: (arg) => `${arg.id}`,
+        serializeQueryArgs: ({
+          endpointDefinition,
+          endpointName,
+          queryArgs,
+        }) => {
+          const { id } = queryArgs
+          return { id }
+        },
+      }),
+      queryWithCustomNumberSerializer: build.query<
+        SuccessResponse,
+        { id: number; client: MyApiClient }
+      >({
+        query: (arg) => `${arg.id}`,
+        serializeQueryArgs: ({
+          endpointDefinition,
+          endpointName,
+          queryArgs,
+        }) => {
+          const { id } = queryArgs
+          return id
+        },
+      }),
+      listItems: build.query<string[], number>({
+        query: (pageNumber) => `/listItems?page=${pageNumber}`,
+        serializeQueryArgs: ({ endpointName }) => {
+          return endpointName
+        },
+        merge: (currentCache, newItems) => {
+          currentCache.push(...newItems)
+        },
+        forceRefetch({ currentArg, previousArg }) {
+          return currentArg !== previousArg
+        },
+      }),
+      listItems2: build.query<{ items: string[]; meta?: any }, number>({
+        query: (pageNumber) => `/listItems2?page=${pageNumber}`,
+        serializeQueryArgs: ({ endpointName }) => {
+          return endpointName
+        },
+        transformResponse(items: string[]) {
+          return { items }
+        },
+        merge: (currentCache, newData, meta) => {
+          currentCache.items.push(...newData.items)
+          currentCache.meta = meta
+        },
+        forceRefetch({ currentArg, previousArg }) {
+          return currentArg !== previousArg
+        },
+      }),
+    }),
+  })
+
+  const storeRef = setupApiStore(api)
+
+  it('Works via createApi', async () => {
+    await storeRef.store.dispatch(
+      api.endpoints.queryWithNoSerializer.initiate(99),
+    )
+
+    expect(serializer1).not.toHaveBeenCalled()
+
+    await storeRef.store.dispatch(
+      api.endpoints.queryWithCustomSerializer.initiate(42),
+    )
+
+    expect(serializer1).toHaveBeenCalled()
+
+    expect(
+      storeRef.store.getState().api.queries['base-queryWithNoSerializer-99'],
+    ).toBeTruthy()
+
+    expect(
+      storeRef.store.getState().api.queries['queryWithCustomSerializer-42'],
+    ).toBeTruthy()
+  })
+
+  const serializer2 = vi.fn(customArgsSerializer)
+
+  const injectedApi = api.injectEndpoints({
+    endpoints: (build) => ({
+      injectedQueryWithCustomSerializer: build.query<SuccessResponse, number>({
+        query: (arg) => `${arg}`,
+        serializeQueryArgs: serializer2,
+      }),
+    }),
+  })
+
+  it('Works via injectEndpoints', async () => {
+    expect(serializer2).not.toHaveBeenCalled()
+
+    await storeRef.store.dispatch(
+      injectedApi.endpoints.injectedQueryWithCustomSerializer.initiate(5),
+    )
+
+    expect(serializer2).toHaveBeenCalled()
+    expect(
+      storeRef.store.getState().api.queries[
+        'injectedQueryWithCustomSerializer-5'
+      ],
+    ).toBeTruthy()
+  })
+
+  test('Serializes a returned object for query args', async () => {
+    await storeRef.store.dispatch(
+      api.endpoints.queryWithCustomObjectSerializer.initiate({
+        id: 42,
+        client: dummyClient,
+      }),
+    )
+
+    expect(
+      storeRef.store.getState().api.queries[
+        'queryWithCustomObjectSerializer({"id":42})'
+      ],
+    ).toBeTruthy()
+  })
+
+  test('Serializes a returned primitive for query args', async () => {
+    await storeRef.store.dispatch(
+      api.endpoints.queryWithCustomNumberSerializer.initiate({
+        id: 42,
+        client: dummyClient,
+      }),
+    )
+
+    expect(
+      storeRef.store.getState().api.queries[
+        'queryWithCustomNumberSerializer(42)'
+      ],
+    ).toBeTruthy()
+  })
+
+  test('serializeQueryArgs + merge allows refetching as args change with same cache key', async () => {
+    const allItems = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i']
+    const PAGE_SIZE = 3
+
+    server.use(
+      http.get('https://example.com/listItems', ({ request }) => {
+        const url = new URL(request.url)
+        const pageString = url.searchParams.get('page')
+        const pageNum = parseInt(pageString || '0')
+
+        const results = paginate(allItems, PAGE_SIZE, pageNum)
+        return HttpResponse.json(results)
+      }),
+    )
+
+    // Page number shouldn't matter here, because the cache key ignores that.
+    // We just need to select the only cache entry.
+    const selectListItems = api.endpoints.listItems.select(0)
+
+    await storeRef.store.dispatch(api.endpoints.listItems.initiate(1))
+
+    const initialEntry = selectListItems(storeRef.store.getState())
+    expect(initialEntry.data).toEqual(['a', 'b', 'c'])
+
+    await storeRef.store.dispatch(api.endpoints.listItems.initiate(2))
+    const updatedEntry = selectListItems(storeRef.store.getState())
+    expect(updatedEntry.data).toEqual(['a', 'b', 'c', 'd', 'e', 'f'])
+  })
+
+  test('merge receives a meta object as an argument', async () => {
+    const allItems = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i']
+    const PAGE_SIZE = 3
+
+    server.use(
+      http.get('https://example.com/listItems2', ({ request }) => {
+        const url = new URL(request.url)
+        const pageString = url.searchParams.get('page')
+        const pageNum = parseInt(pageString || '0')
+
+        const results = paginate(allItems, PAGE_SIZE, pageNum)
+        return HttpResponse.json(results)
+      }),
+    )
+
+    const selectListItems = api.endpoints.listItems2.select(0)
+
+    await storeRef.store.dispatch(api.endpoints.listItems2.initiate(1))
+    await storeRef.store.dispatch(api.endpoints.listItems2.initiate(2))
+    const cacheEntry = selectListItems(storeRef.store.getState())
+
+    // Should have passed along the third arg from `merge` containing these fields
+    expect(cacheEntry.data?.meta).toEqual({
+      requestId: expect.any(String),
+      fulfilledTimeStamp: expect.any(Number),
+      arg: 2,
+      baseQueryMeta: expect.any(Object),
+    })
+  })
+})
+
+describe('timeout behavior', () => {
+  test('triggers TIMEOUT_ERROR', async () => {
+    const api = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com', timeout: 5 }),
+      endpoints: (build) => ({
+        query: build.query<unknown, void>({
+          query: () => '/success',
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    server.use(
+      http.get(
+        'https://example.com/success',
+        async () => {
+          await delay(50)
+          return HttpResponse.json({ value: 'failed' }, { status: 500 })
+        },
+        { once: true },
+      ),
+    )
+
+    const result = await storeRef.store.dispatch(api.endpoints.query.initiate())
+
+    expect(result?.error).toEqual({
+      status: 'TIMEOUT_ERROR',
+      error: expect.stringMatching(/^TimeoutError/),
+    })
+  })
+})
+
+describe('endpoint schemas', () => {
+  const schemaConverter: SchemaFailureConverter<
+    ReturnType<typeof fetchBaseQuery>
+  > = (error) => {
+    return {
+      status: 'CUSTOM_ERROR',
+      error: error.schemaName + ' failed validation',
+      data: error.issues,
+    }
+  }
+
+  const serializedSchemaError = {
+    name: 'SchemaError',
+    message: expect.any(String),
+    stack: expect.any(String),
+  } satisfies SerializedError
+
+  const onSchemaFailureGlobal = vi.fn<SchemaFailureHandler>()
+  const onSchemaFailureEndpoint = vi.fn<SchemaFailureHandler>()
+  afterEach(() => {
+    onSchemaFailureGlobal.mockClear()
+    onSchemaFailureEndpoint.mockClear()
+  })
+
+  function expectFailureHandlersToHaveBeenCalled({
+    schemaName,
+    value,
+    arg,
+  }: {
+    schemaName: `${SchemaType}Schema`
+    value: unknown
+    arg: unknown
+  }) {
+    for (const handler of [onSchemaFailureGlobal, onSchemaFailureEndpoint]) {
+      expect(handler).toHaveBeenCalledOnce()
+      const [namedError, info] = handler.mock.calls[0]
+      expect(namedError).toBeInstanceOf(NamedSchemaError)
+      expect(namedError.issues.length).toBeGreaterThan(0)
+      expect(namedError.value).toEqual(value)
+      expect(namedError.schemaName).toBe(schemaName)
+      expect(info.endpoint).toBe('query')
+      expect(info.type).toBe('query')
+      expect(info.arg).toEqual(arg)
+    }
+  }
+
+  interface SkipApiOptions {
+    globalSkip?: boolean
+    endpointSkip?: boolean
+    useArray?: boolean
+    globalCatch?: boolean
+    endpointCatch?: boolean
+  }
+
+  const apiOptions = (
+    type: SchemaType,
+    { useArray, globalSkip, globalCatch }: SkipApiOptions = {},
+  ) => ({
+    onSchemaFailure: onSchemaFailureGlobal,
+    skipSchemaValidation: useArray ? globalSkip && [type] : globalSkip,
+    catchSchemaFailure: globalCatch ? schemaConverter : undefined,
+  })
+
+  const endpointOptions = (
+    type: SchemaType,
+    { useArray, endpointSkip, endpointCatch }: SkipApiOptions = {},
+  ) => ({
+    onSchemaFailure: onSchemaFailureEndpoint,
+    skipSchemaValidation: useArray ? endpointSkip && [type] : endpointSkip,
+    catchSchemaFailure: endpointCatch ? schemaConverter : undefined,
+  })
+
+  const skipCases: [string, SkipApiOptions][] = [
+    ['globally', { globalSkip: true }],
+    ['on the endpoint', { endpointSkip: true }],
+    ['globally (array)', { globalSkip: true, useArray: true }],
+    ['on the endpoint (array)', { endpointSkip: true, useArray: true }],
+  ]
+
+  describe('argSchema', () => {
+    const makeApi = (opts?: SkipApiOptions) =>
+      createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        ...apiOptions('arg', opts),
+        endpoints: (build) => ({
+          query: build.query<unknown, { id: number }>({
+            query: ({ id }) => `/post/${id}`,
+            argSchema: v.object({ id: v.number() }),
+            ...endpointOptions('arg', opts),
+          }),
+        }),
+      })
+    test("can be used to validate the endpoint's arguments", async () => {
+      const api = makeApi()
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate({ id: 1 }),
+      )
+
+      expect(result?.error).toBeUndefined()
+
+      const invalidResult = await storeRef.store.dispatch(
+        // @ts-expect-error
+        api.endpoints.query.initiate({ id: '1' }),
+      )
+
+      expect(invalidResult?.error).toEqual(serializedSchemaError)
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'argSchema',
+        value: { id: '1' },
+        arg: { id: '1' },
+      })
+    })
+
+    test.each(skipCases)('can be skipped %s', async (_, arg) => {
+      const api = makeApi(arg)
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const result = await storeRef.store.dispatch(
+        // @ts-expect-error
+        api.endpoints.query.initiate({ id: '1' }),
+      )
+
+      expect(result?.error).toBeUndefined()
+    })
+    // we only need to test this once
+    test('endpoint overrides global skip', async () => {
+      const api = makeApi({ globalSkip: true, endpointSkip: false })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const result = await storeRef.store.dispatch(
+        // @ts-expect-error
+        api.endpoints.query.initiate({ id: '1' }),
+      )
+
+      expect(result?.error).toEqual(serializedSchemaError)
+    })
+
+    test('can be converted to a standard error object at global level', async () => {
+      const api = makeApi({ globalCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const result = await storeRef.store.dispatch(
+        // @ts-expect-error
+        api.endpoints.query.initiate({ id: '1' }),
+      )
+
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'argSchema failed validation',
+        data: expect.any(Array),
+      })
+
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'argSchema',
+        value: { id: '1' },
+        arg: { id: '1' },
+      })
+    })
+    test('can be converted to a standard error object at endpoint level', async () => {
+      const api = makeApi({ endpointCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+
+      const result = await storeRef.store.dispatch(
+        // @ts-expect-error
+        api.endpoints.query.initiate({ id: '1' }),
+      )
+
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'argSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'argSchema',
+        value: { id: '1' },
+        arg: { id: '1' },
+      })
+    })
+  })
+  describe('rawResponseSchema', () => {
+    const makeApi = (opts?: SkipApiOptions) =>
+      createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        ...apiOptions('rawResponse', opts),
+        endpoints: (build) => ({
+          query: build.query<{ success: boolean }, void>({
+            query: () => '/success',
+            rawResponseSchema: v.object({ value: v.literal('success!') }),
+            ...endpointOptions('rawResponse', opts),
+          }),
+        }),
+      })
+    test("can be used to validate the endpoint's raw result", async () => {
+      const api = makeApi()
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual(serializedSchemaError)
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'rawResponseSchema',
+        value: { value: 'success' },
+        arg: undefined,
+      })
+    })
+    test.each(skipCases)('can be skipped %s', async (_, arg) => {
+      const api = makeApi(arg)
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toBeUndefined()
+    })
+    test('can be skipped on the endpoint', async () => {
+      const api = makeApi({ endpointSkip: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toBeUndefined()
+    })
+    test('can be converted to a standard error object at global level', async () => {
+      const api = makeApi({ globalCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'rawResponseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'rawResponseSchema',
+        value: { value: 'success' },
+        arg: undefined,
+      })
+    })
+    test('can be converted to a standard error object at endpoint level', async () => {
+      const api = makeApi({ endpointCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'rawResponseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'rawResponseSchema',
+        value: { value: 'success' },
+        arg: undefined,
+      })
+    })
+  })
+  describe('responseSchema', () => {
+    const makeApi = (opts?: SkipApiOptions) =>
+      createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        ...apiOptions('response', opts),
+        endpoints: (build) => ({
+          query: build.query<{ success: boolean }, void>({
+            query: () => '/success',
+            transformResponse: () => ({ success: false }),
+            responseSchema: v.object({ success: v.literal(true) }),
+            ...endpointOptions('response', opts),
+          }),
+        }),
+      })
+    test("can be used to validate the endpoint's final result", async () => {
+      const api = makeApi()
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual(serializedSchemaError)
+
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'responseSchema',
+        value: { success: false },
+        arg: undefined,
+      })
+    })
+    test.each(skipCases)('can be skipped %s', async (_, arg) => {
+      const api = makeApi(arg)
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toBeUndefined()
+    })
+    test('can be converted to a standard error object at global level', async () => {
+      const api = makeApi({ globalCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'responseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'responseSchema',
+        value: { success: false },
+        arg: undefined,
+      })
+    })
+    test('can be converted to a standard error object at endpoint level', async () => {
+      const api = makeApi({ endpointCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'responseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'responseSchema',
+        value: { success: false },
+        arg: undefined,
+      })
+    })
+  })
+  describe('rawErrorResponseSchema', () => {
+    const makeApi = (opts?: SkipApiOptions) =>
+      createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        ...apiOptions('rawErrorResponse', opts),
+        endpoints: (build) => ({
+          query: build.query<{ success: boolean }, void>({
+            query: () => '/error',
+            rawErrorResponseSchema: v.object({
+              status: v.pipe(v.number(), v.minValue(400), v.maxValue(499)),
+              data: v.unknown(),
+            }),
+            ...endpointOptions('rawErrorResponse', opts),
+          }),
+        }),
+      })
+    test("can be used to validate the endpoint's raw error result", async () => {
+      const api = makeApi()
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual(serializedSchemaError)
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'rawErrorResponseSchema',
+        value: { status: 500, data: { value: 'error' } },
+        arg: undefined,
+      })
+    })
+    test.each(skipCases)('can be skipped %s', async (_, arg) => {
+      const api = makeApi(arg)
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).not.toEqual(serializedSchemaError)
+    })
+    test('can be converted to a standard error object at global level', async () => {
+      const api = makeApi({ globalCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'rawErrorResponseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'rawErrorResponseSchema',
+        value: { status: 500, data: { value: 'error' } },
+        arg: undefined,
+      })
+    })
+    test('can be converted to a standard error object at endpoint level', async () => {
+      const api = makeApi({ endpointCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'rawErrorResponseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'rawErrorResponseSchema',
+        value: { status: 500, data: { value: 'error' } },
+        arg: undefined,
+      })
+    })
+  })
+  describe('errorResponseSchema', () => {
+    const makeApi = (opts?: SkipApiOptions) =>
+      createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        ...apiOptions('errorResponse', opts),
+        endpoints: (build) => ({
+          query: build.query<{ success: boolean }, void>({
+            query: () => '/error',
+            transformErrorResponse: (error): FetchBaseQueryError => ({
+              status: 'CUSTOM_ERROR',
+              data: error,
+              error: 'whoops',
+            }),
+            errorResponseSchema: v.object({
+              status: v.literal('CUSTOM_ERROR'),
+              error: v.literal('oh no'),
+              data: v.unknown(),
+            }),
+            ...endpointOptions('errorResponse', opts),
+          }),
+        }),
+      })
+    test("can be used to validate the endpoint's final error result", async () => {
+      const api = makeApi()
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual(serializedSchemaError)
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'errorResponseSchema',
+        value: {
+          status: 'CUSTOM_ERROR',
+          error: 'whoops',
+          data: { status: 500, data: { value: 'error' } },
+        },
+        arg: undefined,
+      })
+    })
+    test.each(skipCases)('can be skipped %s', async (_, arg) => {
+      const api = makeApi(arg)
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).not.toEqual(serializedSchemaError)
+    })
+    test('can be converted to a standard error object at global level', async () => {
+      const api = makeApi({ globalCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'errorResponseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'errorResponseSchema',
+        value: {
+          status: 'CUSTOM_ERROR',
+          error: 'whoops',
+          data: { status: 500, data: { value: 'error' } },
+        },
+        arg: undefined,
+      })
+    })
+    test('can be converted to a standard error object at endpoint level', async () => {
+      const api = makeApi({ endpointCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'errorResponseSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'errorResponseSchema',
+        value: {
+          status: 'CUSTOM_ERROR',
+          error: 'whoops',
+          data: { status: 500, data: { value: 'error' } },
+        },
+        arg: undefined,
+      })
+    })
+  })
+  describe('metaSchema', () => {
+    const makeApi = (opts?: SkipApiOptions) =>
+      createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+        ...apiOptions('meta', opts),
+        endpoints: (build) => ({
+          query: build.query<{ success: boolean }, void>({
+            query: () => '/success',
+            metaSchema: v.object({
+              request: v.instance(Request),
+              response: v.instance(Response),
+              timestamp: v.number(),
+            }),
+            ...endpointOptions('meta', opts),
+          }),
+        }),
+      })
+    test("can be used to validate the endpoint's meta result", async () => {
+      const api = makeApi()
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual(serializedSchemaError)
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'metaSchema',
+        value: {
+          request: expect.any(Request),
+          response: expect.any(Response),
+        },
+        arg: undefined,
+      })
+    })
+    test.each(skipCases)('can be skipped %s', async (_, arg) => {
+      const api = makeApi(arg)
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toBeUndefined()
+    })
+    test('can be converted to a standard error object at global level', async () => {
+      const api = makeApi({ globalCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'metaSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'metaSchema',
+        value: {
+          request: expect.any(Request),
+          response: expect.any(Response),
+        },
+        arg: undefined,
+      })
+    })
+    test('can be converted to a standard error object at endpoint level', async () => {
+      const api = makeApi({ endpointCatch: true })
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const result = await storeRef.store.dispatch(
+        api.endpoints.query.initiate(),
+      )
+      expect(result?.error).toEqual({
+        status: 'CUSTOM_ERROR',
+        error: 'metaSchema failed validation',
+        data: expect.any(Array),
+      })
+      expectFailureHandlersToHaveBeenCalled({
+        schemaName: 'metaSchema',
+        value: {
+          request: expect.any(Request),
+          response: expect.any(Response),
+        },
+        arg: undefined,
+      })
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/defaultSerializeQueryArgs.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/defaultSerializeQueryArgs.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/defaultSerializeQueryArgs.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,122 @@
+import { defaultSerializeQueryArgs } from '@internal/query/defaultSerializeQueryArgs'
+
+const endpointDefinition: any = {}
+const endpointName = 'test'
+
+test('string arg', () => {
+  expect(
+    defaultSerializeQueryArgs({
+      endpointDefinition,
+      endpointName,
+      queryArgs: 'arg',
+    }),
+  ).toMatchInlineSnapshot(`"test("arg")"`)
+})
+
+test('number arg', () => {
+  expect(
+    defaultSerializeQueryArgs({
+      endpointDefinition,
+      endpointName,
+      queryArgs: 5,
+    }),
+  ).toMatchInlineSnapshot(`"test(5)"`)
+})
+
+test('bigint arg has non-default serialization (intead of throwing)', () => {
+  expect(
+    defaultSerializeQueryArgs({
+      endpointDefinition,
+      endpointName,
+      queryArgs: BigInt(10),
+    }),
+  ).toMatchInlineSnapshot(`"test({"$bigint":"10"})"`)
+})
+
+test('simple object arg is sorted', () => {
+  expect(
+    defaultSerializeQueryArgs({
+      endpointDefinition,
+      endpointName,
+      queryArgs: { name: 'arg', age: 5 },
+    }),
+  ).toMatchInlineSnapshot(`"test({"age":5,"name":"arg"})"`)
+})
+
+test('nested object arg is sorted recursively', () => {
+  expect(
+    defaultSerializeQueryArgs({
+      endpointDefinition,
+      endpointName,
+      queryArgs: { name: { last: 'Split', first: 'Banana' }, age: 5 },
+    }),
+  ).toMatchInlineSnapshot(
+    `"test({"age":5,"name":{"first":"Banana","last":"Split"}})"`,
+  )
+})
+
+test('Fully serializes a deeply nested object', () => {
+  const nestedObj = {
+    a: {
+      a1: {
+        a11: {
+          a111: 1,
+        },
+      },
+    },
+    b: {
+      b2: {
+        b21: 3,
+      },
+      b1: {
+        b11: 2,
+      },
+    },
+  }
+
+  const res = defaultSerializeQueryArgs({
+    endpointDefinition,
+    endpointName,
+    queryArgs: nestedObj,
+  })
+  expect(res).toMatchInlineSnapshot(
+    `"test({"a":{"a1":{"a11":{"a111":1}}},"b":{"b1":{"b11":2},"b2":{"b21":3}}})"`,
+  )
+})
+
+test('Caches results for plain objects', () => {
+  const testData = Array.from({ length: 10000 }).map((_, i) => {
+    return {
+      albumId: i,
+      id: i,
+      title: 'accusamus beatae ad facilis cum similique qui sunt',
+      url: 'https://via.placeholder.com/600/92c952',
+      thumbnailUrl: 'https://via.placeholder.com/150/92c952',
+    }
+  })
+
+  const data = {
+    testData,
+  }
+
+  const runWithTimer = (data: any) => {
+    const start = Date.now()
+    const res = defaultSerializeQueryArgs({
+      endpointDefinition,
+      endpointName,
+      queryArgs: data,
+    })
+    const end = Date.now()
+    const duration = end - start
+    return [res, duration] as const
+  }
+
+  const [res1, time1] = runWithTimer(data)
+  const [res2, time2] = runWithTimer(data)
+
+  expect(res1).toBe(res2)
+  expect(time2).toBeLessThanOrEqual(time1)
+  // Locally, stringifying 10K items takes 25-30ms.
+  // Assuming the WeakMap cache hit, this _should_ be 0
+  expect(time2).toBeLessThan(2)
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/devWarnings.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/devWarnings.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/devWarnings.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,552 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import { configureStore } from '@reduxjs/toolkit'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+
+const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)
+
+const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+beforeEach(() => {
+  vi.stubEnv('NODE_ENV', 'development')
+})
+
+afterEach(() => {
+  vi.unstubAllEnvs()
+  vi.clearAllMocks()
+})
+
+afterAll(() => {
+  vi.restoreAllMocks()
+  vi.unstubAllEnvs()
+})
+
+const baseUrl = 'https://example.com'
+
+function createApis() {
+  const api1 = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl }),
+    endpoints: (builder) => ({
+      q1: builder.query({ query: () => '/success' }),
+    }),
+  })
+
+  const api1_2 = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl }),
+    endpoints: (builder) => ({
+      q1: builder.query({ query: () => '/success' }),
+    }),
+  })
+
+  const api2 = createApi({
+    reducerPath: 'api2',
+    baseQuery: fetchBaseQuery({ baseUrl }),
+    endpoints: (builder) => ({
+      q1: builder.query({ query: () => '/success' }),
+    }),
+  })
+  return [api1, api1_2, api2] as const
+}
+
+let [api1, api1_2, api2] = createApis()
+beforeEach(() => {
+  ;[api1, api1_2, api2] = createApis()
+})
+
+const reMatchMissingMiddlewareError =
+  /Warning: Middleware for RTK-Query API at reducerPath "api" has not been added to the store/
+
+describe('missing middleware', () => {
+  test.each([
+    ['development', true],
+    ['production', false],
+  ])('%s warns if middleware is missing: %s', (env, shouldWarn) => {
+    vi.stubEnv('NODE_ENV', env)
+
+    const store = configureStore({
+      reducer: { [api1.reducerPath]: api1.reducer },
+    })
+    const doDispatch = () => {
+      store.dispatch(api1.endpoints.q1.initiate(undefined))
+    }
+    if (shouldWarn) {
+      expect(doDispatch).toThrowError(reMatchMissingMiddlewareError)
+    } else {
+      expect(doDispatch).not.toThrowError()
+    }
+  })
+
+  test('does not warn if middleware is not missing', () => {
+    const store = configureStore({
+      reducer: { [api1.reducerPath]: api1.reducer },
+      middleware: (gdm) => gdm().concat(api1.middleware),
+    })
+    store.dispatch(api1.endpoints.q1.initiate(undefined))
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+  })
+
+  test('warns only once per api', () => {
+    const store = configureStore({
+      reducer: { [api1.reducerPath]: api1.reducer },
+    })
+    const doDispatch = () => {
+      store.dispatch(api1.endpoints.q1.initiate(undefined))
+    }
+
+    expect(doDispatch).toThrowError(reMatchMissingMiddlewareError)
+    expect(doDispatch).not.toThrowError()
+  })
+
+  test('warns multiple times for multiple apis', () => {
+    const store = configureStore({
+      reducer: {
+        [api1.reducerPath]: api1.reducer,
+        [api2.reducerPath]: api2.reducer,
+      },
+    })
+    const doDispatch1 = () => {
+      store.dispatch(api1.endpoints.q1.initiate(undefined))
+    }
+    const doDispatch2 = () => {
+      store.dispatch(api2.endpoints.q1.initiate(undefined))
+    }
+    expect(doDispatch1).toThrowError(reMatchMissingMiddlewareError)
+    expect(doDispatch2).toThrowError(
+      /Warning: Middleware for RTK-Query API at reducerPath "api2" has not been added to the store/,
+    )
+  })
+})
+
+describe('missing reducer', () => {
+  describe.each([
+    ['development', true],
+    ['production', false],
+  ])('%s warns if reducer is missing: %s', (env, shouldWarn) => {
+    beforeEach(() => {
+      vi.stubEnv('NODE_ENV', env)
+    })
+
+    afterAll(() => {
+      vi.unstubAllEnvs()
+    })
+
+    test('middleware not crashing if reducer is missing', async () => {
+      const store = configureStore({
+        reducer: { x: () => 0 },
+        // @ts-expect-error
+        middleware: (gdm) => gdm().concat(api1.middleware),
+      })
+      await store.dispatch(api1.endpoints.q1.initiate(undefined))
+
+      expect(process.env.NODE_ENV).toBe(env)
+    })
+
+    test(`warning behavior`, () => {
+      const store = configureStore({
+        reducer: { x: () => 0 },
+        // @ts-expect-error
+        middleware: (gdm) => gdm().concat(api1.middleware),
+      })
+      // @ts-expect-error
+      api1.endpoints.q1.select(undefined)(store.getState())
+
+      expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+      expect(process.env.NODE_ENV).toBe(env)
+
+      if (shouldWarn) {
+        expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+        expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+          'Error: No data found at `state.api`. Did you forget to add the reducer to the store?',
+        )
+      } else {
+        expect(consoleErrorSpy).not.toHaveBeenCalled()
+      }
+    })
+  })
+
+  test('does not warn if reducer is not missing', () => {
+    const store = configureStore({
+      reducer: { [api1.reducerPath]: api1.reducer },
+      middleware: (gdm) => gdm().concat(api1.middleware),
+    })
+    api1.endpoints.q1.select(undefined)(store.getState())
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+  })
+
+  test('warns only once per api', () => {
+    const store = configureStore({
+      reducer: { x: () => 0 },
+      // @ts-expect-error
+      middleware: (gdm) => gdm().concat(api1.middleware),
+    })
+    // @ts-expect-error
+    api1.endpoints.q1.select(undefined)(store.getState())
+    // @ts-expect-error
+    api1.endpoints.q1.select(undefined)(store.getState())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      'Error: No data found at `state.api`. Did you forget to add the reducer to the store?',
+    )
+  })
+
+  test('warns multiple times for multiple apis', () => {
+    const store = configureStore({
+      reducer: { x: () => 0 },
+      // @ts-expect-error
+      middleware: (gdm) => gdm().concat(api1.middleware),
+    })
+    // @ts-expect-error
+    api1.endpoints.q1.select(undefined)(store.getState())
+    // @ts-expect-error
+    api2.endpoints.q1.select(undefined)(store.getState())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledTimes(2)
+
+    expect(consoleErrorSpy).toHaveBeenNthCalledWith(
+      1,
+      'Error: No data found at `state.api`. Did you forget to add the reducer to the store?',
+    )
+
+    expect(consoleErrorSpy).toHaveBeenNthCalledWith(
+      2,
+      'Error: No data found at `state.api2`. Did you forget to add the reducer to the store?',
+    )
+  })
+})
+
+test('warns for reducer and also throws error if everything is missing', async () => {
+  const store = configureStore({
+    reducer: { x: () => 0 },
+  })
+  // @ts-expect-error
+  api1.endpoints.q1.select(undefined)(store.getState())
+  const doDispatch = () => {
+    store.dispatch(api1.endpoints.q1.initiate(undefined))
+  }
+  expect(doDispatch).toThrowError(reMatchMissingMiddlewareError)
+
+  expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+  expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+  expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+    'Error: No data found at `state.api`. Did you forget to add the reducer to the store?',
+  )
+})
+
+describe('warns on multiple apis using the same `reducerPath`', () => {
+  test('common: two apis, same order', async () => {
+    const store = configureStore({
+      reducer: {
+        // TS 5.3 now errors on identical object keys. We want to force that behavior.
+        // @ts-ignore
+        [api1.reducerPath]: api1.reducer,
+        // @ts-ignore
+        [api1_2.reducerPath]: api1_2.reducer,
+      },
+      middleware: (gDM) => gDM().concat(api1.middleware, api1_2.middleware),
+    })
+    await store.dispatch(api1.endpoints.q1.initiate(undefined))
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+    expect(consoleWarnSpy).toHaveBeenCalledOnce()
+
+    // only second api prints
+    expect(consoleWarnSpy).toHaveBeenLastCalledWith(
+      `There is a mismatch between slice and middleware for the reducerPath "api".
+You can only have one api per reducer path, this will lead to crashes in various situations!
+If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`,
+    )
+  })
+
+  test('common: two apis, opposing order', async () => {
+    const store = configureStore({
+      reducer: {
+        // @ts-ignore
+        [api1.reducerPath]: api1.reducer,
+        // @ts-ignore
+        [api1_2.reducerPath]: api1_2.reducer,
+      },
+      middleware: (gDM) => gDM().concat(api1_2.middleware, api1.middleware),
+    })
+    await store.dispatch(api1.endpoints.q1.initiate(undefined))
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+    expect(consoleWarnSpy).toHaveBeenCalledTimes(2)
+
+    // both apis print
+    expect(consoleWarnSpy).toHaveBeenNthCalledWith(
+      1,
+      `There is a mismatch between slice and middleware for the reducerPath "api".
+You can only have one api per reducer path, this will lead to crashes in various situations!
+If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`,
+    )
+
+    expect(consoleWarnSpy).toHaveBeenNthCalledWith(
+      2,
+      `There is a mismatch between slice and middleware for the reducerPath "api".
+You can only have one api per reducer path, this will lead to crashes in various situations!
+If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`,
+    )
+  })
+
+  test('common: two apis, only first middleware', async () => {
+    const store = configureStore({
+      reducer: {
+        // @ts-ignore
+        [api1.reducerPath]: api1.reducer,
+        // @ts-ignore
+        [api1_2.reducerPath]: api1_2.reducer,
+      },
+      middleware: (gDM) => gDM().concat(api1.middleware),
+    })
+    await store.dispatch(api1.endpoints.q1.initiate(undefined))
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+    expect(consoleWarnSpy).toHaveBeenCalledOnce()
+
+    expect(consoleWarnSpy).toHaveBeenLastCalledWith(
+      `There is a mismatch between slice and middleware for the reducerPath "api".
+You can only have one api per reducer path, this will lead to crashes in various situations!
+If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`,
+    )
+  })
+
+  /**
+   * This is the one edge case that we currently cannot detect:
+   * Multiple apis with the same reducer key and only the middleware of the last api is being used.
+   *
+   * It would be great to support this case as well, but for now:
+   * "It is what it is."
+   */
+  test.todo('common: two apis, only second middleware', async () => {
+    const store = configureStore({
+      reducer: {
+        // @ts-ignore
+        [api1.reducerPath]: api1.reducer,
+        // @ts-ignore
+        [api1_2.reducerPath]: api1_2.reducer,
+      },
+      middleware: (gDM) => gDM().concat(api1_2.middleware),
+    })
+    await store.dispatch(api1.endpoints.q1.initiate(undefined))
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+
+    expect(consoleWarnSpy).toHaveBeenCalledOnce()
+
+    expect(consoleWarnSpy).toHaveBeenLastCalledWith(
+      `There is a mismatch between slice and middleware for the reducerPath "api".
+You can only have one api per reducer path, this will lead to crashes in various situations!
+If you have multiple apis, you *have* to specify the reducerPath option when using createApi!`,
+    )
+  })
+})
+
+describe('`console.error` on unhandled errors during `initiate`', () => {
+  test('error thrown in `baseQuery`', async () => {
+    const api = createApi({
+      baseQuery(): { data: any } {
+        throw new Error('this was kinda expected')
+      },
+      endpoints: (build) => ({
+        baseQuery: build.query<any, void>({ query() {} }),
+      }),
+    })
+    const store = configureStore({
+      reducer: { [api.reducerPath]: api.reducer },
+      middleware: (gdm) => gdm().concat(api.middleware),
+    })
+    await store.dispatch(api.endpoints.baseQuery.initiate())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `An unhandled error occurred processing a request for the endpoint "baseQuery".
+In the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+      Error('this was kinda expected'),
+    )
+  })
+
+  test('error thrown in `queryFn`', async () => {
+    const api = createApi({
+      baseQuery() {
+        return { data: {} }
+      },
+      endpoints: (build) => ({
+        queryFn: build.query<any, void>({
+          queryFn() {
+            throw new Error('this was kinda expected')
+          },
+        }),
+      }),
+    })
+    const store = configureStore({
+      reducer: { [api.reducerPath]: api.reducer },
+      middleware: (gdm) => gdm().concat(api.middleware),
+    })
+    await store.dispatch(api.endpoints.queryFn.initiate())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `An unhandled error occurred processing a request for the endpoint "queryFn".
+In the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+      Error('this was kinda expected'),
+    )
+  })
+
+  test('error thrown in `transformResponse`', async () => {
+    const api = createApi({
+      baseQuery() {
+        return { data: {} }
+      },
+      endpoints: (build) => ({
+        transformRspn: build.query<any, void>({
+          query() {},
+          transformResponse() {
+            throw new Error('this was kinda expected')
+          },
+        }),
+      }),
+    })
+    const store = configureStore({
+      reducer: { [api.reducerPath]: api.reducer },
+      middleware: (gdm) => gdm().concat(api.middleware),
+    })
+    await store.dispatch(api.endpoints.transformRspn.initiate())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `An unhandled error occurred processing a request for the endpoint "transformRspn".
+In the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+      Error('this was kinda expected'),
+    )
+  })
+
+  test('error thrown in `transformErrorResponse`', async () => {
+    const api = createApi({
+      baseQuery() {
+        return { error: {} }
+      },
+      endpoints: (build) => ({
+        // @ts-ignore TS doesn't like `() => never` for `tER`
+        transformErRspn: build.query<number, void>({
+          // @ts-ignore TS doesn't like `() => never` for `tER`
+          query: () => '/dummy',
+          // @ts-ignore TS doesn't like `() => never` for `tER`
+          transformErrorResponse() {
+            throw new Error('this was kinda expected')
+          },
+        }),
+      }),
+    })
+    const store = configureStore({
+      reducer: { [api.reducerPath]: api.reducer },
+      middleware: (gdm) => gdm().concat(api.middleware),
+    })
+    await store.dispatch(api.endpoints.transformErRspn.initiate())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `An unhandled error occurred processing a request for the endpoint "transformErRspn".
+In the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+      Error('this was kinda expected'),
+    )
+  })
+
+  test('`fetchBaseQuery`: error thrown in `prepareHeaders`', async () => {
+    const api = createApi({
+      baseQuery: fetchBaseQuery({
+        baseUrl,
+        prepareHeaders() {
+          throw new Error('this was kinda expected')
+        },
+      }),
+      endpoints: (build) => ({
+        prep: build.query<any, void>({
+          query() {
+            return '/success'
+          },
+        }),
+      }),
+    })
+    const store = configureStore({
+      reducer: { [api.reducerPath]: api.reducer },
+      middleware: (gdm) => gdm().concat(api.middleware),
+    })
+    await store.dispatch(api.endpoints.prep.initiate())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `An unhandled error occurred processing a request for the endpoint "prep".
+In the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+      Error('this was kinda expected'),
+    )
+  })
+
+  test('`fetchBaseQuery`: error thrown in `validateStatus`', async () => {
+    const api = createApi({
+      baseQuery: fetchBaseQuery({
+        baseUrl,
+      }),
+      endpoints: (build) => ({
+        val: build.query<any, void>({
+          query() {
+            return {
+              url: '/success',
+
+              validateStatus() {
+                throw new Error('this was kinda expected')
+              },
+            }
+          },
+        }),
+      }),
+    })
+    const store = configureStore({
+      reducer: { [api.reducerPath]: api.reducer },
+      middleware: (gdm) => gdm().concat(api.middleware),
+    })
+    await store.dispatch(api.endpoints.val.initiate())
+
+    expect(consoleWarnSpy).not.toHaveBeenCalled()
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `An unhandled error occurred processing a request for the endpoint "val".
+In the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+      Error('this was kinda expected'),
+    )
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/errorHandling.test-d.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/errorHandling.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/errorHandling.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,52 @@
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+import { useState } from 'react'
+
+const mockSuccessResponse = { value: 'success' }
+
+const api = createApi({
+  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+  endpoints: (build) => ({
+    update: build.mutation<typeof mockSuccessResponse, any>({
+      query: () => ({ url: 'success' }),
+    }),
+    failedUpdate: build.mutation<typeof mockSuccessResponse, any>({
+      query: () => ({ url: 'error' }),
+    }),
+  }),
+})
+
+describe('type tests', () => {
+  test('a mutation is unwrappable and has the correct types', () => {
+    function User() {
+      const [manualError, setManualError] = useState<any>()
+
+      const [update, { isLoading, data, error }] =
+        api.endpoints.update.useMutation()
+
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="data">{JSON.stringify(data)}</div>
+          <div data-testid="error">{JSON.stringify(error)}</div>
+          <div data-testid="manuallySetError">
+            {JSON.stringify(manualError)}
+          </div>
+          <button
+            onClick={() => {
+              update({ name: 'hello' })
+                .unwrap()
+                .then((result) => {
+                  expectTypeOf(result).toEqualTypeOf(mockSuccessResponse)
+
+                  setManualError(undefined)
+                })
+                .catch(setManualError)
+            }}
+          >
+            Update User
+          </button>
+        </div>
+      )
+    }
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/errorHandling.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/errorHandling.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/errorHandling.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,657 @@
+import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit'
+import type { BaseQueryFn, BaseQueryApi } from '@reduxjs/toolkit/query/react'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+import {
+  act,
+  fireEvent,
+  render,
+  renderHook,
+  screen,
+  waitFor,
+} from '@testing-library/react'
+import type { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'
+import axios from 'axios'
+import { HttpResponse, http } from 'msw'
+import * as React from 'react'
+import { useDispatch } from 'react-redux'
+import { hookWaitFor, setupApiStore } from '@internal/tests/utils/helpers'
+import { server } from '@internal/query/tests/mocks/server'
+
+const baseQuery = fetchBaseQuery({ baseUrl: 'https://example.com' })
+
+const api = createApi({
+  baseQuery,
+  endpoints(build) {
+    return {
+      query: build.query({ query: () => '/query' }),
+      mutation: build.mutation({
+        query: () => ({ url: '/mutation', method: 'POST' }),
+      }),
+    }
+  },
+})
+
+const storeRef = setupApiStore(api)
+
+const failQueryOnce = http.get(
+  '/query',
+  () => HttpResponse.json({ value: 'failed' }, { status: 500 }),
+  { once: true },
+)
+
+describe('fetchBaseQuery', () => {
+  let commonBaseQueryApiArgs: BaseQueryApi = {} as any
+  beforeEach(() => {
+    const abortController = new AbortController()
+    commonBaseQueryApiArgs = {
+      signal: abortController.signal,
+      abort: (reason) =>
+        //@ts-ignore
+        abortController.abort(reason),
+      dispatch: storeRef.store.dispatch,
+      getState: storeRef.store.getState,
+      extra: undefined,
+      type: 'query',
+      endpoint: 'doesntmatterhere',
+    }
+  })
+  test('success', async () => {
+    await expect(
+      baseQuery('/success', commonBaseQueryApiArgs, {}),
+    ).resolves.toEqual({
+      data: { value: 'success' },
+      meta: {
+        request: expect.any(Object),
+        response: expect.any(Object),
+      },
+    })
+  })
+  test('error', async () => {
+    server.use(failQueryOnce)
+    await expect(
+      baseQuery('/error', commonBaseQueryApiArgs, {}),
+    ).resolves.toEqual({
+      error: {
+        data: { value: 'error' },
+        status: 500,
+      },
+      meta: {
+        request: expect.any(Object),
+        response: expect.any(Object),
+      },
+    })
+  })
+})
+
+describe('query error handling', () => {
+  test('success', async () => {
+    server.use(
+      http.get('https://example.com/query', () =>
+        HttpResponse.json({ value: 'success' }),
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.query.useQuery({}), {
+      wrapper: storeRef.wrapper,
+    })
+
+    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())
+    expect(result.current).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: false,
+        isSuccess: true,
+        data: { value: 'success' },
+      }),
+    )
+  })
+
+  test('error', async () => {
+    server.use(
+      http.get('https://example.com/query', () =>
+        HttpResponse.json({ value: 'error' }, { status: 500 }),
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.query.useQuery({}), {
+      wrapper: storeRef.wrapper,
+    })
+
+    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())
+    expect(result.current).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: true,
+        isSuccess: false,
+        error: {
+          status: 500,
+          data: { value: 'error' },
+        },
+      }),
+    )
+  })
+
+  test('success -> error', async () => {
+    server.use(
+      http.get('https://example.com/query', () =>
+        HttpResponse.json({ value: 'success' }),
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.query.useQuery({}), {
+      wrapper: storeRef.wrapper,
+    })
+
+    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())
+    expect(result.current).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: false,
+        isSuccess: true,
+        data: { value: 'success' },
+      }),
+    )
+
+    server.use(
+      http.get(
+        'https://example.com/query',
+        () => HttpResponse.json({ value: 'error' }, { status: 500 }),
+        { once: true },
+      ),
+    )
+
+    act(() => void result.current.refetch())
+
+    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())
+    expect(result.current).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: true,
+        isSuccess: false,
+        error: {
+          status: 500,
+          data: { value: 'error' },
+        },
+        // last data will stay available
+        data: { value: 'success' },
+      }),
+    )
+  })
+
+  test('error -> success', async () => {
+    server.use(
+      http.get('https://example.com/query', () =>
+        HttpResponse.json({ value: 'success' }),
+      ),
+    )
+    server.use(
+      http.get(
+        'https://example.com/query',
+        () => HttpResponse.json({ value: 'error' }, { status: 500 }),
+        { once: true },
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.query.useQuery({}), {
+      wrapper: storeRef.wrapper,
+    })
+
+    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())
+    expect(result.current).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: true,
+        isSuccess: false,
+        error: {
+          status: 500,
+          data: { value: 'error' },
+        },
+      }),
+    )
+
+    act(() => void result.current.refetch())
+
+    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())
+    expect(result.current).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: false,
+        isSuccess: true,
+        data: { value: 'success' },
+      }),
+    )
+  })
+})
+
+describe('mutation error handling', () => {
+  test('success', async () => {
+    server.use(
+      http.post('https://example.com/mutation', () =>
+        HttpResponse.json({ value: 'success' }),
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.mutation.useMutation(), {
+      wrapper: storeRef.wrapper,
+    })
+
+    const [trigger] = result.current
+
+    act(() => void trigger({}))
+
+    await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+    expect(result.current[1]).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: false,
+        isSuccess: true,
+        data: { value: 'success' },
+      }),
+    )
+  })
+
+  test('error', async () => {
+    server.use(
+      http.post('https://example.com/mutation', () =>
+        HttpResponse.json({ value: 'error' }, { status: 500 }),
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.mutation.useMutation(), {
+      wrapper: storeRef.wrapper,
+    })
+
+    const [trigger] = result.current
+
+    act(() => void trigger({}))
+
+    await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+    expect(result.current[1]).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: true,
+        isSuccess: false,
+        error: {
+          status: 500,
+          data: { value: 'error' },
+        },
+      }),
+    )
+  })
+
+  test('success -> error', async () => {
+    server.use(
+      http.post('https://example.com/mutation', () =>
+        HttpResponse.json({ value: 'success' }),
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.mutation.useMutation(), {
+      wrapper: storeRef.wrapper,
+    })
+
+    {
+      const [trigger] = result.current
+
+      act(() => void trigger({}))
+
+      await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+      expect(result.current[1]).toEqual(
+        expect.objectContaining({
+          isLoading: false,
+          isError: false,
+          isSuccess: true,
+          data: { value: 'success' },
+        }),
+      )
+    }
+
+    server.use(
+      http.post(
+        'https://example.com/mutation',
+        () => HttpResponse.json({ value: 'error' }, { status: 500 }),
+        { once: true },
+      ),
+    )
+
+    {
+      const [trigger] = result.current
+
+      act(() => void trigger({}))
+
+      await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+      expect(result.current[1]).toEqual(
+        expect.objectContaining({
+          isLoading: false,
+          isError: true,
+          isSuccess: false,
+          error: {
+            status: 500,
+            data: { value: 'error' },
+          },
+        }),
+      )
+      expect(result.current[1].data).toBeUndefined()
+    }
+  })
+
+  test('error -> success', async () => {
+    server.use(
+      http.post('https://example.com/mutation', () =>
+        HttpResponse.json({ value: 'success' }),
+      ),
+    )
+    server.use(
+      http.post(
+        'https://example.com/mutation',
+        () => HttpResponse.json({ value: 'error' }, { status: 500 }),
+        { once: true },
+      ),
+    )
+
+    const { result } = renderHook(() => api.endpoints.mutation.useMutation(), {
+      wrapper: storeRef.wrapper,
+    })
+
+    {
+      const [trigger] = result.current
+
+      act(() => void trigger({}))
+
+      await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+      expect(result.current[1]).toEqual(
+        expect.objectContaining({
+          isLoading: false,
+          isError: true,
+          isSuccess: false,
+          error: {
+            status: 500,
+            data: { value: 'error' },
+          },
+        }),
+      )
+    }
+
+    {
+      const [trigger] = result.current
+
+      act(() => void trigger({}))
+
+      await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+      expect(result.current[1]).toEqual(
+        expect.objectContaining({
+          isLoading: false,
+          isError: false,
+          isSuccess: true,
+        }),
+      )
+      expect(result.current[1].error).toBeUndefined()
+    }
+  })
+})
+
+describe('custom axios baseQuery', () => {
+  const axiosBaseQuery =
+    (
+      { baseUrl }: { baseUrl: string } = { baseUrl: '' },
+    ): BaseQueryFn<
+      {
+        url: string
+        method?: AxiosRequestConfig['method']
+        data?: AxiosRequestConfig['data']
+      },
+      unknown,
+      unknown,
+      unknown,
+      { response: AxiosResponse; request: AxiosRequestConfig }
+    > =>
+    async ({ url, method, data }) => {
+      const config = { url: baseUrl + url, method, data }
+      try {
+        const result = await axios(config)
+        return {
+          data: result.data,
+          meta: { request: config, response: result },
+        }
+      } catch (axiosError) {
+        const err = axiosError as AxiosError
+        return {
+          error: {
+            status: err.response?.status,
+            data: err.response?.data,
+          },
+          meta: { request: config, response: err.response as AxiosResponse },
+        }
+      }
+    }
+
+  type SuccessResponse = { value: 'success' }
+  const api = createApi({
+    baseQuery: axiosBaseQuery({
+      baseUrl: 'https://example.com',
+    }),
+    endpoints(build) {
+      return {
+        query: build.query<SuccessResponse, void>({
+          query: () => ({ url: '/success', method: 'get' }),
+          transformResponse: (result: SuccessResponse, meta) => {
+            return { ...result, metaResponseData: meta?.response.data }
+          },
+        }),
+        mutation: build.mutation<SuccessResponse, any>({
+          query: () => ({ url: '/success', method: 'post' }),
+        }),
+      }
+    },
+  })
+
+  const storeRef = setupApiStore(api)
+
+  test('axiosBaseQuery transformResponse uses its custom meta format', async () => {
+    const result = await storeRef.store.dispatch(api.endpoints.query.initiate())
+
+    expect(result.data).toEqual({
+      value: 'success',
+      metaResponseData: { value: 'success' },
+    })
+  })
+
+  test('axios errors behave as expected', async () => {
+    server.use(
+      http.get('https://example.com/success', () =>
+        HttpResponse.json({ value: 'error' }, { status: 500 }),
+      ),
+    )
+    const { result } = renderHook(() => api.endpoints.query.useQuery(), {
+      wrapper: storeRef.wrapper,
+    })
+
+    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())
+    expect(result.current).toEqual(
+      expect.objectContaining({
+        isLoading: false,
+        isError: true,
+        isSuccess: false,
+        error: { status: 500, data: { value: 'error' } },
+      }),
+    )
+  })
+})
+
+describe('error handling in a component', () => {
+  const mockErrorResponse = { value: 'error', very: 'mean' }
+  const mockSuccessResponse = { value: 'success' }
+
+  const api = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+    endpoints: (build) => ({
+      update: build.mutation<typeof mockSuccessResponse, any>({
+        query: () => ({ url: 'success' }),
+      }),
+      failedUpdate: build.mutation<typeof mockSuccessResponse, any>({
+        query: () => ({ url: 'error' }),
+      }),
+    }),
+  })
+  const storeRef = setupApiStore(api)
+
+  test('a mutation is unwrappable and has the correct types', async () => {
+    server.use(
+      http.get(
+        'https://example.com/success',
+        () => HttpResponse.json(mockErrorResponse, { status: 500 }),
+        { once: true },
+      ),
+    )
+
+    function User() {
+      const [manualError, setManualError] = React.useState<any>()
+      const [update, { isLoading, data, error }] =
+        api.endpoints.update.useMutation()
+
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="data">{JSON.stringify(data)}</div>
+          <div data-testid="error">{JSON.stringify(error)}</div>
+          <div data-testid="manuallySetError">
+            {JSON.stringify(manualError)}
+          </div>
+          <button
+            onClick={() => {
+              update({ name: 'hello' })
+                .unwrap()
+                .then((result) => {
+                  setManualError(undefined)
+                })
+                .catch((error) => act(() => setManualError(error)))
+            }}
+          >
+            Update User
+          </button>
+        </div>
+      )
+    }
+
+    render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    fireEvent.click(screen.getByText('Update User'))
+    expect(screen.getByTestId('isLoading').textContent).toBe('true')
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+
+    // Make sure the hook and the unwrapped action return the same things in an error state
+    await waitFor(() =>
+      expect(screen.getByTestId('error').textContent).toEqual(
+        screen.getByTestId('manuallySetError').textContent,
+      ),
+    )
+
+    fireEvent.click(screen.getByText('Update User'))
+    expect(screen.getByTestId('isLoading').textContent).toBe('true')
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('error').textContent).toBeFalsy(),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('manuallySetError').textContent).toBeFalsy(),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('data').textContent).toEqual(
+        JSON.stringify(mockSuccessResponse),
+      ),
+    )
+  })
+
+  for (const track of [true, false]) {
+    test(`an un-subscribed mutation will still return something useful (success case, track: ${track})`, async () => {
+      const hook = renderHook(useDispatch, { wrapper: storeRef.wrapper })
+
+      const dispatch = hook.result.current as ThunkDispatch<
+        any,
+        any,
+        UnknownAction
+      >
+      let mutationqueryFulfilled: ReturnType<
+        ReturnType<typeof api.endpoints.update.initiate>
+      >
+      act(() => {
+        mutationqueryFulfilled = dispatch(
+          api.endpoints.update.initiate({}, { track }),
+        )
+      })
+      const result = await mutationqueryFulfilled!
+      expect(result).toMatchObject({
+        data: { value: 'success' },
+      })
+    })
+
+    test(`an un-subscribed mutation will still return something useful (error case, track: ${track})`, async () => {
+      const hook = renderHook(useDispatch, { wrapper: storeRef.wrapper })
+
+      const dispatch = hook.result.current as ThunkDispatch<
+        any,
+        any,
+        UnknownAction
+      >
+      let mutationqueryFulfilled: ReturnType<
+        ReturnType<typeof api.endpoints.failedUpdate.initiate>
+      >
+      act(() => {
+        mutationqueryFulfilled = dispatch(
+          api.endpoints.failedUpdate.initiate({}, { track }),
+        )
+      })
+      const result = await mutationqueryFulfilled!
+      expect(result).toMatchObject({
+        error: {
+          status: 500,
+          data: { value: 'error' },
+        },
+      })
+    })
+    test(`an un-subscribed mutation will still be unwrappable (success case), track: ${track}`, async () => {
+      const hook = renderHook(useDispatch, { wrapper: storeRef.wrapper })
+
+      const dispatch = hook.result.current as ThunkDispatch<
+        any,
+        any,
+        UnknownAction
+      >
+      let mutationqueryFulfilled: ReturnType<
+        ReturnType<typeof api.endpoints.update.initiate>
+      >
+      act(() => {
+        mutationqueryFulfilled = dispatch(
+          api.endpoints.update.initiate({}, { track }),
+        )
+      })
+      const result = await mutationqueryFulfilled!.unwrap()
+      expect(result).toMatchObject({
+        value: 'success',
+      })
+    })
+
+    test(`an un-subscribed mutation will still be unwrappable (error case, track: ${track})`, async () => {
+      const hook = renderHook(useDispatch, { wrapper: storeRef.wrapper })
+
+      const dispatch = hook.result.current as ThunkDispatch<
+        any,
+        any,
+        UnknownAction
+      >
+      let mutationqueryFulfilled: ReturnType<
+        ReturnType<typeof api.endpoints.failedUpdate.initiate>
+      >
+      act(() => {
+        mutationqueryFulfilled = dispatch(
+          api.endpoints.failedUpdate.initiate({}, { track }),
+        )
+      })
+      const unwrappedPromise = mutationqueryFulfilled!.unwrap()
+      await expect(unwrappedPromise).rejects.toMatchObject({
+        status: 500,
+        data: { value: 'error' },
+      })
+    })
+  }
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/fakeBaseQuery.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/fakeBaseQuery.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/fakeBaseQuery.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,148 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import { configureStore } from '@reduxjs/toolkit'
+import { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query'
+
+type CustomErrorType = { type: 'Custom' }
+
+const api = createApi({
+  baseQuery: fakeBaseQuery<CustomErrorType>(),
+  endpoints: (build) => ({
+    withQuery: build.query<string, string>({
+      // @ts-expect-error
+      query(arg: string) {
+        return `resultFrom(${arg})`
+      },
+      // @ts-expect-error
+      transformResponse(response) {
+        return response.wrappedByBaseQuery
+      },
+    }),
+    withQueryFn: build.query<string, string>({
+      queryFn(arg: string) {
+        return { data: `resultFrom(${arg})` }
+      },
+    }),
+    withInvalidDataQueryFn: build.query<string, string>({
+      // @ts-expect-error
+      queryFn(arg: string) {
+        return { data: 5 }
+      },
+    }),
+    withErrorQueryFn: build.query<string, string>({
+      queryFn(arg: string) {
+        return { error: { type: 'Custom' } }
+      },
+    }),
+    withInvalidErrorQueryFn: build.query<string, string>({
+      // @ts-expect-error
+      queryFn(arg: string) {
+        return { error: 5 }
+      },
+    }),
+    withAsyncQueryFn: build.query<string, string>({
+      async queryFn(arg: string) {
+        return { data: `resultFrom(${arg})` }
+      },
+    }),
+    withInvalidDataAsyncQueryFn: build.query<string, string>({
+      // @ts-expect-error
+      async queryFn(arg: string) {
+        return { data: 5 }
+      },
+    }),
+    withAsyncErrorQueryFn: build.query<string, string>({
+      async queryFn(arg: string) {
+        return { error: { type: 'Custom' } }
+      },
+    }),
+    withInvalidAsyncErrorQueryFn: build.query<string, string>({
+      // @ts-expect-error
+      async queryFn(arg: string) {
+        return { error: 5 }
+      },
+    }),
+
+    mutationWithQueryFn: build.mutation<string, string>({
+      queryFn(arg: string) {
+        return { data: `resultFrom(${arg})` }
+      },
+    }),
+    mutationWithInvalidDataQueryFn: build.mutation<string, string>({
+      // @ts-expect-error
+      queryFn(arg: string) {
+        return { data: 5 }
+      },
+    }),
+    mutationWithErrorQueryFn: build.mutation<string, string>({
+      queryFn(arg: string) {
+        return { error: { type: 'Custom' } }
+      },
+    }),
+    mutationWithInvalidErrorQueryFn: build.mutation<string, string>({
+      // @ts-expect-error
+      queryFn(arg: string) {
+        return { error: 5 }
+      },
+    }),
+
+    mutationWithAsyncQueryFn: build.mutation<string, string>({
+      async queryFn(arg: string) {
+        return { data: `resultFrom(${arg})` }
+      },
+    }),
+    mutationWithInvalidAsyncQueryFn: build.mutation<string, string>({
+      // @ts-expect-error
+      async queryFn(arg: string) {
+        return { data: 5 }
+      },
+    }),
+    mutationWithAsyncErrorQueryFn: build.mutation<string, string>({
+      async queryFn(arg: string) {
+        return { error: { type: 'Custom' } }
+      },
+    }),
+    mutationWithInvalidAsyncErrorQueryFn: build.mutation<string, string>({
+      // @ts-expect-error
+      async queryFn(arg: string) {
+        return { error: 5 }
+      },
+    }),
+    // @ts-expect-error
+    withNeither: build.query<string, string>({}),
+    // @ts-expect-error
+    mutationWithNeither: build.mutation<string, string>({}),
+  }),
+})
+
+const store = configureStore({
+  reducer: {
+    [api.reducerPath]: api.reducer,
+  },
+  middleware: (gDM) => gDM({}).concat(api.middleware),
+})
+
+test('fakeBaseQuery throws when invoking query', async () => {
+  const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+  const thunk = api.endpoints.withQuery.initiate('')
+
+  const result = await store.dispatch(thunk)
+
+  expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+  expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+    `An unhandled error occurred processing a request for the endpoint "withQuery".\nIn the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+    Error(
+      'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.',
+    ),
+  )
+
+  expect(result!.error).toEqual({
+    message:
+      'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.',
+    name: 'Error',
+    stack: expect.any(String),
+  })
+
+  consoleErrorSpy.mockRestore()
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/fetchBaseQuery.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/fetchBaseQuery.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/fetchBaseQuery.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1545 @@
+import { createSlice } from '@reduxjs/toolkit'
+import type { FetchArgs } from '@reduxjs/toolkit/query'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+import { headersToObject } from 'headers-polyfill'
+import { HttpResponse, delay, http } from 'msw'
+import nodeFetch from 'node-fetch'
+import queryString from 'query-string'
+import { vi } from 'vitest'
+import { setupApiStore } from '../../tests/utils/helpers'
+import type { BaseQueryApi } from '../baseQueryTypes'
+import { server } from './mocks/server'
+
+const defaultHeaders: Record<string, string> = {
+  fake: 'header',
+  delete: 'true',
+  delete2: '1',
+}
+
+const baseUrl = 'https://example.com'
+
+const baseQuery = fetchBaseQuery({
+  baseUrl,
+  prepareHeaders: (headers, { getState }) => {
+    const { token } = (getState() as RootState).auth
+
+    // If we have a token set in state, let's assume that we should be passing it.
+    if (token) {
+      headers.set('authorization', `Bearer ${token}`)
+    }
+    // A user could customize their behavior here, so we'll just test that custom scenarios would work.
+    const potentiallyConflictingKeys = Object.keys(defaultHeaders)
+    potentiallyConflictingKeys.forEach((key) => {
+      // Check for presence of a default key, if the incoming endpoint headers don't specify it as '', then set it
+      const existingValue = headers.get(key)
+      if (!existingValue && existingValue !== '') {
+        headers.set(key, String(defaultHeaders[key]))
+        // If an endpoint sets a header with a value of '', just delete the header.
+      } else if (headers.get(key) === '') {
+        headers.delete(key)
+      }
+    })
+
+    return headers
+  },
+})
+
+const api = createApi({
+  baseQuery,
+  endpoints(build) {
+    return {
+      query: build.query({ query: () => ({ url: '/echo', headers: {} }) }),
+      mutation: build.mutation({
+        query: () => ({ url: '/echo', method: 'POST', credentials: 'omit' }),
+      }),
+    }
+  },
+})
+
+const authSlice = createSlice({
+  name: 'auth',
+  initialState: {
+    token: '',
+  },
+  reducers: {
+    setToken(state, action) {
+      state.token = action.payload
+    },
+  },
+})
+
+const storeRef = setupApiStore(api, { auth: authSlice.reducer })
+type RootState = ReturnType<typeof storeRef.store.getState>
+
+let commonBaseQueryApi: BaseQueryApi = {} as any
+beforeEach(() => {
+  let abortController = new AbortController()
+  commonBaseQueryApi = {
+    signal: abortController.signal,
+    abort: (reason) =>
+      // @ts-ignore
+      abortController.abort(reason),
+    dispatch: storeRef.store.dispatch,
+    getState: storeRef.store.getState,
+    extra: undefined,
+    type: 'query',
+    endpoint: 'doesntmatterhere',
+  }
+})
+
+describe('fetchBaseQuery', () => {
+  describe('basic functionality', () => {
+    it('should return an object for a simple GET request when it is json data', async () => {
+      const req = baseQuery('/success', commonBaseQueryApi, {})
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.data).toEqual({ value: 'success' })
+    })
+
+    it('should return undefined for a simple GET request when the response is empty', async () => {
+      const req = baseQuery('/empty', commonBaseQueryApi, {})
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+
+      expect(res.data).toBeNull()
+    })
+
+    it('should return an error and status for error responses', async () => {
+      const req = baseQuery('/error', commonBaseQueryApi, {})
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.error).toEqual({
+        status: 500,
+        data: { value: 'error' },
+      })
+    })
+
+    it('should handle a connection loss semi-gracefully', async () => {
+      const fetchFn = vi
+        .fn()
+        .mockRejectedValueOnce(new TypeError('Failed to fetch'))
+
+      const req = fetchBaseQuery({
+        baseUrl,
+        fetchFn,
+      })('/success', commonBaseQueryApi, {})
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBe(undefined)
+      expect(res.error).toEqual({
+        status: 'FETCH_ERROR',
+        error: 'TypeError: Failed to fetch',
+      })
+    })
+  })
+
+  describe('non-JSON-body', () => {
+    it('success: should return data ("text" responseHandler)', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.text(`this is not json!`),
+          { once: true },
+        ),
+      )
+
+      const req = baseQuery(
+        { url: '/success', responseHandler: 'text' },
+        commonBaseQueryApi,
+        {},
+      )
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.data).toEqual(`this is not json!`)
+    })
+
+    it('success: should fail gracefully (default="json" responseHandler)', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.text(`this is not json!`),
+          { once: true },
+        ),
+      )
+
+      const req = baseQuery('/success', commonBaseQueryApi, {})
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.error).toEqual({
+        status: 'PARSING_ERROR',
+        error: expect.stringMatching(/SyntaxError: Unexpected token/),
+        originalStatus: 200,
+        data: `this is not json!`,
+      })
+    })
+
+    it('success: parse text without error ("content-type" responseHandler)', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.text(`this is not json!`),
+          { once: true },
+        ),
+      )
+
+      const req = baseQuery(
+        {
+          url: '/success',
+          responseHandler: 'content-type',
+        },
+        commonBaseQueryApi,
+        {},
+      )
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'text/plain',
+      )
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.data).toEqual(`this is not json!`)
+    })
+
+    it('success: parse json without error ("content-type" responseHandler)', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.json(`this will become json!`),
+          { once: true },
+        ),
+      )
+
+      const req = baseQuery(
+        {
+          url: '/success',
+          responseHandler: 'content-type',
+        },
+        commonBaseQueryApi,
+        {},
+      )
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'application/json',
+      )
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.data).toEqual(`this will become json!`)
+    })
+
+    it('server error: should fail normally with a 500 status ("text" responseHandler)', async () => {
+      server.use(
+        http.get('https://example.com/error', () =>
+          HttpResponse.text(`this is not json!`, { status: 500 }),
+        ),
+      )
+
+      const req = baseQuery(
+        { url: '/error', responseHandler: 'text' },
+        commonBaseQueryApi,
+        {},
+      )
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.error).toEqual({
+        status: 500,
+        data: `this is not json!`,
+      })
+    })
+
+    it('server error: should fail normally with a 500 status as text ("content-type" responseHandler)', async () => {
+      const serverResponse = 'Internal Server Error'
+      server.use(
+        http.get('https://example.com/error', () =>
+          HttpResponse.text(serverResponse, { status: 500 }),
+        ),
+      )
+
+      const req = baseQuery(
+        { url: '/error', responseHandler: 'content-type' },
+        commonBaseQueryApi,
+        {},
+      )
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'text/plain',
+      )
+      expect(res.error).toEqual({
+        status: 500,
+        data: serverResponse,
+      })
+    })
+
+    it('server error: should fail normally with a 500 status as json ("content-type" responseHandler)', async () => {
+      const serverResponse = {
+        errors: { field1: "Password cannot be 'password'" },
+      }
+      server.use(
+        http.get('https://example.com/error', () =>
+          HttpResponse.json(serverResponse, { status: 500 }),
+        ),
+      )
+
+      const req = baseQuery(
+        { url: '/error', responseHandler: 'content-type' },
+        commonBaseQueryApi,
+        {},
+      )
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'application/json',
+      )
+      expect(res.error).toEqual({
+        status: 500,
+        data: serverResponse,
+      })
+    })
+
+    it('server error: should fail gracefully (default="json" responseHandler)', async () => {
+      server.use(
+        http.get('https://example.com/error', () =>
+          HttpResponse.text(`this is not json!`, { status: 500 }),
+        ),
+      )
+
+      const req = baseQuery('/error', commonBaseQueryApi, {})
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.error).toEqual({
+        status: 'PARSING_ERROR',
+        error: expect.stringMatching(/SyntaxError: Unexpected token/),
+        originalStatus: 500,
+        data: `this is not json!`,
+      })
+    })
+  })
+
+  describe('arg.body', () => {
+    test('an object provided to body will be serialized when content-type is json', async () => {
+      const data = {
+        test: 'value',
+      }
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', body: data, method: 'POST' },
+        { ...commonBaseQueryApi, type: 'mutation' },
+        {},
+      ))
+
+      expect(request.headers['content-type']).toBe('application/json')
+      expect(request.body).toEqual(data)
+    })
+
+    test('an array provided to body will be serialized when content-type is json', async () => {
+      const data = ['test', 'value']
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', body: data, method: 'POST' },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['content-type']).toBe('application/json')
+      expect(request.body).toEqual(data)
+    })
+
+    test('an object provided to body will not be serialized when content-type is not json', async () => {
+      const data = {
+        test: 'value',
+      }
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        {
+          url: '/echo',
+          body: data,
+          method: 'POST',
+          headers: { 'content-type': 'text/html' },
+        },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['content-type']).toBe('text/html')
+      expect(request.body).toEqual('[object Object]')
+    })
+
+    test('an array provided to body will not be serialized when content-type is not json', async () => {
+      const data = ['test', 'value']
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        {
+          url: '/echo',
+          body: data,
+          method: 'POST',
+          headers: { 'content-type': 'text/html' },
+        },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['content-type']).toBe('text/html')
+      expect(request.body).toEqual(data.join(','))
+    })
+
+    it('supports a custom jsonContentType', async () => {
+      const baseQuery = fetchBaseQuery({
+        baseUrl,
+        jsonContentType: 'application/vnd.api+json',
+      })
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        {
+          url: '/echo',
+          body: {},
+          method: 'POST',
+        },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['content-type']).toBe('application/vnd.api+json')
+    })
+
+    it('supports a custom jsonReplacer', async () => {
+      const body = {
+        items: new Set(['A', 'B', 'C']),
+      }
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        {
+          url: '/echo',
+          body,
+          method: 'POST',
+        },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['content-type']).toBe('application/json')
+      expect(request.body).toEqual({ items: {} }) // Set is not properly marshalled by default
+
+      // Use jsonReplacer
+      const baseQueryWithReplacer = fetchBaseQuery({
+        baseUrl,
+        jsonReplacer: (key, value) =>
+          value instanceof Set ? [...value] : value,
+      })
+
+      ;({ data: request } = await baseQueryWithReplacer(
+        {
+          url: '/echo',
+          body,
+          method: 'POST',
+        },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['content-type']).toBe('application/json')
+      expect(request.body).toEqual({ items: ['A', 'B', 'C'] }) // Set is marshalled correctly by jsonReplacer
+    })
+  })
+
+  describe('arg.params', () => {
+    it('should not serialize missing params', async () => {
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo' },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.url).toEqual(`${baseUrl}/echo`)
+    })
+
+    it('should serialize numeric and boolean params', async () => {
+      const params = { a: 1, b: true }
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', params },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.url).toEqual(`${baseUrl}/echo?a=1&b=true`)
+    })
+
+    it('should merge params into existing url querystring', async () => {
+      const params = { a: 1, b: true }
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo?banana=pudding', params },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.url).toEqual(`${baseUrl}/echo?banana=pudding&a=1&b=true`)
+    })
+
+    it('should accept a URLSearchParams instance', async () => {
+      const params = new URLSearchParams({ apple: 'fruit' })
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', params },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit`)
+    })
+
+    it('should strip undefined values from the end params', async () => {
+      const params = { apple: 'fruit', banana: undefined, randy: null }
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', params },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit&randy=null`)
+    })
+
+    it('should support a paramsSerializer', async () => {
+      const baseQuery = fetchBaseQuery({
+        baseUrl,
+        paramsSerializer: (params: Record<string, unknown>) =>
+          queryString.stringify(params, { arrayFormat: 'bracket' }),
+      })
+
+      const api = createApi({
+        baseQuery,
+        endpoints(build) {
+          return {
+            query: build.query({
+              query: () => ({ url: '/echo', headers: {} }),
+            }),
+            mutation: build.mutation({
+              query: () => ({
+                url: '/echo',
+                method: 'POST',
+                credentials: 'omit',
+              }),
+            }),
+          }
+        },
+      })
+
+      const params = {
+        someArray: ['a', 'b', 'c'],
+      }
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', params },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.url).toEqual(
+        `${baseUrl}/echo?someArray[]=a&someArray[]=b&someArray[]=c`,
+      )
+    })
+
+    it('should supports a custom isJsonContentType function', async () => {
+      const testBody = {
+        i_should_be_stringified: true,
+      }
+      const baseQuery = fetchBaseQuery({
+        baseUrl,
+        isJsonContentType: (headers) =>
+          [
+            'application/vnd.api+json',
+            'application/json',
+            'application/vnd.hal+json',
+          ].includes(headers.get('content-type') ?? ''),
+      })
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        {
+          url: '/echo',
+          method: 'POST',
+          body: testBody,
+          headers: { 'content-type': 'application/vnd.hal+json' },
+        },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.body).toMatchObject(testBody)
+    })
+  })
+
+  describe('validateStatus', () => {
+    test('validateStatus can return an error even on normal 200 responses', async () => {
+      // This is a scenario where an API may always return a 200, but indicates there is an error when success = false
+      const res = await baseQuery(
+        {
+          url: '/nonstandard-error',
+          validateStatus: (response, body) =>
+            response.status === 200 && body.success === false ? false : true,
+        },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(res.error).toEqual({
+        status: 200,
+        data: {
+          success: false,
+          message: 'This returns a 200 but is really an error',
+        },
+      })
+    })
+  })
+
+  describe('arg.headers and prepareHeaders', () => {
+    test('uses the default headers set in prepareHeaders', async () => {
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo' },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['fake']).toBe(defaultHeaders['fake'])
+      expect(request.headers['delete']).toBe(defaultHeaders['delete'])
+      expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
+    })
+
+    test('adds endpoint-level headers to the defaults', async () => {
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', headers: { authorization: 'Bearer banana' } },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['authorization']).toBe('Bearer banana')
+      expect(request.headers['fake']).toBe(defaultHeaders['fake'])
+      expect(request.headers['delete']).toBe(defaultHeaders['delete'])
+      expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
+    })
+
+    test('it does not set application/json when content-type is set', async () => {
+      let request: any
+      ;({ data: request } = await baseQuery(
+        {
+          url: '/echo',
+          headers: {
+            authorization: 'Bearer banana',
+            'content-type': 'custom-content-type',
+          },
+        },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['authorization']).toBe('Bearer banana')
+      expect(request.headers['content-type']).toBe('custom-content-type')
+      expect(request.headers['fake']).toBe(defaultHeaders['fake'])
+      expect(request.headers['delete']).toBe(defaultHeaders['delete'])
+      expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
+    })
+
+    test('respects the headers from an endpoint over the base headers', async () => {
+      const fake = 'fake endpoint value'
+
+      let request: any
+      ;({ data: request } = await baseQuery(
+        { url: '/echo', headers: { fake, delete: '', delete2: '' } },
+        commonBaseQueryApi,
+        {},
+      ))
+
+      expect(request.headers['fake']).toBe(fake)
+      expect(request.headers['delete']).toBeUndefined()
+      expect(request.headers['delete2']).toBeUndefined()
+    })
+
+    test('prepareHeaders can return undefined', async () => {
+      let request: any
+
+      const token = 'accessToken'
+
+      const _baseQuery = fetchBaseQuery({
+        baseUrl,
+        prepareHeaders: (headers) => {
+          headers.set('authorization', `Bearer ${token}`)
+        },
+      })
+
+      const doRequest = async () =>
+        _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})
+
+      ;({ data: request } = await doRequest())
+
+      expect(request.headers['authorization']).toBe(`Bearer ${token}`)
+    })
+
+    test('prepareHeaders is able to be an async function', async () => {
+      let request: any
+
+      const token = 'accessToken'
+      const getAccessTokenAsync = async () => token
+
+      const _baseQuery = fetchBaseQuery({
+        baseUrl,
+        prepareHeaders: async (headers) => {
+          headers.set('authorization', `Bearer ${await getAccessTokenAsync()}`)
+          return headers
+        },
+      })
+
+      const doRequest = async () =>
+        _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})
+
+      ;({ data: request } = await doRequest())
+
+      expect(request.headers['authorization']).toBe(`Bearer ${token}`)
+    })
+
+    test('prepareHeaders is able to be an async function returning undefined', async () => {
+      let request: any
+
+      const token = 'accessToken'
+      const getAccessTokenAsync = async () => token
+
+      const _baseQuery = fetchBaseQuery({
+        baseUrl,
+        prepareHeaders: async (headers) => {
+          headers.set('authorization', `Bearer ${await getAccessTokenAsync()}`)
+        },
+      })
+
+      const doRequest = async () =>
+        _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})
+
+      ;({ data: request } = await doRequest())
+
+      expect(request.headers['authorization']).toBe(`Bearer ${token}`)
+    })
+
+    test('prepareHeaders is able to select from a state', async () => {
+      let request: any
+
+      const doRequest = async () => {
+        const abortController = new AbortController()
+        return baseQuery(
+          { url: '/echo' },
+          {
+            signal: abortController.signal,
+            abort: (reason) =>
+              // @ts-ignore
+              abortController.abort(reason),
+            dispatch: storeRef.store.dispatch,
+            getState: storeRef.store.getState,
+            extra: undefined,
+            type: 'query',
+            endpoint: '',
+          },
+          {},
+        )
+      }
+
+      ;({ data: request } = await doRequest())
+
+      expect(request.headers['authorization']).toBeUndefined()
+
+      // Set a token and the follow up request should have the header injected by prepareHeaders
+      const token = 'fakeToken!'
+      storeRef.store.dispatch(authSlice.actions.setToken(token))
+      ;({ data: request } = await doRequest())
+
+      expect(request.headers['authorization']).toBe(`Bearer ${token}`)
+    })
+
+    test('prepareHeaders provides extra api information for getState, extra, endpoint, type and forced', async () => {
+      let _getState, _arg: any, _extra, _endpoint, _type, _forced
+
+      const baseQuery = fetchBaseQuery({
+        baseUrl,
+        prepareHeaders: (
+          headers,
+          { getState, arg, extra, endpoint, type, forced },
+        ) => {
+          _getState = getState
+          _arg = arg
+          _endpoint = endpoint
+          _type = type
+          _forced = forced
+          _extra = extra
+
+          return headers
+        },
+      })
+
+      const fakeAuth0Client = {
+        getTokenSilently: async () => 'fakeToken',
+      }
+
+      const doRequest = async () => {
+        const abortController = new AbortController()
+        return baseQuery(
+          { url: '/echo' },
+          {
+            signal: abortController.signal,
+            abort: (reason) =>
+              // @ts-ignore
+              abortController.abort(reason),
+            dispatch: storeRef.store.dispatch,
+            getState: storeRef.store.getState,
+            extra: fakeAuth0Client,
+            type: 'query',
+            forced: true,
+            endpoint: 'someEndpointName',
+          },
+          {},
+        )
+      }
+
+      await doRequest()
+
+      expect(_getState).toBeDefined()
+      expect(_arg!.url).toBe('/echo')
+      expect(_endpoint).toBe('someEndpointName')
+      expect(_type).toBe('query')
+      expect(_forced).toBe(true)
+      expect(_extra).toBe(fakeAuth0Client)
+    })
+
+    test('can be instantiated with a `ExtraOptions` generic and `extraOptions` will be available in `prepareHeaders', async () => {
+      const prepare = vitest.fn()
+      const baseQuery = fetchBaseQuery({
+        prepareHeaders(headers, api) {
+          expectTypeOf(api.extraOptions).toEqualTypeOf<unknown>()
+          prepare.apply(undefined, arguments as unknown as any[])
+        },
+      })
+      baseQuery('https://example.com', commonBaseQueryApi, {
+        foo: 'baz',
+        bar: 5,
+      })
+      expect(prepare).toHaveBeenCalledWith(
+        expect.anything(),
+        expect.objectContaining({ extraOptions: { foo: 'baz', bar: 5 } }),
+      )
+
+      // ensure types
+      createApi({
+        baseQuery,
+        endpoints(build) {
+          return {
+            testQuery: build.query({
+              query: () => ({ url: '/echo', headers: {} }),
+              extraOptions: {
+                foo: 'asd',
+                bar: 1,
+              },
+            }),
+            testMutation: build.mutation({
+              query: () => ({
+                url: '/echo',
+                method: 'POST',
+                credentials: 'omit',
+              }),
+              extraOptions: {
+                foo: 'qwe',
+                bar: 15,
+              },
+            }),
+          }
+        },
+      })
+    })
+  })
+
+  test('can pass `headers` into `fetchBaseQuery`', async () => {
+    let request: any
+
+    const token = 'accessToken'
+
+    const _baseQuery = fetchBaseQuery({
+      baseUrl,
+      headers: { authorization: `Bearer ${token}` },
+    })
+
+    const doRequest = async () =>
+      _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})
+
+    ;({ data: request } = await doRequest())
+
+    expect(request.headers['authorization']).toBe(`Bearer ${token}`)
+  })
+
+  test('lets a header be undefined', async () => {
+    let request: any
+    ;({ data: request } = await baseQuery(
+      { url: '/echo', headers: undefined },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.headers['fake']).toBe(defaultHeaders['fake'])
+    expect(request.headers['delete']).toBe(defaultHeaders['delete'])
+    expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
+  })
+
+  test('allows for possibly undefined header key/values', async () => {
+    const banana = '1' as '1' | undefined
+    let request: any
+    ;({ data: request } = await baseQuery(
+      { url: '/echo', headers: { banana } },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.headers['banana']).toBe('1')
+    expect(request.headers['fake']).toBe(defaultHeaders['fake'])
+    expect(request.headers['delete']).toBe(defaultHeaders['delete'])
+    expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
+  })
+
+  test('strips undefined values from the headers', async () => {
+    const banana = undefined as '1' | undefined
+    let request: any
+    ;({ data: request } = await baseQuery(
+      { url: '/echo', headers: { banana } },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.headers['banana']).toBeUndefined()
+    expect(request.headers['fake']).toBe(defaultHeaders['fake'])
+    expect(request.headers['delete']).toBe(defaultHeaders['delete'])
+    expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])
+  })
+
+  describe('Accepts global arguments', () => {
+    test('Global responseHandler', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.text(`this is not json!`),
+          { once: true },
+        ),
+      )
+
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        responseHandler: 'text',
+      })
+
+      const req = globalizedBaseQuery(
+        { url: '/success' },
+        commonBaseQueryApi,
+        {},
+      )
+      expect(req).toBeInstanceOf(Promise)
+      const res = await req
+      expect(res).toBeInstanceOf(Object)
+      expect(res.meta?.request).toBeInstanceOf(Request)
+      expect(res.meta?.response).toBeInstanceOf(Object)
+      expect(res.error).toBeUndefined()
+      expect(res.data).toEqual(`this is not json!`)
+    })
+
+    test('Global responseHandler: content-type with text response', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.text(`this is plain text!`),
+          { once: true },
+        ),
+      )
+
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        responseHandler: 'content-type',
+      })
+
+      const res = await globalizedBaseQuery(
+        { url: '/success' },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(res.error).toBeUndefined()
+      expect(res.data).toEqual(`this is plain text!`)
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'text/plain',
+      )
+    })
+
+    test('Global responseHandler: content-type with JSON response', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.json({ message: 'this is json!' }),
+          { once: true },
+        ),
+      )
+
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        responseHandler: 'content-type',
+      })
+
+      const res = await globalizedBaseQuery(
+        { url: '/success' },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(res.error).toBeUndefined()
+      expect(res.data).toEqual({ message: 'this is json!' })
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'application/json',
+      )
+    })
+
+    test('Global responseHandler: content-type can be overridden at endpoint level', async () => {
+      server.use(
+        http.get(
+          'https://example.com/success',
+          () => HttpResponse.text(`this is text but will be parsed as json`),
+          { once: true },
+        ),
+      )
+
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        responseHandler: 'content-type',
+      })
+
+      // Override global content-type handler with explicit text handler
+      const res = await globalizedBaseQuery(
+        { url: '/success', responseHandler: 'text' },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(res.error).toBeUndefined()
+      expect(res.data).toEqual(`this is text but will be parsed as json`)
+    })
+
+    test('Global responseHandler: content-type with error response (text)', async () => {
+      const errorMessage = 'Internal Server Error'
+      server.use(
+        http.get('https://example.com/error', () =>
+          HttpResponse.text(errorMessage, { status: 500 }),
+        ),
+      )
+
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        responseHandler: 'content-type',
+      })
+
+      const res = await globalizedBaseQuery(
+        { url: '/error' },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(res.error).toEqual({
+        status: 500,
+        data: errorMessage,
+      })
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'text/plain',
+      )
+    })
+
+    test('Global responseHandler: content-type with error response (JSON)', async () => {
+      const errorData = { error: 'Something went wrong', code: 'ERR_500' }
+      server.use(
+        http.get('https://example.com/error', () =>
+          HttpResponse.json(errorData, { status: 500 }),
+        ),
+      )
+
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        responseHandler: 'content-type',
+      })
+
+      const res = await globalizedBaseQuery(
+        { url: '/error' },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(res.error).toEqual({
+        status: 500,
+        data: errorData,
+      })
+      expect(res.meta?.response?.headers.get('content-type')).toEqual(
+        'application/json',
+      )
+    })
+
+    test('Global validateStatus', async () => {
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        validateStatus: (response, body) =>
+          response.status === 200 && body.success === false ? false : true,
+      })
+
+      // This is a scenario where an API may always return a 200, but indicates there is an error when success = false
+      const res = await globalizedBaseQuery(
+        {
+          url: '/nonstandard-error',
+        },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(res.error).toEqual({
+        status: 200,
+        data: {
+          success: false,
+          message: 'This returns a 200 but is really an error',
+        },
+      })
+    })
+
+    test('Global timeout', async () => {
+      server.use(
+        http.get(
+          'https://example.com/empty1',
+          async ({ request, cookies, params, requestId }) => {
+            await delay(300)
+
+            return HttpResponse.json({
+              ...request,
+              cookies,
+              params,
+              requestId,
+              url: new URL(request.url),
+              headers: headersToObject(request.headers),
+            })
+          },
+          { once: true },
+        ),
+      )
+
+      const globalizedBaseQuery = fetchBaseQuery({
+        baseUrl,
+        timeout: 200,
+      })
+
+      const result = await globalizedBaseQuery(
+        { url: '/empty1' },
+        commonBaseQueryApi,
+        {},
+      )
+
+      expect(result?.error).toEqual({
+        status: 'TIMEOUT_ERROR',
+        error: expect.stringMatching(/^TimeoutError/),
+      })
+    })
+  })
+})
+
+describe('fetchFn', () => {
+  test('accepts a custom fetchFn', async () => {
+    const baseUrl = 'https://example.com'
+    const params = new URLSearchParams({ apple: 'fruit' })
+
+    const baseQuery = fetchBaseQuery({
+      baseUrl,
+      fetchFn: nodeFetch as any,
+    })
+    let request: any
+    ;({ data: request } = await baseQuery(
+      { url: '/echo', params },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit`)
+  })
+
+  test('respects mocking window.fetch after a fetch base query is created', async () => {
+    const baseUrl = 'https://example.com'
+    const baseQuery = fetchBaseQuery({ baseUrl })
+
+    const fakeResponse = {
+      ok: true,
+      status: 200,
+      text: async () => `{ "url": "mock-return-url" }`,
+      clone: () => fakeResponse,
+    }
+
+    const spiedFetch = vi.spyOn(window, 'fetch')
+    spiedFetch.mockResolvedValueOnce(fakeResponse as any)
+
+    const { data } = await baseQuery({ url: '/echo' }, commonBaseQueryApi, {})
+    expect(data).toEqual({ url: 'mock-return-url' })
+
+    spiedFetch.mockClear()
+  })
+})
+
+describe('FormData', () => {
+  test('sets the right headers when sending FormData', async () => {
+    const body = new FormData()
+
+    body.append('username', 'test')
+
+    body.append(
+      'file',
+      new Blob([JSON.stringify({ hello: 'there' }, null, 2)], {
+        type: 'application/json',
+      }),
+    )
+
+    const res = await baseQuery(
+      { url: '/echo', method: 'POST', body },
+      commonBaseQueryApi,
+      {},
+    )
+
+    const request: any = res.data
+
+    expect(request.headers['content-type']).not.toContain('application/json')
+  })
+
+  test('FormData works correctly when prepareHeaders sets Content-Type to application/json', async () => {
+    // This test covers the exact scenario from issue #4669
+    const baseQueryWithJsonDefault = fetchBaseQuery({
+      baseUrl,
+      prepareHeaders: (headers) => {
+        // Set default Content-Type for all requests
+        headers.set('Content-Type', 'application/json')
+        return headers
+      },
+    })
+
+    const body = new FormData()
+    body.append('username', 'test')
+    body.append(
+      'file',
+      new Blob([JSON.stringify({ hello: 'there' }, null, 2)], {
+        type: 'application/json',
+      }),
+    )
+
+    const res = await baseQueryWithJsonDefault(
+      { url: '/echo', method: 'POST', body },
+      commonBaseQueryApi,
+      {},
+    )
+
+    const request: any = res.data
+
+    // The Content-Type should NOT be application/json when FormData is used
+    expect(request.headers['content-type']).not.toContain('application/json')
+    // It should contain multipart/form-data (set automatically by the browser)
+    expect(request.headers['content-type']).toContain('multipart/form-data')
+  })
+
+  test('FormData works when prepareHeaders conditionally removes Content-Type', async () => {
+    // This tests the workaround solution from the issue comments
+    const baseQueryWithConditionalHeader = fetchBaseQuery({
+      baseUrl,
+      prepareHeaders: (headers, { arg }) => {
+        // Check if body is FormData and skip setting Content-Type
+        if ((arg as FetchArgs).body instanceof FormData) {
+          // Delete Content-Type to let browser set it automatically
+          headers.delete('Content-Type')
+        } else {
+          // Set default Content-Type for non-FormData requests
+          headers.set('Content-Type', 'application/json')
+        }
+        return headers
+      },
+    })
+
+    const body = new FormData()
+    body.append('username', 'test')
+    body.append('file', new Blob(['test content'], { type: 'text/plain' }))
+
+    const res = await baseQueryWithConditionalHeader(
+      { url: '/echo', method: 'POST', body },
+      commonBaseQueryApi,
+      {},
+    )
+
+    const request: any = res.data
+
+    // Should have multipart/form-data set by browser
+    expect(request.headers['content-type']).toContain('multipart/form-data')
+    expect(request.headers['content-type']).not.toContain('application/json')
+  })
+
+  test('endpoint-level headers cannot override to multipart/form-data manually', async () => {
+    // This tests the fetch API quirk mentioned in the issue
+    const baseQueryWithJsonDefault = fetchBaseQuery({
+      baseUrl,
+      prepareHeaders: (headers) => {
+        headers.set('Content-Type', 'application/json')
+        return headers
+      },
+    })
+
+    const body = new FormData()
+    body.append('test', 'value')
+
+    const res = await baseQueryWithJsonDefault(
+      {
+        url: '/echo',
+        method: 'POST',
+        body,
+        // Attempting to manually set multipart/form-data (this won't work as expected)
+        headers: { 'Content-Type': 'multipart/form-data' },
+      },
+      commonBaseQueryApi,
+      {},
+    )
+
+    const request: any = res.data
+
+    // Due to prepareHeaders running after endpoint headers,
+    // and the fetch API not allowing manual multipart/form-data setting,
+    // this demonstrates the problem from the issue
+    // The actual behavior depends on fetchBaseQuery implementation
+    expect(request.headers['content-type']).toBeDefined()
+  })
+
+  test('non-FormData requests still get application/json from prepareHeaders', async () => {
+    // Verify that the workaround doesn't break normal JSON requests
+    const baseQueryWithConditionalHeader = fetchBaseQuery({
+      baseUrl,
+      prepareHeaders: (headers, { arg }) => {
+        if (!((arg as FetchArgs).body instanceof FormData)) {
+          headers.set('Content-Type', 'application/json')
+        }
+        return headers
+      },
+    })
+
+    const jsonBody = { test: 'value' }
+
+    const res = await baseQueryWithConditionalHeader(
+      { url: '/echo', method: 'POST', body: jsonBody },
+      commonBaseQueryApi,
+      {},
+    )
+
+    const request: any = res.data
+
+    // Regular JSON requests should still get application/json
+    expect(request.headers['content-type']).toBe('application/json')
+    expect(request.body).toEqual(jsonBody)
+  })
+})
+
+describe('Accept header handling', () => {
+  test('sets Accept header to application/json for json responseHandler', async () => {
+    let request: any
+    ;({ data: request } = await baseQuery(
+      { url: '/echo', responseHandler: 'json' },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.headers['accept']).toBe('application/json')
+  })
+
+  test('sets Accept header to application/json by default (json is default responseHandler)', async () => {
+    let request: any
+    ;({ data: request } = await baseQuery(
+      { url: '/echo' },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.headers['accept']).toBe('application/json')
+  })
+
+  test('sets Accept header for text responseHandler', async () => {
+    // Create a baseQuery with text as the global responseHandler
+    const textBaseQuery = fetchBaseQuery({
+      baseUrl,
+      responseHandler: 'text',
+    })
+
+    let request: any
+      // Override to json just for this test so we can inspect the echoed request object
+    ;({ data: request } = await textBaseQuery(
+      { url: '/echo', responseHandler: 'json' },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    // The endpoint-level 'json' responseHandler overrides the global 'text',
+    // so the Accept header should be application/json
+    expect(request.headers['accept']).toBe('application/json')
+  })
+
+  test('does not override explicit Accept header from endpoint', async () => {
+    let request: any
+    ;({ data: request } = await baseQuery(
+      {
+        url: '/echo',
+        responseHandler: 'json',
+        headers: { Accept: 'application/xml' },
+      },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.headers['accept']).toBe('application/xml')
+  })
+
+  test('does not override Accept header set in prepareHeaders', async () => {
+    const customBaseQuery = fetchBaseQuery({
+      baseUrl,
+      prepareHeaders: (headers) => {
+        headers.set('Accept', 'application/vnd.api+json')
+        return headers
+      },
+    })
+
+    let request: any
+    ;({ data: request } = await customBaseQuery(
+      { url: '/echo', responseHandler: 'json' },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    expect(request.headers['accept']).toBe('application/vnd.api+json')
+  })
+
+  test('does not set Accept header for content-type responseHandler', async () => {
+    let request: any
+    ;({ data: request } = await baseQuery(
+      { url: '/echo', responseHandler: 'content-type' },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    // Should either not have accept header or have a permissive one
+    // content-type handler adapts to whatever server sends
+    const acceptHeader = request.headers['accept']
+    if (acceptHeader) {
+      expect(acceptHeader).toMatch(/\*\/\*/)
+    }
+  })
+
+  test('respects global responseHandler for Accept header', async () => {
+    const textBaseQuery = fetchBaseQuery({
+      baseUrl,
+      responseHandler: 'text',
+    })
+
+    let request: any
+      // Override to json just for this test so we can inspect the echoed request object
+    ;({ data: request } = await textBaseQuery(
+      { url: '/echo', responseHandler: 'json' },
+      commonBaseQueryApi,
+      {},
+    ))
+
+    // The endpoint-level 'json' responseHandler overrides the global 'text',
+    // so the Accept header should be application/json (proving endpoint-level takes precedence)
+    expect(request.headers['accept']).toBe('application/json')
+  })
+})
+
+describe('still throws on completely unexpected errors', () => {
+  test('', async () => {
+    const error = new Error('some unexpected error')
+    const req = baseQuery(
+      {
+        url: '/success',
+        validateStatus() {
+          throw error
+        },
+      },
+      commonBaseQueryApi,
+      {},
+    )
+    expect(req).toBeInstanceOf(Promise)
+    await expect(req).rejects.toBe(error)
+  })
+})
+
+describe('timeout', () => {
+  test('throws a timeout error when a request takes longer than specified timeout duration', async () => {
+    server.use(
+      http.get(
+        'https://example.com/empty2',
+        async ({ request, cookies, params, requestId }) => {
+          await delay(300)
+
+          return HttpResponse.json({
+            ...request,
+            url: new URL(request.url),
+            cookies,
+            params,
+            requestId,
+            headers: headersToObject(request.headers),
+          })
+        },
+        { once: true },
+      ),
+    )
+
+    const result = await baseQuery(
+      { url: '/empty2', timeout: 200 },
+      commonBaseQueryApi,
+      {},
+    )
+
+    expect(result?.error).toEqual({
+      status: 'TIMEOUT_ERROR',
+      error: expect.stringMatching(/^TimeoutError/),
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/infiniteQueries.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/infiniteQueries.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/infiniteQueries.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,171 @@
+import type { skipToken, InfiniteData } from '@reduxjs/toolkit/query/react'
+import {
+  createApi,
+  fetchBaseQuery,
+  QueryStatus,
+} from '@reduxjs/toolkit/query/react'
+import { setupApiStore } from '../../tests/utils/helpers'
+import { createSlice } from '@internal/createSlice'
+
+describe('Infinite queries', () => {
+  test('Basic infinite query behavior', async () => {
+    type Pokemon = {
+      id: string
+      name: string
+    }
+
+    const pokemonApi = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+      endpoints: (build) => ({
+        getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              lastPageParam,
+              allPageParams,
+              queryArg,
+            ) => {
+              expectTypeOf(lastPage).toEqualTypeOf<Pokemon[]>()
+
+              expectTypeOf(allPages).toEqualTypeOf<Pokemon[][]>()
+
+              expectTypeOf(lastPageParam).toBeNumber()
+
+              expectTypeOf(allPageParams).toEqualTypeOf<number[]>()
+
+              expectTypeOf(queryArg).toBeString()
+
+              return lastPageParam + 1
+            },
+          },
+          query({ pageParam, queryArg }) {
+            expectTypeOf(pageParam).toBeNumber()
+            expectTypeOf(queryArg).toBeString()
+
+            return `https://example.com/listItems?page=${pageParam}`
+          },
+          async onCacheEntryAdded(arg, api) {
+            const data = await api.cacheDataLoaded
+            expectTypeOf(data.data).toEqualTypeOf<
+              InfiniteData<Pokemon[], number>
+            >()
+          },
+          async onQueryStarted(arg, api) {
+            const data = await api.queryFulfilled
+            expectTypeOf(data.data).toEqualTypeOf<
+              InfiniteData<Pokemon[], number>
+            >()
+          },
+          providesTags: (result) => {
+            expectTypeOf(result).toEqualTypeOf<
+              InfiniteData<Pokemon[], number> | undefined
+            >()
+            return []
+          },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(pokemonApi, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    expectTypeOf(pokemonApi.endpoints.getInfinitePokemon.initiate)
+      .parameter(0)
+      .toBeString()
+
+    expectTypeOf(pokemonApi.useGetInfinitePokemonInfiniteQuery).toBeFunction()
+
+    expectTypeOf<
+      Parameters<
+        typeof pokemonApi.endpoints.getInfinitePokemon.useInfiniteQuery
+      >[0]
+    >().toEqualTypeOf<string | typeof skipToken>()
+
+    expectTypeOf(pokemonApi.endpoints.getInfinitePokemon.useInfiniteQueryState)
+      .parameter(0)
+      .toEqualTypeOf<string | typeof skipToken>()
+
+    expectTypeOf(
+      pokemonApi.endpoints.getInfinitePokemon.useInfiniteQuerySubscription,
+    )
+      .parameter(0)
+      .toEqualTypeOf<string | typeof skipToken>()
+
+    const slice = createSlice({
+      name: 'pokemon',
+      initialState: {} as { data: Pokemon[] },
+      reducers: {},
+      extraReducers: (builder) => {
+        builder.addMatcher(
+          pokemonApi.endpoints.getInfinitePokemon.matchFulfilled,
+          (state, action) => {
+            expectTypeOf(action.payload).toEqualTypeOf<
+              InfiniteData<Pokemon[], number>
+            >()
+          },
+        )
+      },
+    })
+
+    const res = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),
+    )
+
+    const firstResult = await res
+
+    if (firstResult.status === QueryStatus.fulfilled) {
+      expectTypeOf(firstResult.data.pages).toEqualTypeOf<Pokemon[][]>()
+      expectTypeOf(firstResult.data.pageParams).toEqualTypeOf<number[]>()
+    }
+
+    storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    const useGetInfinitePokemonQuery =
+      pokemonApi.endpoints.getInfinitePokemon.useInfiniteQuery
+
+    expectTypeOf<
+      Parameters<typeof useGetInfinitePokemonQuery>[0]
+    >().toEqualTypeOf<string | typeof skipToken>()
+
+    function PokemonList() {
+      const {
+        data,
+        currentData,
+        isFetching,
+        isUninitialized,
+        isSuccess,
+        fetchNextPage,
+      } = useGetInfinitePokemonQuery('a')
+
+      expectTypeOf(data).toEqualTypeOf<
+        InfiniteData<Pokemon[], number> | undefined
+      >()
+
+      if (isSuccess) {
+        expectTypeOf(data.pages).toEqualTypeOf<Pokemon[][]>()
+        expectTypeOf(data.pageParams).toEqualTypeOf<number[]>()
+      }
+
+      if (currentData) {
+        expectTypeOf(currentData.pages).toEqualTypeOf<Pokemon[][]>()
+        expectTypeOf(currentData.pageParams).toEqualTypeOf<number[]>()
+      }
+
+      const handleClick = async () => {
+        const res = await fetchNextPage()
+
+        if (res.status === QueryStatus.fulfilled) {
+          expectTypeOf(res.data.pages).toEqualTypeOf<Pokemon[][]>()
+          expectTypeOf(res.data.pageParams).toEqualTypeOf<number[]>()
+        }
+      }
+    }
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/infiniteQueries.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/infiniteQueries.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/infiniteQueries.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,1814 @@
+import { server } from '@internal/query/tests/mocks/server'
+import type { InfiniteQueryActionCreatorResult } from '@reduxjs/toolkit/query/react'
+import {
+  QueryStatus,
+  createApi,
+  fakeBaseQuery,
+  fetchBaseQuery,
+} from '@reduxjs/toolkit/query/react'
+import { HttpResponse, delay, http } from 'msw'
+import { actionsReducer, setupApiStore } from '../../tests/utils/helpers'
+import type { InfiniteQueryResultFlags } from '../core/buildSelectors'
+
+describe('Infinite queries', () => {
+  type Pokemon = {
+    id: string
+    name: string
+  }
+
+  type HitCounter = { page: number; hitCounter: number }
+  let counters: Record<string, number> = {}
+  let queryCounter = 0
+
+  const pokemonApi = createApi({
+    baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+    endpoints: (build) => ({
+      getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({
+        infiniteQueryOptions: {
+          initialPageParam: 0,
+          getNextPageParam: (
+            lastPage,
+            allPages,
+            lastPageParam,
+            allPageParams,
+            queryArg,
+          ) => {
+            expect(typeof queryArg).toBe('string')
+            return lastPageParam + 1
+          },
+          getPreviousPageParam: (
+            firstPage,
+            allPages,
+            firstPageParam,
+            allPageParams,
+            queryArg,
+          ) => {
+            expect(typeof queryArg).toBe('string')
+            return firstPageParam > 0 ? firstPageParam - 1 : undefined
+          },
+        },
+        query({ pageParam }) {
+          return `https://example.com/listItems?page=${pageParam}`
+        },
+      }),
+      getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>(
+        {
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            maxPages: 3,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+            getPreviousPageParam: (
+              firstPage,
+              allPages,
+              firstPageParam,
+              allPageParams,
+            ) => {
+              return firstPageParam > 0 ? firstPageParam - 1 : undefined
+            },
+          },
+          query({ pageParam }) {
+            return `https://example.com/listItems?page=${pageParam}`
+          },
+        },
+      ),
+      counters: build.query<{ id: string; counter: number }, string>({
+        queryFn: async (arg) => {
+          if (!(arg in counters)) {
+            counters[arg] = 0
+          }
+          counters[arg]++
+
+          return { data: { id: arg, counter: counters[arg] } }
+        },
+      }),
+    }),
+  })
+
+  function createCountersApi() {
+    let hitCounter = 0
+
+    const countersApi = createApi({
+      baseQuery: fakeBaseQuery(),
+      tagTypes: ['Counter'],
+      endpoints: (build) => ({
+        counters: build.infiniteQuery<HitCounter, string, number>({
+          queryFn({ pageParam }) {
+            hitCounter++
+
+            return { data: { page: pageParam, hitCounter } }
+          },
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+          },
+          providesTags: ['Counter'],
+        }),
+        mutation: build.mutation<null, void>({
+          queryFn: async () => {
+            return { data: null }
+          },
+          invalidatesTags: ['Counter'],
+        }),
+      }),
+    })
+
+    return countersApi
+  }
+
+  let storeRef = setupApiStore(
+    pokemonApi,
+    { ...actionsReducer },
+    {
+      withoutTestLifecycles: true,
+    },
+  )
+
+  beforeEach(() => {
+    server.use(
+      http.get('https://example.com/listItems', ({ request }) => {
+        const url = new URL(request.url)
+        const pageString = url.searchParams.get('page')
+        const pageNum = parseInt(pageString || '0')
+        queryCounter++
+
+        const results: Pokemon[] = [
+          { id: `${pageNum}`, name: `Pokemon ${pageNum}` },
+        ]
+        return HttpResponse.json(results)
+      }),
+    )
+
+    storeRef = setupApiStore(
+      pokemonApi,
+      { ...actionsReducer },
+      {
+        withoutTestLifecycles: true,
+      },
+    )
+
+    counters = {}
+
+    queryCounter = 0
+  })
+
+  type InfiniteQueryResult = Awaited<InfiniteQueryActionCreatorResult<any>>
+
+  const checkResultData = (
+    result: InfiniteQueryResult,
+    expectedValues: Pokemon[][],
+  ) => {
+    expect(result.status).toBe(QueryStatus.fulfilled)
+    if (result.status === QueryStatus.fulfilled) {
+      expect(result.data.pages).toEqual(expectedValues)
+    }
+  }
+
+  const checkResultLength = (
+    result: InfiniteQueryResult,
+    expectedLength: number,
+  ) => {
+    expect(result.status).toBe(QueryStatus.fulfilled)
+    if (result.status === QueryStatus.fulfilled) {
+      expect(result.data.pages).toHaveLength(expectedLength)
+    }
+  }
+
+  test('Basic infinite query behavior', async () => {
+    const checkFlags = (
+      value: unknown,
+      expectedFlags: Partial<InfiniteQueryResultFlags>,
+    ) => {
+      const actualFlags: InfiniteQueryResultFlags = {
+        hasNextPage: false,
+        hasPreviousPage: false,
+        isFetchingNextPage: false,
+        isFetchingPreviousPage: false,
+        isFetchNextPageError: false,
+        isFetchPreviousPageError: false,
+        ...expectedFlags,
+      }
+
+      expect(value).toMatchObject(actualFlags)
+    }
+
+    const checkEntryFlags = (
+      arg: string,
+      expectedFlags: Partial<InfiniteQueryResultFlags>,
+    ) => {
+      const selector = pokemonApi.endpoints.getInfinitePokemon.select(arg)
+      const entry = selector(storeRef.store.getState())
+
+      checkFlags(entry, expectedFlags)
+    }
+
+    const res1 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),
+    )
+
+    checkEntryFlags('fire', {})
+
+    const entry1InitialLoad = await res1
+
+    checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])
+    checkFlags(entry1InitialLoad, {
+      hasNextPage: true,
+    })
+
+    const res2 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    checkEntryFlags('fire', {
+      hasNextPage: true,
+      isFetchingNextPage: true,
+    })
+
+    const entry1SecondPage = await res2
+
+    checkResultData(entry1SecondPage, [
+      [{ id: '0', name: 'Pokemon 0' }],
+      [{ id: '1', name: 'Pokemon 1' }],
+    ])
+    checkFlags(entry1SecondPage, {
+      hasNextPage: true,
+    })
+
+    const res3 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'backward',
+      }),
+    )
+
+    checkEntryFlags('fire', {
+      hasNextPage: true,
+      isFetchingPreviousPage: true,
+    })
+
+    const entry1PrevPageMissing = await res3
+
+    checkResultData(entry1PrevPageMissing, [
+      [{ id: '0', name: 'Pokemon 0' }],
+      [{ id: '1', name: 'Pokemon 1' }],
+    ])
+    checkFlags(entry1PrevPageMissing, {
+      hasNextPage: true,
+    })
+
+    const res4 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('water', {
+        initialPageParam: 3,
+      }),
+    )
+
+    checkEntryFlags('water', {})
+
+    const entry2InitialLoad = await res4
+
+    checkResultData(entry2InitialLoad, [[{ id: '3', name: 'Pokemon 3' }]])
+    checkFlags(entry2InitialLoad, {
+      hasNextPage: true,
+      hasPreviousPage: true,
+    })
+
+    const res5 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('water', {
+        direction: 'forward',
+      }),
+    )
+
+    checkEntryFlags('water', {
+      hasNextPage: true,
+      hasPreviousPage: true,
+      isFetchingNextPage: true,
+    })
+
+    const entry2NextPage = await res5
+
+    checkResultData(entry2NextPage, [
+      [{ id: '3', name: 'Pokemon 3' }],
+      [{ id: '4', name: 'Pokemon 4' }],
+    ])
+    checkFlags(entry2NextPage, {
+      hasNextPage: true,
+      hasPreviousPage: true,
+    })
+
+    const res6 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('water', {
+        direction: 'backward',
+      }),
+    )
+
+    checkEntryFlags('water', {
+      hasNextPage: true,
+      hasPreviousPage: true,
+      isFetchingPreviousPage: true,
+    })
+
+    const entry2PrevPage = await res6
+
+    checkResultData(entry2PrevPage, [
+      [{ id: '2', name: 'Pokemon 2' }],
+      [{ id: '3', name: 'Pokemon 3' }],
+      [{ id: '4', name: 'Pokemon 4' }],
+    ])
+    checkFlags(entry2PrevPage, {
+      hasNextPage: true,
+      hasPreviousPage: true,
+    })
+  })
+
+  test('does not have a page limit without maxPages', async () => {
+    for (let i = 1; i <= 10; i++) {
+      const res = await storeRef.store.dispatch(
+        pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+          direction: 'forward',
+        }),
+      )
+
+      checkResultLength(res, i)
+    }
+  })
+
+  test('applies a page limit with maxPages', async () => {
+    for (let i = 1; i <= 10; i++) {
+      const res = await storeRef.store.dispatch(
+        pokemonApi.endpoints.getInfinitePokemonWithMax.initiate('fire', {
+          direction: 'forward',
+        }),
+      )
+
+      checkResultLength(res, Math.min(i, 3))
+    }
+
+    // Should now have entries 7, 8, 9 after the loop
+
+    const res = await storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemonWithMax.initiate('fire', {
+        direction: 'backward',
+      }),
+    )
+
+    checkResultData(res, [
+      [{ id: '6', name: 'Pokemon 6' }],
+      [{ id: '7', name: 'Pokemon 7' }],
+      [{ id: '8', name: 'Pokemon 8' }],
+    ])
+  })
+
+  test('validates maxPages during createApi call', async () => {
+    vi.stubEnv('NODE_ENV', 'development')
+
+    const createApiWithMaxPages = (
+      maxPages: number,
+      getPreviousPageParam: (() => number) | undefined,
+    ) => {
+      createApi({
+        baseQuery: fakeBaseQuery(),
+        endpoints: (build) => ({
+          getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({
+            query(pageParam) {
+              return `https://example.com/listItems?page=${pageParam}`
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              maxPages,
+              getNextPageParam: () => 1,
+              getPreviousPageParam,
+            },
+          }),
+        }),
+      })
+    }
+
+    expect(() => createApiWithMaxPages(0, () => 0)).toThrowError(
+      `maxPages for endpoint 'getInfinitePokemon' must be a number greater than 0`,
+    )
+
+    expect(() => createApiWithMaxPages(1, undefined)).toThrowError(
+      `getPreviousPageParam for endpoint 'getInfinitePokemon' must be a function if maxPages is used`,
+    )
+  })
+
+  test('refetches all existing pages', async () => {
+    const checkResultData = (
+      result: InfiniteQueryResult,
+      expectedValues: HitCounter[],
+    ) => {
+      expect(result.status).toBe(QueryStatus.fulfilled)
+      if (result.status === QueryStatus.fulfilled) {
+        expect(result.data.pages).toEqual(expectedValues)
+      }
+    }
+
+    const countersApi = createCountersApi()
+
+    const storeRef = setupApiStore(
+      countersApi,
+      { ...actionsReducer },
+      {
+        withoutTestLifecycles: true,
+      },
+    )
+
+    await storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        initialPageParam: 3,
+      }),
+    )
+
+    await storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        direction: 'forward',
+      }),
+    )
+
+    const thirdPromise = storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        direction: 'forward',
+      }),
+    )
+
+    const thirdRes = await thirdPromise
+
+    checkResultData(thirdRes, [
+      { page: 3, hitCounter: 1 },
+      { page: 4, hitCounter: 2 },
+      { page: 5, hitCounter: 3 },
+    ])
+
+    const fourthRes = await thirdPromise.refetch()
+
+    checkResultData(fourthRes, [
+      { page: 3, hitCounter: 4 },
+      { page: 4, hitCounter: 5 },
+      { page: 5, hitCounter: 6 },
+    ])
+  })
+
+  test('Refetches on invalidation', async () => {
+    const checkResultData = (
+      result: InfiniteQueryResult,
+      expectedValues: HitCounter[],
+    ) => {
+      expect(result.status).toBe(QueryStatus.fulfilled)
+      if (result.status === QueryStatus.fulfilled) {
+        expect(result.data.pages).toEqual(expectedValues)
+      }
+    }
+
+    const countersApi = createCountersApi()
+
+    const storeRef = setupApiStore(
+      countersApi,
+      { ...actionsReducer },
+      {
+        withoutTestLifecycles: true,
+      },
+    )
+
+    await storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        initialPageParam: 3,
+      }),
+    )
+
+    await storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        direction: 'forward',
+      }),
+    )
+
+    const thirdPromise = storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        direction: 'forward',
+      }),
+    )
+
+    const thirdRes = await thirdPromise
+
+    checkResultData(thirdRes, [
+      { page: 3, hitCounter: 1 },
+      { page: 4, hitCounter: 2 },
+      { page: 5, hitCounter: 3 },
+    ])
+
+    await storeRef.store.dispatch(countersApi.endpoints.mutation.initiate())
+
+    let entry = countersApi.endpoints.counters.select('item')(
+      storeRef.store.getState(),
+    )
+    const promise = storeRef.store.dispatch(
+      countersApi.util.getRunningQueryThunk('counters', 'item'),
+    )
+    const promises = storeRef.store.dispatch(
+      countersApi.util.getRunningQueriesThunk(),
+    )
+    expect(entry).toMatchObject({
+      status: 'pending',
+    })
+
+    expect(promise).toBeInstanceOf(Promise)
+
+    expect(promises).toEqual([promise])
+
+    const finalRes = await promise
+
+    checkResultData(finalRes as any, [
+      { page: 3, hitCounter: 4 },
+      { page: 4, hitCounter: 5 },
+      { page: 5, hitCounter: 6 },
+    ])
+  })
+
+  test('Refetches on polling', async () => {
+    const countersApi = createCountersApi()
+    const checkResultData = (
+      result: InfiniteQueryResult,
+      expectedValues: HitCounter[],
+    ) => {
+      expect(result.status).toBe(QueryStatus.fulfilled)
+      if (result.status === QueryStatus.fulfilled) {
+        expect(result.data.pages).toEqual(expectedValues)
+      }
+    }
+
+    const storeRef = setupApiStore(
+      countersApi,
+      { ...actionsReducer },
+      {
+        withoutTestLifecycles: true,
+      },
+    )
+
+    await storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        initialPageParam: 3,
+      }),
+    )
+
+    await storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        direction: 'forward',
+      }),
+    )
+
+    const thirdPromise = storeRef.store.dispatch(
+      countersApi.endpoints.counters.initiate('item', {
+        direction: 'forward',
+      }),
+    )
+
+    const thirdRes = await thirdPromise
+
+    checkResultData(thirdRes, [
+      { page: 3, hitCounter: 1 },
+      { page: 4, hitCounter: 2 },
+      { page: 5, hitCounter: 3 },
+    ])
+
+    thirdPromise.updateSubscriptionOptions({
+      pollingInterval: 50,
+    })
+
+    await delay(25)
+
+    let entry = countersApi.endpoints.counters.select('item')(
+      storeRef.store.getState(),
+    )
+
+    checkResultData(thirdRes, [
+      { page: 3, hitCounter: 1 },
+      { page: 4, hitCounter: 2 },
+      { page: 5, hitCounter: 3 },
+    ])
+
+    await delay(50)
+
+    entry = countersApi.endpoints.counters.select('item')(
+      storeRef.store.getState(),
+    )
+
+    checkResultData(entry as any, [
+      { page: 3, hitCounter: 4 },
+      { page: 4, hitCounter: 5 },
+      { page: 5, hitCounter: 6 },
+    ])
+  })
+
+  test('Handles multiple next page fetches at once', async () => {
+    const initialEntry = await storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),
+    )
+
+    checkResultData(initialEntry, [[{ id: '0', name: 'Pokemon 0' }]])
+
+    expect(queryCounter).toBe(1)
+
+    const promise1 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    expect(queryCounter).toBe(1)
+
+    const promise2 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    const entry1 = await promise1
+    const entry2 = await promise2
+
+    // The second thunk should have bailed out because the entry was now
+    // pending, so we should only have sent one request.
+    expect(queryCounter).toBe(2)
+
+    expect(entry1).toEqual(entry2)
+
+    checkResultData(entry1, [
+      [{ id: '0', name: 'Pokemon 0' }],
+      [{ id: '1', name: 'Pokemon 1' }],
+    ])
+
+    expect(queryCounter).toBe(2)
+
+    const promise3 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    expect(queryCounter).toBe(2)
+
+    // We can abort an existing promise, but due to timing issues,
+    // we have to await the promise first before triggering the next request.
+    promise3.abort()
+    const entry3 = await promise3
+
+    const promise4 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    const entry4 = await promise4
+
+    expect(queryCounter).toBe(4)
+
+    checkResultData(entry4, [
+      [{ id: '0', name: 'Pokemon 0' }],
+      [{ id: '1', name: 'Pokemon 1' }],
+      [{ id: '2', name: 'Pokemon 2' }],
+    ])
+  })
+
+  test('can fetch pages with refetchOnMountOrArgChange active', async () => {
+    const pokemonApiWithRefetch = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+      endpoints: (build) => ({
+        getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              // Page param type should be `number`
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+            getPreviousPageParam: (
+              firstPage,
+              allPages,
+              firstPageParam,
+              allPageParams,
+            ) => {
+              return firstPageParam > 0 ? firstPageParam - 1 : undefined
+            },
+          },
+          query({ pageParam }) {
+            return `https://example.com/listItems?page=${pageParam}`
+          },
+        }),
+      }),
+      refetchOnMountOrArgChange: true,
+    })
+
+    const storeRef = setupApiStore(
+      pokemonApiWithRefetch,
+      { ...actionsReducer },
+      {
+        withoutTestLifecycles: true,
+      },
+    )
+
+    const res1 = storeRef.store.dispatch(
+      pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('fire', {}),
+    )
+
+    const entry1InitialLoad = await res1
+    checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])
+
+    const res2 = storeRef.store.dispatch(
+      pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    const entry1SecondPage = await res2
+    checkResultData(entry1SecondPage, [
+      [{ id: '0', name: 'Pokemon 0' }],
+      [{ id: '1', name: 'Pokemon 1' }],
+    ])
+
+    expect(queryCounter).toBe(2)
+
+    const entry2InitialLoad = await storeRef.store.dispatch(
+      pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('water', {}),
+    )
+
+    checkResultData(entry2InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])
+
+    expect(queryCounter).toBe(3)
+
+    const entry2SecondPage = await storeRef.store.dispatch(
+      pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('water', {
+        direction: 'forward',
+      }),
+    )
+    checkResultData(entry2SecondPage, [
+      [{ id: '0', name: 'Pokemon 0' }],
+      [{ id: '1', name: 'Pokemon 1' }],
+    ])
+
+    expect(queryCounter).toBe(4)
+
+    // Should now be able to switch back to the first query.
+    // The hooks dispatch on arg change without a direction.
+    // That should trigger a refetch of the first query, meaning two requests.
+    // It should also _replace_ the existing results, rather than appending
+    // duplicate entries ([0, 1, 0, 1])
+    const entry1Refetched = await storeRef.store.dispatch(
+      pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('fire', {}),
+    )
+
+    checkResultData(entry1Refetched, [
+      [{ id: '0', name: 'Pokemon 0' }],
+      [{ id: '1', name: 'Pokemon 1' }],
+    ])
+
+    expect(queryCounter).toBe(6)
+  })
+
+  test('Works with cache manipulation utils', async () => {
+    const res1 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),
+    )
+
+    const entry1InitialLoad = await res1
+    checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])
+
+    storeRef.store.dispatch(
+      pokemonApi.util.updateQueryData('getInfinitePokemon', 'fire', (draft) => {
+        draft.pages.push([{ id: '1', name: 'Pokemon 1' }])
+        draft.pageParams.push(1)
+      }),
+    )
+
+    const selectFire = pokemonApi.endpoints.getInfinitePokemon.select('fire')
+    const entry1Updated = selectFire(storeRef.store.getState())
+
+    expect(entry1Updated.data).toEqual({
+      pages: [
+        [{ id: '0', name: 'Pokemon 0' }],
+        [{ id: '1', name: 'Pokemon 1' }],
+      ],
+      pageParams: [0, 1],
+    })
+
+    const res2 = storeRef.store.dispatch(
+      pokemonApi.util.upsertQueryData('getInfinitePokemon', 'water', {
+        pages: [[{ id: '2', name: 'Pokemon 2' }]],
+        pageParams: [2],
+      }),
+    )
+
+    const entry2InitialLoad = await res2
+    const selectWater = pokemonApi.endpoints.getInfinitePokemon.select('water')
+    const entry2Updated = selectWater(storeRef.store.getState())
+
+    expect(entry2Updated.data).toEqual({
+      pages: [[{ id: '2', name: 'Pokemon 2' }]],
+      pageParams: [2],
+    })
+
+    storeRef.store.dispatch(
+      pokemonApi.util.upsertQueryEntries([
+        {
+          endpointName: 'getInfinitePokemon',
+          arg: 'air',
+          value: {
+            pages: [[{ id: '3', name: 'Pokemon 3' }]],
+            pageParams: [3],
+          },
+        },
+      ]),
+    )
+
+    const selectAir = pokemonApi.endpoints.getInfinitePokemon.select('air')
+    const entry3Initial = selectAir(storeRef.store.getState())
+
+    expect(entry3Initial.data).toEqual({
+      pages: [[{ id: '3', name: 'Pokemon 3' }]],
+      pageParams: [3],
+    })
+
+    await storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemon.initiate('air', {
+        direction: 'forward',
+      }),
+    )
+
+    const entry3Updated = selectAir(storeRef.store.getState())
+
+    expect(entry3Updated.data).toEqual({
+      pages: [
+        [{ id: '3', name: 'Pokemon 3' }],
+        [{ id: '4', name: 'Pokemon 4' }],
+      ],
+      pageParams: [3, 4],
+    })
+  })
+
+  test('Cache lifecycle methods are called', async () => {
+    const cacheEntryAddedCallback = vi.fn()
+    const queryStartedCallback = vi.fn()
+
+    const pokemonApi = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+      endpoints: (build) => ({
+        getInfinitePokemonWithLifecycles: build.infiniteQuery<
+          Pokemon[],
+          string,
+          number
+        >({
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              // Page param type should be `number`
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+            getPreviousPageParam: (
+              firstPage,
+              allPages,
+              firstPageParam,
+              allPageParams,
+            ) => {
+              return firstPageParam > 0 ? firstPageParam - 1 : undefined
+            },
+          },
+          query({ pageParam }) {
+            return `https://example.com/listItems?page=${pageParam}`
+          },
+          async onCacheEntryAdded(arg, api) {
+            const data = await api.cacheDataLoaded
+            cacheEntryAddedCallback(arg, data)
+          },
+          async onQueryStarted(arg, api) {
+            const data = await api.queryFulfilled
+            queryStartedCallback(arg, data)
+          },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(
+      pokemonApi,
+      { ...actionsReducer },
+      {
+        withoutTestLifecycles: true,
+      },
+    )
+
+    const res1 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemonWithLifecycles.initiate(
+        'fire',
+        {},
+      ),
+    )
+
+    const entry1InitialLoad = await res1
+    checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])
+
+    expect(cacheEntryAddedCallback).toHaveBeenCalledWith('fire', {
+      data: {
+        pages: [[{ id: '0', name: 'Pokemon 0' }]],
+        pageParams: [0],
+      },
+      meta: expect.objectContaining({
+        request: expect.anything(),
+        response: expect.anything(),
+      }),
+    })
+
+    expect(queryStartedCallback).toHaveBeenCalledWith('fire', {
+      data: {
+        pages: [[{ id: '0', name: 'Pokemon 0' }]],
+        pageParams: [0],
+      },
+      meta: expect.objectContaining({
+        request: expect.anything(),
+        response: expect.anything(),
+      }),
+    })
+  })
+
+  test('Can use transformResponse', async () => {
+    type PokemonPage = { items: Pokemon[]; page: number }
+    const pokemonApi = createApi({
+      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
+      endpoints: (build) => ({
+        getInfinitePokemonWithTransform: build.infiniteQuery<
+          PokemonPage,
+          string,
+          number
+        >({
+          infiniteQueryOptions: {
+            initialPageParam: 0,
+            getNextPageParam: (
+              lastPage,
+              allPages,
+              // Page param type should be `number`
+              lastPageParam,
+              allPageParams,
+            ) => lastPageParam + 1,
+          },
+          query({ pageParam }) {
+            return `https://example.com/listItems?page=${pageParam}`
+          },
+          transformResponse(baseQueryReturnValue: Pokemon[], meta, arg) {
+            expect(Array.isArray(baseQueryReturnValue)).toBe(true)
+            return {
+              items: baseQueryReturnValue,
+              page: arg.pageParam,
+            }
+          },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(
+      pokemonApi,
+      { ...actionsReducer },
+      {
+        withoutTestLifecycles: true,
+      },
+    )
+
+    const checkResultData = (
+      result: InfiniteQueryResult,
+      expectedValues: PokemonPage[],
+    ) => {
+      expect(result.status).toBe(QueryStatus.fulfilled)
+      if (result.status === QueryStatus.fulfilled) {
+        expect(result.data.pages).toEqual(expectedValues)
+      }
+    }
+
+    const res1 = storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemonWithTransform.initiate('fire', {}),
+    )
+
+    const entry1InitialLoad = await res1
+    checkResultData(entry1InitialLoad, [
+      { items: [{ id: '0', name: 'Pokemon 0' }], page: 0 },
+    ])
+
+    const entry1Updated = await storeRef.store.dispatch(
+      pokemonApi.endpoints.getInfinitePokemonWithTransform.initiate('fire', {
+        direction: 'forward',
+      }),
+    )
+
+    checkResultData(entry1Updated, [
+      { items: [{ id: '0', name: 'Pokemon 0' }], page: 0 },
+      { items: [{ id: '1', name: 'Pokemon 1' }], page: 1 },
+    ])
+  })
+
+  describe('refetchCachedPages option', () => {
+    test('refetches all pages by default (refetchCachedPages: true)', async () => {
+      let hitCounter = 0
+
+      const countersApi = createApi({
+        baseQuery: fakeBaseQuery(),
+        tagTypes: ['Counter'],
+        endpoints: (build) => ({
+          counters: build.infiniteQuery<HitCounter, string, number>({
+            queryFn({ pageParam }) {
+              hitCounter++
+              return { data: { page: pageParam, hitCounter } }
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => lastPageParam + 1,
+            },
+            providesTags: ['Counter'],
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(
+        countersApi,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      // Load 3 pages
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          initialPageParam: 0,
+        }),
+      )
+
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdPromise = storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdRes = await thirdPromise
+
+      // Should have 3 pages with hitCounters 1, 2, 3
+      expect(thirdRes.data!.pages).toEqual([
+        { page: 0, hitCounter: 1 },
+        { page: 1, hitCounter: 2 },
+        { page: 2, hitCounter: 3 },
+      ])
+
+      // Refetch without specifying refetchCachedPages
+      const refetchRes = await thirdPromise.refetch()
+
+      // All 3 pages should be refetched (hitCounters 4, 5, 6)
+      expect(refetchRes.data!.pages).toEqual([
+        { page: 0, hitCounter: 4 },
+        { page: 1, hitCounter: 5 },
+        { page: 2, hitCounter: 6 },
+      ])
+      expect(refetchRes.data!.pages).toHaveLength(3)
+    })
+
+    test('refetches all pages when refetchCachedPages is explicitly true', async () => {
+      let hitCounter = 0
+
+      const countersApi = createApi({
+        baseQuery: fakeBaseQuery(),
+        tagTypes: ['Counter'],
+        endpoints: (build) => ({
+          counters: build.infiniteQuery<HitCounter, string, number>({
+            queryFn({ pageParam }) {
+              hitCounter++
+              return { data: { page: pageParam, hitCounter } }
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => lastPageParam + 1,
+              refetchCachedPages: true, // Explicit true
+            },
+            providesTags: ['Counter'],
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(
+        countersApi,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      // Load 3 pages
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          initialPageParam: 0,
+        }),
+      )
+
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdPromise = storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdRes = await thirdPromise
+
+      expect(thirdRes.data!.pages).toHaveLength(3)
+
+      // Refetch
+      const refetchRes = await thirdPromise.refetch()
+
+      // All 3 pages should be refetched
+      expect(refetchRes.data!.pages).toHaveLength(3)
+      expect(refetchRes.data!.pages[0].hitCounter).toBeGreaterThan(
+        thirdRes.data!.pages[0].hitCounter,
+      )
+    })
+
+    test('refetches only first page when refetchCachedPages is false', async () => {
+      let hitCounter = 0
+
+      const countersApi = createApi({
+        baseQuery: fakeBaseQuery(),
+        tagTypes: ['Counter'],
+        endpoints: (build) => ({
+          counters: build.infiniteQuery<HitCounter, string, number>({
+            queryFn({ pageParam }) {
+              hitCounter++
+              return { data: { page: pageParam, hitCounter } }
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => lastPageParam + 1,
+              refetchCachedPages: false, // Only refetch first page
+            },
+            providesTags: ['Counter'],
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(
+        countersApi,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      // Load 3 pages
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          initialPageParam: 0,
+        }),
+      )
+
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdPromise = storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdRes = await thirdPromise
+
+      // Should have 3 pages with hitCounters 1, 2, 3
+      expect(thirdRes.data!.pages).toEqual([
+        { page: 0, hitCounter: 1 },
+        { page: 1, hitCounter: 2 },
+        { page: 2, hitCounter: 3 },
+      ])
+
+      // Refetch with refetchCachedPages: false
+      const refetchRes = await thirdPromise.refetch()
+
+      // Only first page should be refetched, cache reset to 1 page
+      expect(refetchRes.data!.pages).toEqual([{ page: 0, hitCounter: 4 }])
+      expect(refetchRes.data!.pageParams).toEqual([0])
+    })
+
+    test('refetches only first page on tag invalidation when refetchCachedPages is false', async () => {
+      let hitCounter = 0
+
+      const countersApi = createApi({
+        baseQuery: fakeBaseQuery(),
+        tagTypes: ['Counter'],
+        endpoints: (build) => ({
+          counters: build.infiniteQuery<HitCounter, string, number>({
+            queryFn({ pageParam }) {
+              hitCounter++
+              return { data: { page: pageParam, hitCounter } }
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => lastPageParam + 1,
+              refetchCachedPages: false,
+            },
+            providesTags: ['Counter'],
+          }),
+          mutation: build.mutation<null, void>({
+            queryFn: async () => ({ data: null }),
+            invalidatesTags: ['Counter'],
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(
+        countersApi,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      // Load 3 pages
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          initialPageParam: 0,
+        }),
+      )
+
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      // Verify we have 3 pages
+      let entry = countersApi.endpoints.counters.select('item')(
+        storeRef.store.getState(),
+      )
+      expect(entry.data?.pages).toHaveLength(3)
+
+      // Trigger mutation to invalidate tags
+      await storeRef.store.dispatch(countersApi.endpoints.mutation.initiate())
+
+      // Wait for refetch to complete
+      const promise = storeRef.store.dispatch(
+        countersApi.util.getRunningQueryThunk('counters', 'item'),
+      )
+      const finalRes = await promise
+
+      // Only first page should be refetched
+      expect((finalRes as any).data.pages).toEqual([{ page: 0, hitCounter: 4 }])
+    })
+
+    test('refetches only first page during polling when refetchCachedPages is false', async () => {
+      let hitCounter = 0
+
+      const countersApi = createApi({
+        baseQuery: fakeBaseQuery(),
+        endpoints: (build) => ({
+          counters: build.infiniteQuery<HitCounter, string, number>({
+            queryFn({ pageParam }) {
+              hitCounter++
+              return { data: { page: pageParam, hitCounter } }
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => lastPageParam + 1,
+              refetchCachedPages: false,
+            },
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(
+        countersApi,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      // Load 3 pages
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          initialPageParam: 0,
+        }),
+      )
+
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdPromise = storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      await thirdPromise
+
+      // Enable polling
+      thirdPromise.updateSubscriptionOptions({
+        pollingInterval: 50,
+      })
+
+      // Wait for first poll
+      await delay(75)
+
+      const entry = countersApi.endpoints.counters.select('item')(
+        storeRef.store.getState(),
+      )
+
+      // Should only have 1 page after poll
+      expect(entry.data?.pages).toEqual([{ page: 0, hitCounter: 4 }])
+    })
+
+    test('refetchCachedPages: false works with maxPages', async () => {
+      let hitCounter = 0
+
+      const countersApi = createApi({
+        baseQuery: fakeBaseQuery(),
+        endpoints: (build) => ({
+          counters: build.infiniteQuery<HitCounter, string, number>({
+            queryFn({ pageParam }) {
+              hitCounter++
+              return { data: { page: pageParam, hitCounter } }
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              maxPages: 3,
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => lastPageParam + 1,
+              getPreviousPageParam: (
+                firstPage,
+                allPages,
+                firstPageParam,
+                allPageParams,
+              ) => (firstPageParam > 0 ? firstPageParam - 1 : undefined),
+              refetchCachedPages: false,
+            },
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(
+        countersApi,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      // Load 5 pages (but maxPages will limit to 3)
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          initialPageParam: 0,
+        }),
+      )
+
+      for (let i = 0; i < 4; i++) {
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+      }
+
+      let entry = countersApi.endpoints.counters.select('item')(
+        storeRef.store.getState(),
+      )
+
+      // Should have 3 pages due to maxPages
+      expect(entry.data?.pages).toHaveLength(3)
+
+      // Refetch
+      const refetchPromise = storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          forceRefetch: true,
+        }),
+      )
+
+      const refetchRes = await refetchPromise
+
+      // Should only have 1 page after refetch (refetchCachedPages: false)
+      // Note: With maxPages: 3, the cache kept pages 2, 3, 4
+      // So refetch starts from the first cached page param, which is 2
+      expect(refetchRes.data!.pages).toHaveLength(1)
+      expect(refetchRes.data!.pages[0].page).toBe(2)
+    })
+
+    test('can fetch next page after refetch with refetchCachedPages: false', async () => {
+      let hitCounter = 0
+
+      const countersApi = createApi({
+        baseQuery: fakeBaseQuery(),
+        endpoints: (build) => ({
+          counters: build.infiniteQuery<HitCounter, string, number>({
+            queryFn({ pageParam }) {
+              hitCounter++
+              return { data: { page: pageParam, hitCounter } }
+            },
+            infiniteQueryOptions: {
+              initialPageParam: 0,
+              getNextPageParam: (
+                lastPage,
+                allPages,
+                lastPageParam,
+                allPageParams,
+              ) => lastPageParam + 1,
+              refetchCachedPages: false,
+            },
+          }),
+        }),
+      })
+
+      const storeRef = setupApiStore(
+        countersApi,
+        { ...actionsReducer },
+        {
+          withoutTestLifecycles: true,
+        },
+      )
+
+      // Load 3 pages
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          initialPageParam: 0,
+        }),
+      )
+
+      await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      const thirdPromise = storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      await thirdPromise
+
+      // Refetch (resets to 1 page)
+      await thirdPromise.refetch()
+
+      let entry = countersApi.endpoints.counters.select('item')(
+        storeRef.store.getState(),
+      )
+      expect(entry.data?.pages).toHaveLength(1)
+
+      // Fetch next page
+      const nextPageRes = await storeRef.store.dispatch(
+        countersApi.endpoints.counters.initiate('item', {
+          direction: 'forward',
+        }),
+      )
+
+      // Should now have 2 pages
+      expect(nextPageRes.data!.pages).toEqual([
+        { page: 0, hitCounter: 4 },
+        { page: 1, hitCounter: 5 },
+      ])
+    })
+
+    describe('per-call refetchCachedPages override', () => {
+      test('per-call false overrides endpoint true', async () => {
+        let hitCounter = 0
+
+        const countersApi = createApi({
+          baseQuery: fakeBaseQuery(),
+          endpoints: (build) => ({
+            counters: build.infiniteQuery<HitCounter, string, number>({
+              queryFn({ pageParam }) {
+                hitCounter++
+                return { data: { page: pageParam, hitCounter } }
+              },
+              infiniteQueryOptions: {
+                initialPageParam: 0,
+                getNextPageParam: (
+                  lastPage,
+                  allPages,
+                  lastPageParam,
+                  allPageParams,
+                ) => lastPageParam + 1,
+                refetchCachedPages: true, // Endpoint default: refetch all
+              },
+            }),
+          }),
+        })
+
+        const storeRef = setupApiStore(
+          countersApi,
+          { ...actionsReducer },
+          {
+            withoutTestLifecycles: true,
+          },
+        )
+
+        // Load 3 pages
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            initialPageParam: 0,
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        // Should have 3 pages with hitCounters 1, 2, 3
+        let entry = countersApi.endpoints.counters.select('item')(
+          storeRef.store.getState(),
+        )
+        expect(entry.data?.pages).toEqual([
+          { page: 0, hitCounter: 1 },
+          { page: 1, hitCounter: 2 },
+          { page: 2, hitCounter: 3 },
+        ])
+
+        // Refetch with per-call override: false
+        const refetchRes = await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            forceRefetch: true,
+            refetchCachedPages: false, // Override to false
+          }),
+        )
+
+        // Only first page should be refetched (hitCounter 4)
+        expect(refetchRes.data!.pages).toEqual([{ page: 0, hitCounter: 4 }])
+        expect(refetchRes.data!.pageParams).toEqual([0])
+      })
+
+      test('per-call true overrides endpoint false', async () => {
+        let hitCounter = 0
+
+        const countersApi = createApi({
+          baseQuery: fakeBaseQuery(),
+          endpoints: (build) => ({
+            counters: build.infiniteQuery<HitCounter, string, number>({
+              queryFn({ pageParam }) {
+                hitCounter++
+                return { data: { page: pageParam, hitCounter } }
+              },
+              infiniteQueryOptions: {
+                initialPageParam: 0,
+                getNextPageParam: (
+                  lastPage,
+                  allPages,
+                  lastPageParam,
+                  allPageParams,
+                ) => lastPageParam + 1,
+                refetchCachedPages: false, // Endpoint default: only first page
+              },
+            }),
+          }),
+        })
+
+        const storeRef = setupApiStore(
+          countersApi,
+          { ...actionsReducer },
+          {
+            withoutTestLifecycles: true,
+          },
+        )
+
+        // Load 3 pages
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            initialPageParam: 0,
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        // Should have 3 pages
+        let entry = countersApi.endpoints.counters.select('item')(
+          storeRef.store.getState(),
+        )
+        expect(entry.data?.pages).toHaveLength(3)
+
+        // Refetch with per-call override: true
+        const refetchRes = await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            forceRefetch: true,
+            refetchCachedPages: true, // Override to true
+          }),
+        )
+
+        // All 3 pages should be refetched
+        expect(refetchRes.data!.pages).toEqual([
+          { page: 0, hitCounter: 4 },
+          { page: 1, hitCounter: 5 },
+          { page: 2, hitCounter: 6 },
+        ])
+        expect(refetchRes.data!.pages).toHaveLength(3)
+      })
+
+      test('uses endpoint config when no per-call override', async () => {
+        let hitCounter = 0
+
+        const countersApi = createApi({
+          baseQuery: fakeBaseQuery(),
+          endpoints: (build) => ({
+            counters: build.infiniteQuery<HitCounter, string, number>({
+              queryFn({ pageParam }) {
+                hitCounter++
+                return { data: { page: pageParam, hitCounter } }
+              },
+              infiniteQueryOptions: {
+                initialPageParam: 0,
+                getNextPageParam: (
+                  lastPage,
+                  allPages,
+                  lastPageParam,
+                  allPageParams,
+                ) => lastPageParam + 1,
+                refetchCachedPages: false, // Endpoint config
+              },
+            }),
+          }),
+        })
+
+        const storeRef = setupApiStore(
+          countersApi,
+          { ...actionsReducer },
+          {
+            withoutTestLifecycles: true,
+          },
+        )
+
+        // Load 3 pages
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            initialPageParam: 0,
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        // Refetch without per-call override
+        const refetchRes = await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            forceRefetch: true,
+            // No refetchCachedPages specified
+          }),
+        )
+
+        // Should use endpoint config (false) - only first page
+        expect(refetchRes.data!.pages).toEqual([{ page: 0, hitCounter: 4 }])
+      })
+
+      test('defaults to true when no config at any level', async () => {
+        let hitCounter = 0
+
+        const countersApi = createApi({
+          baseQuery: fakeBaseQuery(),
+          endpoints: (build) => ({
+            counters: build.infiniteQuery<HitCounter, string, number>({
+              queryFn({ pageParam }) {
+                hitCounter++
+                return { data: { page: pageParam, hitCounter } }
+              },
+              infiniteQueryOptions: {
+                initialPageParam: 0,
+                getNextPageParam: (
+                  lastPage,
+                  allPages,
+                  lastPageParam,
+                  allPageParams,
+                ) => lastPageParam + 1,
+                // No refetchCachedPages specified
+              },
+            }),
+          }),
+        })
+
+        const storeRef = setupApiStore(
+          countersApi,
+          { ...actionsReducer },
+          {
+            withoutTestLifecycles: true,
+          },
+        )
+
+        // Load 3 pages
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            initialPageParam: 0,
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            direction: 'forward',
+          }),
+        )
+
+        // Refetch without any config
+        const refetchRes = await storeRef.store.dispatch(
+          countersApi.endpoints.counters.initiate('item', {
+            forceRefetch: true,
+          }),
+        )
+
+        // Should default to true - refetch all pages
+        expect(refetchRes.data!.pages).toEqual([
+          { page: 0, hitCounter: 4 },
+          { page: 1, hitCounter: 5 },
+          { page: 2, hitCounter: 6 },
+        ])
+      })
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/injectEndpoints.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/injectEndpoints.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/injectEndpoints.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,121 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import { configureStore } from '@internal/configureStore'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+
+const api = createApi({
+  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+  endpoints: () => ({}),
+})
+
+describe('injectEndpoints', () => {
+  const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+  afterEach(() => {
+    vi.clearAllMocks()
+    vi.unstubAllEnvs()
+  })
+
+  afterAll(() => {
+    vi.restoreAllMocks()
+    vi.unstubAllEnvs()
+  })
+
+  test("query: overriding with `overrideEndpoints`='throw' throws an error", async () => {
+    const extended = api.injectEndpoints({
+      endpoints: (build) => ({
+        injected: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+    })
+
+    expect(() => {
+      extended.injectEndpoints({
+        overrideExisting: 'throw',
+        endpoints: (build) => ({
+          injected: build.query<unknown, string>({
+            query: () => '/success',
+          }),
+        }),
+      })
+    }).toThrowError(
+      new Error(
+        `called \`injectEndpoints\` to override already-existing endpointName injected without specifying \`overrideExisting: true\``,
+      ),
+    )
+  })
+
+  test('query: overriding an endpoint with `overrideEndpoints`=false does nothing in production', async () => {
+    vi.stubEnv('NODE_ENV', 'development')
+
+    const extended = api.injectEndpoints({
+      endpoints: (build) => ({
+        injected: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+    })
+
+    extended.injectEndpoints({
+      overrideExisting: false,
+      endpoints: (build) => ({
+        injected: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+    })
+
+    expect(consoleErrorSpy).toHaveBeenCalledWith(
+      `called \`injectEndpoints\` to override already-existing endpointName injected without specifying \`overrideExisting: true\``,
+    )
+  })
+
+  test('query: overriding with `overrideEndpoints`=false logs an error in development', async () => {
+    vi.stubEnv('NODE_ENV', 'production')
+
+    const extended = api.injectEndpoints({
+      endpoints: (build) => ({
+        injected: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+    })
+
+    extended.injectEndpoints({
+      overrideExisting: false,
+      endpoints: (build) => ({
+        injected: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+    })
+
+    expect(consoleErrorSpy).not.toHaveBeenCalled()
+  })
+
+  test('adding the same middleware to the store twice throws an error', () => {
+    // Strictly speaking this is a duplicate of the tests in configureStore.test.ts,
+    // but this helps confirm that we throw the error for adding
+    // the same API middleware twice.
+    const extendedApi = api.injectEndpoints({
+      endpoints: (build) => ({
+        injected: build.query<unknown, string>({
+          query: () => '/success',
+        }),
+      }),
+    })
+
+    const makeStore = () =>
+      configureStore({
+        reducer: {
+          api: api.reducer,
+        },
+        middleware: (getDefaultMiddleware) =>
+          getDefaultMiddleware().concat(api.middleware, extendedApi.middleware),
+      })
+
+    expect(makeStore).toThrowError(
+      'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.',
+    )
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/invalidation.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/invalidation.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/invalidation.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,146 @@
+import type { TagDescription } from '@reduxjs/toolkit/query'
+import { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query'
+import { waitFor } from '@testing-library/react'
+import { delay } from 'msw'
+import { setupApiStore } from '../../tests/utils/helpers'
+
+const tagTypes = [
+  'apple',
+  'pear',
+  'banana',
+  'tomato',
+  'cat',
+  'dog',
+  'giraffe',
+] as const
+type TagTypes = (typeof tagTypes)[number]
+type ProvidedTags = TagDescription<TagTypes>[] 
+type InvalidatesTags = (ProvidedTags[number] | null | undefined)[]
+/** providesTags, invalidatesTags, shouldInvalidate */
+const caseMatrix: [ProvidedTags, InvalidatesTags, boolean][] = [
+  // *****************************
+  // basic invalidation behavior
+  // *****************************
+
+  // string
+  [['apple'], ['apple'], true],
+  [['apple'], ['pear'], false],
+  // string and type only behave identical
+  [[{ type: 'apple' }], ['apple'], true],
+  [[{ type: 'apple' }], ['pear'], false],
+  [['apple'], [{ type: 'apple' }], true],
+  [['apple'], [{ type: 'pear' }], false],
+  // type only invalidates type + id
+  [[{ type: 'apple', id: 1 }], [{ type: 'apple' }], true],
+  [[{ type: 'pear', id: 1 }], ['apple'], false],
+  // type + id never invalidates type only
+  [['apple'], [{ type: 'apple', id: 1 }], false],
+  [['pear'], [{ type: 'apple', id: 1 }], false],
+  // type + id invalidates type + id
+  [[{ type: 'apple', id: 1 }], [{ type: 'apple', id: 1 }], true],
+  [[{ type: 'apple', id: 1 }], [{ type: 'apple', id: 2 }], false],
+  // null and undefined
+  [['apple'], [null], false],
+  [['apple'], [undefined], false],
+  [['apple'], [null, 'apple'], true],
+  [['apple'], [undefined, 'apple'], true],
+  // *****************************
+  // test multiple values in array
+  // *****************************
+
+  [['apple', 'banana', 'tomato'], ['apple'], true],
+  [['apple'], ['pear', 'banana', 'tomato'], false],
+  [
+    [
+      { type: 'apple', id: 1 },
+      { type: 'apple', id: 3 },
+      { type: 'apple', id: 4 },
+    ],
+    [{ type: 'apple', id: 1 }],
+    true,
+  ],
+  [
+    [{ type: 'apple', id: 1 }],
+    [
+      { type: 'apple', id: 2 },
+      { type: 'apple', id: 3 },
+      { type: 'apple', id: 4 },
+    ],
+    false,
+  ],
+]
+
+test.each(caseMatrix)(
+  '\tprovidesTags: %O,\n\tinvalidatesTags: %O,\n\tshould invalidate: %s',
+  async (providesTags, invalidatesTags, shouldInvalidate) => {
+    let queryCount = 0
+    const {
+      store,
+      api,
+      api: {
+        endpoints: { invalidating, providing, unrelated },
+      },
+    } = setupApiStore(
+      createApi({
+        baseQuery: fakeBaseQuery(),
+        tagTypes,
+        endpoints: (build) => ({
+          providing: build.query<unknown, void>({
+            queryFn() {
+              queryCount++
+              return { data: {} }
+            },
+            providesTags,
+          }),
+          unrelated: build.query<unknown, void>({
+            queryFn() {
+              return { data: {} }
+            },
+            providesTags: ['cat', 'dog', { type: 'giraffe', id: 8 }],
+          }),
+          invalidating: build.mutation<unknown, void>({
+            queryFn() {
+              return { data: {} }
+            },
+            invalidatesTags,
+          }),
+        }),
+      }),
+      undefined,
+      { withoutTestLifecycles: true },
+    )
+
+    store.dispatch(providing.initiate())
+    store.dispatch(unrelated.initiate())
+    expect(queryCount).toBe(1)
+    await waitFor(() => {
+      expect(api.endpoints.providing.select()(store.getState()).status).toBe(
+        'fulfilled',
+      )
+      expect(api.endpoints.unrelated.select()(store.getState()).status).toBe(
+        'fulfilled',
+      )
+    })
+    const toInvalidate = api.util.selectInvalidatedBy(
+      store.getState(),
+      invalidatesTags,
+    )
+
+    if (shouldInvalidate) {
+      expect(toInvalidate).toEqual([
+        {
+          queryCacheKey: 'providing(undefined)',
+          endpointName: 'providing',
+          originalArgs: undefined,
+        },
+      ])
+    } else {
+      expect(toInvalidate).toEqual([])
+    }
+
+    store.dispatch(invalidating.initiate())
+    expect(queryCount).toBe(1)
+    await delay(2)
+    expect(queryCount).toBe(shouldInvalidate ? 2 : 1)
+  },
+)
Index: node_modules/@reduxjs/toolkit/src/query/tests/matchers.test-d.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/matchers.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/matchers.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,80 @@
+import type { SerializedError } from '@reduxjs/toolkit'
+import { createSlice } from '@reduxjs/toolkit'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+
+interface ResultType {
+  result: 'complex'
+}
+
+interface ArgType {
+  foo: 'bar'
+  count: 3
+}
+
+const baseQuery = fetchBaseQuery({ baseUrl: 'https://example.com' })
+const api = createApi({
+  baseQuery,
+  endpoints(build) {
+    return {
+      querySuccess: build.query<ResultType, ArgType>({
+        query: () => '/success',
+      }),
+      querySuccess2: build.query({ query: () => '/success' }),
+      queryFail: build.query({ query: () => '/error' }),
+      mutationSuccess: build.mutation({
+        query: () => ({ url: '/success', method: 'POST' }),
+      }),
+      mutationSuccess2: build.mutation({
+        query: () => ({ url: '/success', method: 'POST' }),
+      }),
+      mutationFail: build.mutation({
+        query: () => ({ url: '/error', method: 'POST' }),
+      }),
+    }
+  },
+})
+
+describe('type tests', () => {
+  test('inferred types', () => {
+    createSlice({
+      name: 'auth',
+      initialState: {},
+      reducers: {},
+      extraReducers: (builder) => {
+        builder
+          .addMatcher(
+            api.endpoints.querySuccess.matchPending,
+            (state, action) => {
+              expectTypeOf(action.payload).toBeUndefined()
+
+              expectTypeOf(
+                action.meta.arg.originalArgs,
+              ).toEqualTypeOf<ArgType>()
+            },
+          )
+          .addMatcher(
+            api.endpoints.querySuccess.matchFulfilled,
+            (state, action) => {
+              expectTypeOf(action.payload).toEqualTypeOf<ResultType>()
+
+              expectTypeOf(action.meta.fulfilledTimeStamp).toBeNumber()
+
+              expectTypeOf(
+                action.meta.arg.originalArgs,
+              ).toEqualTypeOf<ArgType>()
+            },
+          )
+          .addMatcher(
+            api.endpoints.querySuccess.matchRejected,
+            (state, action) => {
+              expectTypeOf(action.error).toEqualTypeOf<SerializedError>()
+
+              expectTypeOf(
+                action.meta.arg.originalArgs,
+              ).toEqualTypeOf<ArgType>()
+            },
+          )
+      },
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/matchers.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/matchers.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/matchers.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,241 @@
+import {
+  actionsReducer,
+  hookWaitFor,
+  setupApiStore,
+} from '@internal/tests/utils/helpers'
+import { createSlice } from '@reduxjs/toolkit'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+import { act, renderHook } from '@testing-library/react'
+
+interface ResultType {
+  result: 'complex'
+}
+
+interface ArgType {
+  foo: 'bar'
+  count: 3
+}
+
+const baseQuery = fetchBaseQuery({ baseUrl: 'https://example.com' })
+const api = createApi({
+  baseQuery,
+  endpoints(build) {
+    return {
+      querySuccess: build.query<ResultType, ArgType>({
+        query: () => '/success',
+      }),
+      querySuccess2: build.query({ query: () => '/success' }),
+      queryFail: build.query({ query: () => '/error' }),
+      mutationSuccess: build.mutation({
+        query: () => ({ url: '/success', method: 'POST' }),
+      }),
+      mutationSuccess2: build.mutation({
+        query: () => ({ url: '/success', method: 'POST' }),
+      }),
+      mutationFail: build.mutation({
+        query: () => ({ url: '/error', method: 'POST' }),
+      }),
+    }
+  },
+})
+
+const storeRef = setupApiStore(api, {
+  ...actionsReducer,
+})
+
+const {
+  mutationFail,
+  mutationSuccess,
+  mutationSuccess2,
+  queryFail,
+  querySuccess,
+  querySuccess2,
+} = api.endpoints
+
+test('matches query pending & fulfilled actions for the given endpoint', async () => {
+  const endpoint = querySuccess2
+  const otherEndpoint = queryFail
+  const { result } = renderHook(() => endpoint.useQuery({} as any), {
+    wrapper: storeRef.wrapper,
+  })
+  await hookWaitFor(() => expect(result.current.isLoading).toBeFalsy())
+
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchFulfilled,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    otherEndpoint.matchPending,
+    otherEndpoint.matchFulfilled,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchFulfilled,
+    api.endpoints.mutationSuccess.matchFulfilled,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchRejected,
+  )
+})
+test('matches query pending & rejected actions for the given endpoint', async () => {
+  const endpoint = queryFail
+  const { result } = renderHook(() => endpoint.useQuery({}), {
+    wrapper: storeRef.wrapper,
+  })
+  await hookWaitFor(() => expect(result.current.isLoading).toBeFalsy())
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchFulfilled,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchFulfilled,
+  )
+})
+
+test('matches lazy query pending & fulfilled actions for given endpoint', async () => {
+  const endpoint = querySuccess
+  const { result } = renderHook(() => endpoint.useLazyQuery(), {
+    wrapper: storeRef.wrapper,
+  })
+  act(() => void result.current[0]({} as any))
+  await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchFulfilled,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchFulfilled,
+    endpoint.matchRejected,
+  )
+
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchRejected,
+  )
+})
+
+test('matches lazy query pending & rejected actions for given endpoint', async () => {
+  const endpoint = queryFail
+  const { result } = renderHook(() => endpoint.useLazyQuery(), {
+    wrapper: storeRef.wrapper,
+  })
+  act(() => void result.current[0]({}))
+  await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchFulfilled,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchFulfilled,
+  )
+})
+
+test('matches mutation pending & fulfilled actions for the given endpoint', async () => {
+  const endpoint = mutationSuccess
+  const otherEndpoint = mutationSuccess2
+  const { result } = renderHook(() => endpoint.useMutation(), {
+    wrapper: storeRef.wrapper,
+  })
+  act(() => void result.current[0]({}))
+  await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchFulfilled,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    otherEndpoint.matchPending,
+    otherEndpoint.matchFulfilled,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchFulfilled,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchRejected,
+  )
+})
+test('matches mutation pending & rejected actions for the given endpoint', async () => {
+  const endpoint = mutationFail
+  const { result } = renderHook(() => endpoint.useMutation(), {
+    wrapper: storeRef.wrapper,
+  })
+  act(() => void result.current[0]({}))
+  await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
+
+  expect(storeRef.store.getState().actions).toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchFulfilled,
+    endpoint.matchRejected,
+  )
+  expect(storeRef.store.getState().actions).not.toMatchSequence(
+    api.internalActions.middlewareRegistered.match,
+    endpoint.matchPending,
+    endpoint.matchFulfilled,
+  )
+})
+
+test('inferred types', () => {
+  createSlice({
+    name: 'auth',
+    initialState: {},
+    reducers: {},
+    extraReducers: (builder) => {
+      builder
+        .addMatcher(
+          api.endpoints.querySuccess.matchPending,
+          (state, action) => {
+            // @ts-expect-error
+            console.log(action.error)
+          },
+        )
+        .addMatcher(
+          api.endpoints.querySuccess.matchFulfilled,
+          (state, action) => {
+            // @ts-expect-error
+            console.log(action.error)
+          },
+        )
+        .addMatcher(
+          api.endpoints.querySuccess.matchRejected,
+          (state, action) => {},
+        )
+    },
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/mocks/handlers.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/mocks/handlers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/mocks/handlers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,107 @@
+import { headersToObject } from 'headers-polyfill'
+import { HttpResponse, http } from 'msw'
+
+export type Post = {
+  id: number
+  title: string
+  body: string
+}
+
+export const posts: Record<string, Post> = {
+  1: { id: 1, title: 'hello', body: 'extra body!' },
+}
+
+export const handlers = [
+  http.get(
+    'https://example.com',
+    async ({ request, params, cookies, requestId }) => {
+      HttpResponse.json({ value: 'success' })
+    },
+  ),
+  http.get(
+    'https://example.com/echo',
+    async ({ request, params, cookies, requestId }) => {
+      return HttpResponse.json({
+        ...request,
+        params,
+        cookies,
+        requestId,
+        url: new URL(request.url),
+        headers: headersToObject(request.headers),
+      })
+    },
+  ),
+
+  http.post(
+    'https://example.com/echo',
+    async ({ request, cookies, params, requestId }) => {
+      let body
+
+      try {
+        body =
+          headersToObject(request.headers)['content-type'] === 'text/html'
+            ? await request.text()
+            : await request.json()
+      } catch (err) {
+        body = request.body
+      }
+
+      return HttpResponse.json({
+        ...request,
+        cookies,
+        params,
+        requestId,
+        body,
+        url: new URL(request.url),
+        headers: headersToObject(request.headers),
+      })
+    },
+  ),
+
+  http.get('https://example.com/success', () =>
+    HttpResponse.json({ value: 'success' }),
+  ),
+
+  http.post('https://example.com/success', () =>
+    HttpResponse.json({ value: 'success' }),
+  ),
+
+  http.get('https://example.com/empty', () => new HttpResponse('')),
+
+  http.get('https://example.com/error', () =>
+    HttpResponse.json({ value: 'error' }, { status: 500 }),
+  ),
+
+  http.post('https://example.com/error', () =>
+    HttpResponse.json({ value: 'error' }, { status: 500 }),
+  ),
+
+  http.get('https://example.com/nonstandard-error', () =>
+    HttpResponse.json(
+      {
+        success: false,
+        message: 'This returns a 200 but is really an error',
+      },
+      { status: 200 },
+    ),
+  ),
+
+  http.get('https://example.com/mirror', ({ params }) =>
+    HttpResponse.json(params),
+  ),
+
+  http.post('https://example.com/mirror', ({ params }) =>
+    HttpResponse.json(params),
+  ),
+
+  http.get('https://example.com/posts/random', () => {
+    // just simulate an api that returned a random ID
+    const { id } = posts[1]
+    return HttpResponse.json({ id })
+  }),
+
+  http.get<{ id: string }, any, Pick<Post, 'id'>>(
+    'https://example.com/post/:id',
+    ({ params }) => HttpResponse.json(posts[params.id]),
+  ),
+]
Index: node_modules/@reduxjs/toolkit/src/query/tests/mocks/server.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/mocks/server.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/mocks/server.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,5 @@
+import { setupServer } from 'msw/node'
+import { handlers } from './handlers'
+
+// This configures a request mocking server with the given request handlers.
+export const server = setupServer(...handlers)
Index: node_modules/@reduxjs/toolkit/src/query/tests/optimisticUpdates.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/optimisticUpdates.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/optimisticUpdates.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,476 @@
+import { createApi } from '@reduxjs/toolkit/query/react'
+import { act, renderHook } from '@testing-library/react'
+import { delay } from 'msw'
+import {
+  actionsReducer,
+  hookWaitFor,
+  setupApiStore,
+} from '../../tests/utils/helpers'
+import type { InvalidationState } from '../core/apiState'
+
+interface Post {
+  id: string
+  title: string
+  contents: string
+}
+
+const baseQuery = vi.fn()
+beforeEach(() => {
+  baseQuery.mockReset()
+})
+
+const api = createApi({
+  baseQuery: (...args: any[]) => {
+    const result = baseQuery(...args)
+    if (typeof result === 'object' && 'then' in result)
+      return result
+        .then((data: any) => ({ data, meta: 'meta' }))
+        .catch((e: any) => ({ error: e }))
+    return { data: result, meta: 'meta' }
+  },
+  tagTypes: ['Post'],
+  endpoints: (build) => ({
+    post: build.query<Post, string>({
+      query: (id) => `post/${id}`,
+      providesTags: ['Post'],
+    }),
+    listPosts: build.query<Post[], void>({
+      query: () => `posts`,
+      providesTags: (result) => [
+        ...(result?.map(({ id }) => ({ type: 'Post' as const, id })) ?? []),
+        'Post',
+      ],
+    }),
+    updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
+      query: ({ id, ...patch }) => ({
+        url: `post/${id}`,
+        method: 'PATCH',
+        body: patch,
+      }),
+      async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
+        const { undo } = dispatch(
+          api.util.updateQueryData('post', id, (draft) => {
+            Object.assign(draft, patch)
+          }),
+        )
+        queryFulfilled.catch(undo)
+      },
+      invalidatesTags: (result) => (result ? ['Post'] : []),
+    }),
+  }),
+})
+
+const storeRef = setupApiStore(api, { ...actionsReducer })
+
+describe('basic lifecycle', () => {
+  let onStart = vi.fn(),
+    onError = vi.fn(),
+    onSuccess = vi.fn()
+
+  const extendedApi = api.injectEndpoints({
+    endpoints: (build) => ({
+      test: build.mutation({
+        query: (x) => x,
+        async onQueryStarted(arg, api) {
+          onStart(arg)
+          try {
+            const result = await api.queryFulfilled
+            onSuccess(result)
+          } catch (e) {
+            onError(e)
+          }
+        },
+      }),
+    }),
+    overrideExisting: true,
+  })
+
+  beforeEach(() => {
+    onStart.mockReset()
+    onError.mockReset()
+    onSuccess.mockReset()
+  })
+
+  test('success', async () => {
+    const { result } = renderHook(
+      () => extendedApi.endpoints.test.useMutation(),
+      { wrapper: storeRef.wrapper },
+    )
+
+    baseQuery.mockResolvedValue('success')
+
+    expect(onStart).not.toHaveBeenCalled()
+    expect(baseQuery).not.toHaveBeenCalled()
+    act(() => void result.current[0]('arg'))
+    expect(onStart).toHaveBeenCalledWith('arg')
+    expect(baseQuery).toHaveBeenCalledWith('arg', expect.any(Object), undefined)
+
+    expect(onError).not.toHaveBeenCalled()
+    expect(onSuccess).not.toHaveBeenCalled()
+    await act(() => delay(5))
+    expect(onError).not.toHaveBeenCalled()
+    expect(onSuccess).toHaveBeenCalledWith({ data: 'success', meta: 'meta' })
+  })
+
+  test('error', async () => {
+    const { result } = renderHook(
+      () => extendedApi.endpoints.test.useMutation(),
+      { wrapper: storeRef.wrapper },
+    )
+
+    baseQuery.mockRejectedValueOnce('error')
+    expect(onStart).not.toHaveBeenCalled()
+    expect(baseQuery).not.toHaveBeenCalled()
+
+    act(() => void result.current[0]('arg'))
+    expect(onStart).toHaveBeenCalledWith('arg')
+    expect(baseQuery).toHaveBeenCalledWith('arg', expect.any(Object), undefined)
+    expect(onError).not.toHaveBeenCalled()
+    expect(onSuccess).not.toHaveBeenCalled()
+    await act(() => delay(5))
+    expect(onError).toHaveBeenCalledWith({
+      error: 'error',
+      isUnhandledError: false,
+      meta: undefined,
+    })
+    expect(onSuccess).not.toHaveBeenCalled()
+  })
+})
+
+describe('updateQueryData', () => {
+  test('updates cache values, can apply inverse patch', async () => {
+    baseQuery
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      })
+      // TODO I have no idea why the query is getting called multiple times,
+      // but passing an additional mocked value (_any_ value)
+      // seems to silence some annoying "got an undefined result" logging
+      .mockResolvedValueOnce(42)
+    const { result } = renderHook(() => api.endpoints.post.useQuery('3'), {
+      wrapper: storeRef.wrapper,
+    })
+    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())
+
+    const dataBefore = result.current.data
+    expect(dataBefore).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'TODO',
+    })
+
+    let returnValue!: ReturnType<ReturnType<typeof api.util.updateQueryData>>
+    act(() => {
+      returnValue = storeRef.store.dispatch(
+        api.util.updateQueryData('post', '3', (draft) => {
+          draft.contents = 'I love cheese!'
+        }),
+      )
+    })
+
+    expect(result.current.data).not.toBe(dataBefore)
+    expect(result.current.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'I love cheese!',
+    })
+
+    expect(returnValue).toEqual({
+      inversePatches: [{ op: 'replace', path: ['contents'], value: 'TODO' }],
+      patches: [{ op: 'replace', path: ['contents'], value: 'I love cheese!' }],
+      undo: expect.any(Function),
+    })
+
+    act(() => {
+      storeRef.store.dispatch(
+        api.util.patchQueryData('post', '3', returnValue.inversePatches),
+      )
+    })
+
+    expect(result.current.data).toEqual(dataBefore)
+  })
+
+  test('updates (list) cache values including provided tags, undos that', async () => {
+    baseQuery
+      .mockResolvedValueOnce([
+        { id: '3', title: 'All about cheese.', contents: 'TODO' },
+      ])
+      .mockResolvedValueOnce(42)
+    const { result } = renderHook(() => api.endpoints.listPosts.useQuery(), {
+      wrapper: storeRef.wrapper,
+    })
+    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())
+
+    let provided!: InvalidationState<'Post'>
+    act(() => {
+      provided = storeRef.store.getState().api.provided
+    })
+
+    const provided3 = provided.tags.Post['3']
+
+    let returnValue!: ReturnType<ReturnType<typeof api.util.updateQueryData>>
+    act(() => {
+      returnValue = storeRef.store.dispatch(
+        api.util.updateQueryData(
+          'listPosts',
+          undefined,
+          (draft) => {
+            draft.push({
+              id: '4',
+              title: 'Mostly about cheese.',
+              contents: 'TODO',
+            })
+          },
+          true,
+        ),
+      )
+    })
+
+    act(() => {
+      provided = storeRef.store.getState().api.provided
+    })
+
+    const provided4 = provided.tags.Post['4']
+
+    expect(provided4).toEqual(provided3)
+
+    act(() => {
+      returnValue.undo()
+    })
+
+    act(() => {
+      provided = storeRef.store.getState().api.provided
+    })
+
+    const provided4Next = provided.tags.Post['4']
+
+    expect(provided4Next).toEqual([])
+  })
+
+  test('updates (list) cache values excluding provided tags, undoes that', async () => {
+    baseQuery
+      .mockResolvedValueOnce([
+        { id: '3', title: 'All about cheese.', contents: 'TODO' },
+      ])
+      .mockResolvedValueOnce(42)
+    const { result } = renderHook(() => api.endpoints.listPosts.useQuery(), {
+      wrapper: storeRef.wrapper,
+    })
+    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())
+
+    let provided!: InvalidationState<'Post'>
+    act(() => {
+      provided = storeRef.store.getState().api.provided
+    })
+
+    let returnValue!: ReturnType<ReturnType<typeof api.util.updateQueryData>>
+    act(() => {
+      returnValue = storeRef.store.dispatch(
+        api.util.updateQueryData(
+          'listPosts',
+          undefined,
+          (draft) => {
+            draft.push({
+              id: '4',
+              title: 'Mostly about cheese.',
+              contents: 'TODO',
+            })
+          },
+          false,
+        ),
+      )
+    })
+
+    act(() => {
+      provided = storeRef.store.getState().api.provided
+    })
+
+    const provided4 = provided.tags.Post['4']
+
+    expect(provided4).toEqual(undefined)
+
+    act(() => {
+      returnValue.undo()
+    })
+
+    act(() => {
+      provided = storeRef.store.getState().api.provided
+    })
+
+    const provided4Next = provided.tags.Post['4']
+
+    expect(provided4Next).toEqual(undefined)
+  })
+
+  test('does not update non-existing values', async () => {
+    baseQuery
+      .mockImplementationOnce(async () => ({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      }))
+      .mockResolvedValueOnce(42)
+
+    const { result } = renderHook(() => api.endpoints.post.useQuery('3'), {
+      wrapper: storeRef.wrapper,
+    })
+    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())
+
+    const dataBefore = result.current.data
+    expect(dataBefore).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'TODO',
+    })
+
+    let returnValue!: ReturnType<ReturnType<typeof api.util.updateQueryData>>
+    act(() => {
+      returnValue = storeRef.store.dispatch(
+        api.util.updateQueryData('post', '4', (draft) => {
+          draft.contents = 'I love cheese!'
+        }),
+      )
+    })
+
+    expect(result.current.data).toBe(dataBefore)
+
+    expect(returnValue).toEqual({
+      inversePatches: [],
+      patches: [],
+      undo: expect.any(Function),
+    })
+  })
+})
+
+describe('full integration', () => {
+  test('success case', async () => {
+    baseQuery
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      })
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'Delicious cheese!',
+      })
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'Delicious cheese!',
+      })
+      .mockResolvedValueOnce(42)
+    const { result } = renderHook(
+      () => ({
+        query: api.endpoints.post.useQuery('3'),
+        mutation: api.endpoints.updatePost.useMutation(),
+      }),
+      { wrapper: storeRef.wrapper },
+    )
+    await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy())
+
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'TODO',
+    })
+
+    act(() => {
+      result.current.mutation[0]({ id: '3', contents: 'Delicious cheese!' })
+    })
+
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'Delicious cheese!',
+    })
+
+    await hookWaitFor(() =>
+      expect(result.current.query.data).toEqual({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'Delicious cheese!',
+      }),
+    )
+  })
+
+  test('error case', async () => {
+    baseQuery
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      })
+      .mockRejectedValueOnce('some error!')
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'TODO',
+      })
+      .mockResolvedValueOnce(42)
+
+    const { result } = renderHook(
+      () => ({
+        query: api.endpoints.post.useQuery('3'),
+        mutation: api.endpoints.updatePost.useMutation(),
+      }),
+      { wrapper: storeRef.wrapper },
+    )
+    await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy())
+
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'TODO',
+    })
+
+    act(() => {
+      result.current.mutation[0]({ id: '3', contents: 'Delicious cheese!' })
+    })
+
+    // optimistic update
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'Delicious cheese!',
+    })
+
+    // rollback
+    await hookWaitFor(() =>
+      expect(result.current.query.data).toEqual({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      }),
+    )
+
+    // mutation failed - will not invalidate query and not refetch data from the server
+    await expect(() =>
+      hookWaitFor(
+        () =>
+          expect(result.current.query.data).toEqual({
+            id: '3',
+            title: 'Meanwhile, this changed server-side.',
+            contents: 'TODO',
+          }),
+        50,
+      ),
+    ).rejects.toBeTruthy()
+
+    act(() => void result.current.query.refetch())
+
+    // manually refetching gives up-to-date data
+    await hookWaitFor(
+      () =>
+        expect(result.current.query.data).toEqual({
+          id: '3',
+          title: 'Meanwhile, this changed server-side.',
+          contents: 'TODO',
+        }),
+      50,
+    )
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/optimisticUpserts.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/optimisticUpserts.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/optimisticUpserts.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,662 @@
+import { createApi } from '@reduxjs/toolkit/query/react'
+import { createAction } from '@reduxjs/toolkit'
+import {
+  actionsReducer,
+  hookWaitFor,
+  setupApiStore,
+} from '../../tests/utils/helpers'
+import {
+  render,
+  renderHook,
+  act,
+  waitFor,
+  screen,
+} from '@testing-library/react'
+import { delay } from 'msw'
+
+interface Post {
+  id: string
+  title: string
+  contents: string
+}
+
+interface FolderT {
+  id: number
+  children: FolderT[]
+}
+
+const baseQuery = vi.fn()
+beforeEach(() => baseQuery.mockReset())
+
+const postAddedAction = createAction<string>('postAdded')
+
+const api = createApi({
+  baseQuery: (...args: any[]) => {
+    const result = baseQuery(...args)
+    if (typeof result === 'object' && 'then' in result)
+      return result
+        .then((data: any) => ({ data, meta: 'meta' }))
+        .catch((e: any) => ({ error: e }))
+    return { data: result, meta: 'meta' }
+  },
+  tagTypes: ['Post', 'Folder'],
+  endpoints: (build) => ({
+    getPosts: build.query<Post[], void>({ query: () => '/posts' }),
+    post: build.query<Post, string>({
+      query: (id) => `post/${id}`,
+      providesTags: ['Post'],
+    }),
+    updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
+      query: ({ id, ...patch }) => ({
+        url: `post/${id}`,
+        method: 'PATCH',
+        body: patch,
+      }),
+      async onQueryStarted(arg, { dispatch, queryFulfilled, getState }) {
+        const currentItem = api.endpoints.post.select(arg.id)(getState())
+        if (currentItem?.data) {
+          dispatch(
+            api.util.upsertQueryData('post', arg.id, {
+              ...currentItem.data,
+              ...arg,
+            }),
+          )
+        }
+      },
+      invalidatesTags: (result) => (result ? ['Post'] : []),
+    }),
+    post2: build.query<Post, string>({
+      queryFn: async (id) => {
+        await delay(20)
+        return { data: { id, title: 'All about cheese.', contents: 'TODO' } }
+      },
+    }),
+    postWithSideEffect: build.query<Post, string>({
+      query: (id) => `post/${id}`,
+      providesTags: (result) => {
+        if (result) {
+          return [{ type: 'Post', id: result.id } as const]
+        }
+        return []
+      },
+      async onCacheEntryAdded(arg, api) {
+        // Verify that lifecycle promise resolution works
+        const res = await api.cacheDataLoaded
+
+        // and leave a side effect we can check in the test
+        api.dispatch(postAddedAction(res.data.id))
+      },
+      keepUnusedDataFor: 0.1,
+    }),
+    getFolder: build.query<FolderT, number>({
+      queryFn: async (args) => {
+        return {
+          data: {
+            id: args,
+            // Folder contains children that are as well folders
+            children: [{ id: 2, children: [] }],
+          },
+        }
+      },
+      providesTags: (result, err, args) => [{ type: 'Folder', id: args }],
+      onQueryStarted: async (args, queryApi) => {
+        const { data } = await queryApi.queryFulfilled
+
+        // Upsert getFolder endpoint with children from response data
+        const upsertData = data.children.map((child) => ({
+          arg: child.id,
+          endpointName: 'getFolder' as const,
+          value: child,
+        }))
+
+        queryApi.dispatch(api.util.upsertQueryEntries(upsertData))
+      },
+    }),
+  }),
+})
+
+const storeRef = setupApiStore(api, { ...actionsReducer })
+
+describe('basic lifecycle', () => {
+  let onStart = vi.fn(),
+    onError = vi.fn(),
+    onSuccess = vi.fn()
+
+  const extendedApi = api.injectEndpoints({
+    endpoints: (build) => ({
+      test: build.mutation({
+        query: (x) => x,
+        async onQueryStarted(arg, api) {
+          onStart(arg)
+          try {
+            const result = await api.queryFulfilled
+            onSuccess(result)
+          } catch (e) {
+            onError(e)
+          }
+        },
+      }),
+    }),
+    overrideExisting: true,
+  })
+
+  beforeEach(() => {
+    onStart.mockReset()
+    onError.mockReset()
+    onSuccess.mockReset()
+  })
+
+  test('Does basic inserts and upserts', async () => {
+    const newPost: Post = {
+      id: '3',
+      contents: 'Inserted content',
+      title: 'Inserted title',
+    }
+    const insertPromise = storeRef.store.dispatch(
+      api.util.upsertQueryData('post', newPost.id, newPost),
+    )
+
+    await insertPromise
+
+    const selectPost3 = api.endpoints.post.select(newPost.id)
+    const insertedPostEntry = selectPost3(storeRef.store.getState())
+    expect(insertedPostEntry.isSuccess).toBe(true)
+    expect(insertedPostEntry.data).toEqual(newPost)
+
+    const updatedPost: Post = {
+      id: '3',
+      contents: 'Updated content',
+      title: 'Updated title',
+    }
+
+    const updatePromise = storeRef.store.dispatch(
+      api.util.upsertQueryData('post', updatedPost.id, updatedPost),
+    )
+
+    await updatePromise
+
+    const updatedPostEntry = selectPost3(storeRef.store.getState())
+
+    expect(updatedPostEntry.isSuccess).toBe(true)
+    expect(updatedPostEntry.data).toEqual(updatedPost)
+  })
+
+  test('success', async () => {
+    const { result } = renderHook(
+      () => extendedApi.endpoints.test.useMutation(),
+      { wrapper: storeRef.wrapper },
+    )
+
+    baseQuery.mockResolvedValue('success')
+
+    expect(onStart).not.toHaveBeenCalled()
+    expect(baseQuery).not.toHaveBeenCalled()
+    act(() => void result.current[0]('arg'))
+    expect(onStart).toHaveBeenCalledWith('arg')
+    expect(baseQuery).toHaveBeenCalledWith('arg', expect.any(Object), undefined)
+
+    expect(onError).not.toHaveBeenCalled()
+    expect(onSuccess).not.toHaveBeenCalled()
+    await act(() => delay(5))
+    expect(onError).not.toHaveBeenCalled()
+    expect(onSuccess).toHaveBeenCalledWith({ data: 'success', meta: 'meta' })
+  })
+
+  test('error', async () => {
+    const { result } = renderHook(
+      () => extendedApi.endpoints.test.useMutation(),
+      { wrapper: storeRef.wrapper },
+    )
+
+    baseQuery.mockRejectedValueOnce('error')
+
+    expect(onStart).not.toHaveBeenCalled()
+    expect(baseQuery).not.toHaveBeenCalled()
+    act(() => void result.current[0]('arg'))
+    expect(onStart).toHaveBeenCalledWith('arg')
+    expect(baseQuery).toHaveBeenCalledWith('arg', expect.any(Object), undefined)
+
+    expect(onError).not.toHaveBeenCalled()
+    expect(onSuccess).not.toHaveBeenCalled()
+    await act(() => delay(5))
+    expect(onError).toHaveBeenCalledWith({
+      error: 'error',
+      isUnhandledError: false,
+      meta: undefined,
+    })
+    expect(onSuccess).not.toHaveBeenCalled()
+  })
+})
+
+describe('upsertQueryData', () => {
+  test('inserts cache entry', async () => {
+    baseQuery
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      })
+      // TODO I have no idea why the query is getting called multiple times,
+      // but passing an additional mocked value (_any_ value)
+      // seems to silence some annoying "got an undefined result" logging
+      .mockResolvedValueOnce(42)
+    const { result } = renderHook(() => api.endpoints.post.useQuery('3'), {
+      wrapper: storeRef.wrapper,
+    })
+    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())
+
+    const dataBefore = result.current.data
+    expect(dataBefore).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'TODO',
+    })
+
+    await act(async () => {
+      storeRef.store.dispatch(
+        api.util.upsertQueryData('post', '3', {
+          id: '3',
+          title: 'All about cheese.',
+          contents: 'I love cheese!',
+        }),
+      )
+    })
+
+    expect(result.current.data).not.toBe(dataBefore)
+    expect(result.current.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'I love cheese!',
+    })
+  })
+
+  test('does update non-existing values', async () => {
+    baseQuery
+      // throw an error to make sure there is no cached data
+      .mockImplementationOnce(async () => {
+        throw new Error('failed to load')
+      })
+      .mockResolvedValueOnce(42)
+
+    // a subscriber is needed to have the data stay in the cache
+    // Not sure if this is the wanted behavior, I would have liked
+    // it to stay in the cache for the x amount of time the cache
+    // is preserved normally after the last subscriber was unmounted
+    const { result, rerender } = renderHook(
+      () => api.endpoints.post.useQuery('4'),
+      { wrapper: storeRef.wrapper },
+    )
+    await hookWaitFor(() => expect(result.current.isError).toBeTruthy())
+
+    // upsert the data
+    act(() => {
+      storeRef.store.dispatch(
+        api.util.upsertQueryData('post', '4', {
+          id: '4',
+          title: 'All about cheese',
+          contents: 'I love cheese!',
+        }),
+      )
+    })
+
+    // rerender the hook
+    rerender()
+    // wait until everything has settled
+    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())
+
+    // the cached data is returned as the result
+    expect(result.current.data).toStrictEqual({
+      id: '4',
+      title: 'All about cheese',
+      contents: 'I love cheese!',
+    })
+  })
+
+  test('upsert while a normal query is running (success)', async () => {
+    const fetchedData = {
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'Yummy',
+    }
+    baseQuery.mockImplementation(() => delay(20).then(() => fetchedData))
+    const upsertedData = {
+      id: '3',
+      title: 'Data from a SSR Render',
+      contents: 'This is just some random data',
+    }
+
+    const selector = api.endpoints.post.select('3')
+    const fetchRes = storeRef.store.dispatch(api.endpoints.post.initiate('3'))
+    const upsertRes = storeRef.store.dispatch(
+      api.util.upsertQueryData('post', '3', upsertedData),
+    )
+
+    await upsertRes
+    let state = selector(storeRef.store.getState())
+    expect(state.data).toEqual(upsertedData)
+
+    await fetchRes
+    state = selector(storeRef.store.getState())
+    expect(state.data).toEqual(fetchedData)
+  })
+  test('upsert while a normal query is running (rejected)', async () => {
+    baseQuery.mockImplementationOnce(async () => {
+      await delay(20)
+      // eslint-disable-next-line no-throw-literal
+      throw 'Error!'
+    })
+    const upsertedData = {
+      id: '3',
+      title: 'Data from a SSR Render',
+      contents: 'This is just some random data',
+    }
+
+    const selector = api.endpoints.post.select('3')
+    const fetchRes = storeRef.store.dispatch(api.endpoints.post.initiate('3'))
+    const upsertRes = storeRef.store.dispatch(
+      api.util.upsertQueryData('post', '3', upsertedData),
+    )
+
+    await upsertRes
+    let state = selector(storeRef.store.getState())
+    expect(state.data).toEqual(upsertedData)
+    expect(state.isSuccess).toBeTruthy()
+
+    await fetchRes
+    state = selector(storeRef.store.getState())
+    expect(state.data).toEqual(upsertedData)
+    expect(state.isError).toBeTruthy()
+  })
+})
+
+describe('upsertQueryEntries', () => {
+  const posts: Post[] = [
+    { id: '1', contents: 'A', title: 'A' },
+    { id: '2', contents: 'B', title: 'B' },
+    { id: '3', contents: 'C', title: 'C' },
+  ]
+
+  const entriesAction = api.util.upsertQueryEntries([
+    { endpointName: 'getPosts', arg: undefined, value: posts },
+    ...posts.map((post) => ({
+      endpointName: 'postWithSideEffect' as const,
+      arg: post.id,
+      value: post,
+    })),
+  ])
+
+  test('Upserts many entries at once', async () => {
+    storeRef.store.dispatch(entriesAction)
+
+    const state = storeRef.store.getState()
+
+    expect(api.endpoints.getPosts.select()(state).data).toBe(posts)
+
+    for (const post of posts) {
+      expect(api.endpoints.postWithSideEffect.select(post.id)(state).data).toBe(
+        post,
+      )
+
+      // Should have added tags
+      expect(state.api.provided.tags.Post[post.id]).toEqual([
+        `postWithSideEffect("${post.id}")`,
+      ])
+    }
+  })
+
+  test('Triggers cache lifecycles and side effects', async () => {
+    storeRef.store.dispatch(entriesAction)
+
+    // Tricky timing. The cache data promises will be resolved
+    // in microtasks. We need to wait for them. Best to do this
+    // in a loop just to avoid a hardcoded delay, but also this
+    // needs to complete before `keepUnusedDataFor` expires them.
+    await waitFor(
+      () => {
+        const state = storeRef.store.getState()
+
+        // onCacheEntryAdded should have run for each post,
+        // including cache data being resolved
+        for (const post of posts) {
+          const matchingSideEffectAction = state.actions.find(
+            (action) =>
+              postAddedAction.match(action) && action.payload === post.id,
+          )
+          expect(matchingSideEffectAction).toBeTruthy()
+        }
+
+        const selectedData =
+          api.endpoints.postWithSideEffect.select('1')(state).data
+
+        expect(selectedData).toBe(posts[0])
+      },
+      { timeout: 150, interval: 5 },
+    )
+
+    // The cache data should be removed after the keepUnusedDataFor time,
+    // so wait longer than that
+    await delay(300)
+
+    const stateAfter = storeRef.store.getState()
+
+    expect(api.endpoints.postWithSideEffect.select('1')(stateAfter).data).toBe(
+      undefined,
+    )
+  })
+
+  test('Handles repeated upserts and async lifecycles', async () => {
+    const StateForUpsertFolder = ({ folderId }: { folderId: number }) => {
+      const { status } = api.useGetFolderQuery(folderId)
+
+      return (
+        <>
+          <div>
+            Status getFolder with ID (
+            {folderId === 1 ? 'original request' : 'upserted'}) {folderId}:{' '}
+            <span data-testid={`status-${folderId}`}>{status}</span>
+          </div>
+        </>
+      )
+    }
+
+    const Folder = () => {
+      const { data, isLoading, isError } = api.useGetFolderQuery(1)
+
+      return (
+        <div>
+          <h1>Folders</h1>
+
+          {isLoading && <div>Loading...</div>}
+
+          {isError && <div>Error...</div>}
+
+          <StateForUpsertFolder key={`state-${1}`} folderId={1} />
+          <StateForUpsertFolder key={`state-${2}`} folderId={2} />
+        </div>
+      )
+    }
+
+    render(<Folder />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() => {
+      const { actions } = storeRef.store.getState()
+      // Inspection:
+      // - 2 inits
+      // - 2 pendings, 2 fulfilleds for the hook queries
+      // - 2 upserts
+      expect(actions.length).toBe(8)
+      expect(
+        actions.filter((a) => api.util.upsertQueryEntries.match(a)).length,
+      ).toBe(2)
+    })
+    expect(screen.getByTestId('status-2').textContent).toBe('fulfilled')
+  })
+})
+
+describe('full integration', () => {
+  test('success case', async () => {
+    baseQuery
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      })
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'Delicious cheese!',
+      })
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'Delicious cheese!',
+      })
+      .mockResolvedValueOnce(42)
+    const { result } = renderHook(
+      () => ({
+        query: api.endpoints.post.useQuery('3'),
+        mutation: api.endpoints.updatePost.useMutation(),
+      }),
+      { wrapper: storeRef.wrapper },
+    )
+    await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy())
+
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'TODO',
+    })
+
+    await act(async () => {
+      await result.current.mutation[0]({
+        id: '3',
+        contents: 'Delicious cheese!',
+      })
+    })
+
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'Meanwhile, this changed server-side.',
+      contents: 'Delicious cheese!',
+    })
+
+    await hookWaitFor(() =>
+      expect(result.current.query.data).toEqual({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'Delicious cheese!',
+      }),
+    )
+  })
+
+  test('error case', async () => {
+    baseQuery
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'All about cheese.',
+        contents: 'TODO',
+      })
+      .mockRejectedValueOnce('some error!')
+      .mockResolvedValueOnce({
+        id: '3',
+        title: 'Meanwhile, this changed server-side.',
+        contents: 'TODO',
+      })
+      .mockResolvedValueOnce(42)
+
+    const { result } = renderHook(
+      () => ({
+        query: api.endpoints.post.useQuery('3'),
+        mutation: api.endpoints.updatePost.useMutation(),
+      }),
+      { wrapper: storeRef.wrapper },
+    )
+    await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy())
+
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'TODO',
+    })
+
+    await act(async () => {
+      await result.current.mutation[0]({
+        id: '3',
+        contents: 'Delicious cheese!',
+      })
+    })
+
+    // optimistic update
+    expect(result.current.query.data).toEqual({
+      id: '3',
+      title: 'All about cheese.',
+      contents: 'Delicious cheese!',
+    })
+
+    // mutation failed - will not invalidate query and not refetch data from the server
+    await expect(() =>
+      hookWaitFor(
+        () =>
+          expect(result.current.query.data).toEqual({
+            id: '3',
+            title: 'Meanwhile, this changed server-side.',
+            contents: 'TODO',
+          }),
+        50,
+      ),
+    ).rejects.toBeTruthy()
+
+    act(() => void result.current.query.refetch())
+
+    // manually refetching gives up-to-date data
+    await hookWaitFor(
+      () =>
+        expect(result.current.query.data).toEqual({
+          id: '3',
+          title: 'Meanwhile, this changed server-side.',
+          contents: 'TODO',
+        }),
+      50,
+    )
+  })
+
+  test('Interop with in-flight requests', async () => {
+    await act(async () => {
+      const fetchRes = storeRef.store.dispatch(
+        api.endpoints.post2.initiate('3'),
+      )
+
+      const upsertRes = storeRef.store.dispatch(
+        api.util.upsertQueryData('post2', '3', {
+          id: '3',
+          title: 'Upserted title',
+          contents: 'Upserted contents',
+        }),
+      )
+
+      const selectEntry = api.endpoints.post2.select('3')
+      await waitFor(
+        () => {
+          const entry1 = selectEntry(storeRef.store.getState())
+          expect(entry1.data).toEqual({
+            id: '3',
+            title: 'Upserted title',
+            contents: 'Upserted contents',
+          })
+        },
+        { interval: 1, timeout: 15 },
+      )
+      await waitFor(
+        () => {
+          const entry2 = selectEntry(storeRef.store.getState())
+          expect(entry2.data).toEqual({
+            id: '3',
+            title: 'All about cheese.',
+            contents: 'TODO',
+          })
+        },
+        { interval: 1 },
+      )
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/polling.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/polling.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/polling.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,286 @@
+import { createApi } from '@reduxjs/toolkit/query'
+import type { QueryActionCreatorResult } from '@reduxjs/toolkit/query'
+import { delay } from 'msw'
+import { setupApiStore } from '../../tests/utils/helpers'
+import type { SubscriptionSelectors } from '../core/buildMiddleware/types'
+
+const mockBaseQuery = vi
+  .fn()
+  .mockImplementation((args: any) => ({ data: args }))
+
+const api = createApi({
+  baseQuery: mockBaseQuery,
+  tagTypes: ['Posts'],
+  endpoints: (build) => ({
+    getPosts: build.query<unknown, number>({
+      query(pageNumber) {
+        return { url: 'posts', params: pageNumber }
+      },
+      providesTags: ['Posts'],
+    }),
+  }),
+})
+const { getPosts } = api.endpoints
+
+const storeRef = setupApiStore(api)
+
+let getSubscriptions: SubscriptionSelectors['getSubscriptions']
+
+beforeEach(() => {
+  ;({ getSubscriptions } = storeRef.store.dispatch(
+    api.internalActions.internal_getRTKQSubscriptions(),
+  ) as unknown as SubscriptionSelectors)
+
+  const currentPolls = storeRef.store.dispatch({
+    type: `${api.reducerPath}/getPolling`,
+  }) as any
+  ;(currentPolls as any).pollUpdateCounters = {}
+})
+
+const getSubscribersForQueryCacheKey = (queryCacheKey: string) =>
+  getSubscriptions().get(queryCacheKey) ?? new Map()
+const createSubscriptionGetter = (queryCacheKey: string) => () =>
+  getSubscribersForQueryCacheKey(queryCacheKey)
+
+describe('polling tests', () => {
+  it('clears intervals when seeing a resetApiState action', async () => {
+    await storeRef.store.dispatch(
+      getPosts.initiate(1, {
+        subscriptionOptions: { pollingInterval: 10 },
+        subscribe: true,
+      }),
+    )
+
+    expect(mockBaseQuery).toHaveBeenCalledOnce()
+
+    storeRef.store.dispatch(api.util.resetApiState())
+
+    await delay(30)
+
+    expect(mockBaseQuery).toHaveBeenCalledOnce()
+  })
+
+  it('replaces polling interval when the subscription options are updated', async () => {
+    const { requestId, queryCacheKey, ...subscription } =
+      storeRef.store.dispatch(
+        getPosts.initiate(1, {
+          subscriptionOptions: { pollingInterval: 10 },
+          subscribe: true,
+        }),
+      )
+
+    const getSubs = createSubscriptionGetter(queryCacheKey)
+
+    await delay(1)
+    expect(getSubs().size).toBe(1)
+    expect(getSubs()?.get(requestId)?.pollingInterval).toBe(10)
+
+    subscription.updateSubscriptionOptions({ pollingInterval: 20 })
+
+    await delay(1)
+    expect(getSubs().size).toBe(1)
+    expect(getSubs()?.get(requestId)?.pollingInterval).toBe(20)
+  })
+
+  it(`doesn't replace the interval when removing a shared query instance with a poll `, async () => {
+    const subscriptionOne = storeRef.store.dispatch(
+      getPosts.initiate(1, {
+        subscriptionOptions: { pollingInterval: 10 },
+        subscribe: true,
+      }),
+    )
+
+    storeRef.store.dispatch(
+      getPosts.initiate(1, {
+        subscriptionOptions: { pollingInterval: 10 },
+        subscribe: true,
+      }),
+    )
+
+    await delay(10)
+
+    const getSubs = createSubscriptionGetter(subscriptionOne.queryCacheKey)
+
+    expect(getSubs().size).toBe(2)
+
+    subscriptionOne.unsubscribe()
+
+    await delay(1)
+    expect(getSubs().size).toBe(1)
+  })
+
+  it('uses lowest specified interval when two components are mounted', async () => {
+    storeRef.store.dispatch(
+      getPosts.initiate(1, {
+        subscriptionOptions: { pollingInterval: 30000 },
+        subscribe: true,
+      }),
+    )
+
+    storeRef.store.dispatch(
+      getPosts.initiate(1, {
+        subscriptionOptions: { pollingInterval: 10 },
+        subscribe: true,
+      }),
+    )
+
+    await delay(20)
+
+    expect(mockBaseQuery.mock.calls.length).toBeGreaterThanOrEqual(2)
+  })
+
+  it('respects skipPollingIfUnfocused', async () => {
+    mockBaseQuery.mockClear()
+    storeRef.store.dispatch(
+      getPosts.initiate(2, {
+        subscriptionOptions: {
+          pollingInterval: 10,
+          skipPollingIfUnfocused: true,
+        },
+        subscribe: true,
+      }),
+    )
+    storeRef.store.dispatch(api.internalActions?.onFocusLost())
+
+    await delay(50)
+    const callsWithSkip = mockBaseQuery.mock.calls.length
+
+    storeRef.store.dispatch(
+      getPosts.initiate(2, {
+        subscriptionOptions: {
+          pollingInterval: 10,
+          skipPollingIfUnfocused: false,
+        },
+        subscribe: true,
+      }),
+    )
+
+    storeRef.store.dispatch(api.internalActions?.onFocus())
+
+    await delay(50)
+    const callsWithoutSkip = mockBaseQuery.mock.calls.length
+
+    expect(callsWithSkip).toBe(1)
+    expect(callsWithoutSkip).toBeGreaterThanOrEqual(2)
+
+    storeRef.store.dispatch(api.util.resetApiState())
+  })
+
+  it('respects skipPollingIfUnfocused if at least one subscription has it', async () => {
+    storeRef.store.dispatch(
+      getPosts.initiate(3, {
+        subscriptionOptions: {
+          pollingInterval: 10,
+          skipPollingIfUnfocused: false,
+        },
+        subscribe: true,
+      }),
+    )
+
+    await delay(50)
+    const callsWithoutSkip = mockBaseQuery.mock.calls.length
+
+    storeRef.store.dispatch(
+      getPosts.initiate(3, {
+        subscriptionOptions: {
+          pollingInterval: 15,
+          skipPollingIfUnfocused: true,
+        },
+        subscribe: true,
+      }),
+    )
+
+    storeRef.store.dispatch(
+      getPosts.initiate(3, {
+        subscriptionOptions: {
+          pollingInterval: 20,
+          skipPollingIfUnfocused: false,
+        },
+        subscribe: true,
+      }),
+    )
+
+    storeRef.store.dispatch(api.internalActions?.onFocusLost())
+
+    await delay(50)
+    const callsWithSkip = mockBaseQuery.mock.calls.length
+
+    expect(callsWithoutSkip).toBeGreaterThan(2)
+    expect(callsWithSkip).toBe(callsWithoutSkip + 1)
+  })
+
+  it('replaces skipPollingIfUnfocused when the subscription options are updated', async () => {
+    const { requestId, queryCacheKey, ...subscription } =
+      storeRef.store.dispatch(
+        getPosts.initiate(1, {
+          subscriptionOptions: {
+            pollingInterval: 10,
+            skipPollingIfUnfocused: false,
+          },
+          subscribe: true,
+        }),
+      )
+
+    const getSubs = createSubscriptionGetter(queryCacheKey)
+
+    await delay(1)
+    expect(getSubs().size).toBe(1)
+    expect(getSubs().get(requestId)?.skipPollingIfUnfocused).toBe(false)
+
+    subscription.updateSubscriptionOptions({
+      pollingInterval: 20,
+      skipPollingIfUnfocused: true,
+    })
+
+    await delay(1)
+    expect(getSubs().size).toBe(1)
+    expect(getSubs().get(requestId)?.skipPollingIfUnfocused).toBe(true)
+  })
+
+  it('should minimize polling recalculations when adding multiple subscribers', async () => {
+    // Reset any existing state
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    const SUBSCRIBER_COUNT = 10
+    const subscriptions: QueryActionCreatorResult<any>[] = []
+
+    // Add 10 subscribers to the same endpoint with polling enabled
+    for (let i = 0; i < SUBSCRIBER_COUNT; i++) {
+      const subscription = storeRef.store.dispatch(
+        getPosts.initiate(1, {
+          subscriptionOptions: { pollingInterval: 1000 },
+          subscribe: true,
+        }),
+      )
+      subscriptions.push(subscription)
+    }
+
+    // Wait a bit for all subscriptions to be processed
+    await Promise.all(subscriptions)
+
+    // Wait for the poll update timer
+    await delay(25)
+
+    // Get the polling state using the secret "getPolling" action
+    const currentPolls = storeRef.store.dispatch({
+      type: `${api.reducerPath}/getPolling`,
+    }) as any
+
+    // Get the query cache key for our endpoint
+    const queryCacheKey = subscriptions[0].queryCacheKey
+
+    // Check the poll update counters
+    const pollUpdateCounters = currentPolls.pollUpdateCounters || {}
+    const updateCount = pollUpdateCounters[queryCacheKey] || 0
+
+    // With batching optimization, this should be much lower than SUBSCRIBER_COUNT
+    // Ideally 1, but could be slightly higher due to timing
+    expect(updateCount).toBeGreaterThanOrEqual(1)
+    expect(updateCount).toBeLessThanOrEqual(2)
+
+    // Clean up subscriptions
+    subscriptions.forEach((sub) => sub.unsubscribe())
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/queryFn.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/queryFn.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/queryFn.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,445 @@
+import { noop } from '@internal/listenerMiddleware/utils'
+import type { QuerySubState } from '@internal/query/core/apiState'
+import type { Post } from '@internal/query/tests/mocks/handlers'
+import { posts } from '@internal/query/tests/mocks/handlers'
+import { actionsReducer, setupApiStore } from '@internal/tests/utils/helpers'
+import type { SerializedError } from '@reduxjs/toolkit'
+import { configureStore } from '@reduxjs/toolkit'
+import type { BaseQueryFn, FetchBaseQueryError } from '@reduxjs/toolkit/query'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+
+describe('queryFn base implementation tests', () => {
+  const baseQuery: BaseQueryFn<string, { wrappedByBaseQuery: string }, string> =
+    vi.fn((arg: string) =>
+      arg.includes('withErrorQuery')
+        ? { error: `cut${arg}` }
+        : { data: { wrappedByBaseQuery: arg } },
+    )
+
+  const api = createApi({
+    baseQuery,
+    endpoints: (build) => ({
+      withQuery: build.query<string, string>({
+        query(arg: string) {
+          return `resultFrom(${arg})`
+        },
+        transformResponse(response) {
+          return response.wrappedByBaseQuery
+        },
+      }),
+      withErrorQuery: build.query<string, string>({
+        query(arg: string) {
+          return `resultFrom(${arg})`
+        },
+        transformErrorResponse(response) {
+          return response.slice(3)
+        },
+      }),
+      withQueryFn: build.query<string, string>({
+        queryFn(arg: string) {
+          return { data: `resultFrom(${arg})` }
+        },
+      }),
+      withInvalidDataQueryFn: build.query<string, string>({
+        // @ts-expect-error
+        queryFn(arg: string) {
+          return { data: 5 }
+        },
+      }),
+      withErrorQueryFn: build.query<string, string>({
+        queryFn(arg: string) {
+          return { error: `resultFrom(${arg})` }
+        },
+      }),
+      withInvalidErrorQueryFn: build.query<string, string>({
+        // @ts-expect-error
+        queryFn(arg: string) {
+          return { error: 5 }
+        },
+      }),
+      withThrowingQueryFn: build.query<string, string>({
+        queryFn(arg: string) {
+          throw new Error(`resultFrom(${arg})`)
+        },
+      }),
+      withAsyncQueryFn: build.query<string, string>({
+        async queryFn(arg: string) {
+          return { data: `resultFrom(${arg})` }
+        },
+      }),
+      withInvalidDataAsyncQueryFn: build.query<string, string>({
+        // @ts-expect-error
+        async queryFn(arg: string) {
+          return { data: 5 }
+        },
+      }),
+      withAsyncErrorQueryFn: build.query<string, string>({
+        async queryFn(arg: string) {
+          return { error: `resultFrom(${arg})` }
+        },
+      }),
+      withInvalidAsyncErrorQueryFn: build.query<string, string>({
+        // @ts-expect-error
+        async queryFn(arg: string) {
+          return { error: 5 }
+        },
+      }),
+      withAsyncThrowingQueryFn: build.query<string, string>({
+        async queryFn(arg: string) {
+          throw new Error(`resultFrom(${arg})`)
+        },
+      }),
+      mutationWithQueryFn: build.mutation<string, string>({
+        queryFn(arg: string) {
+          return { data: `resultFrom(${arg})` }
+        },
+      }),
+      mutationWithInvalidDataQueryFn: build.mutation<string, string>({
+        // @ts-expect-error
+        queryFn(arg: string) {
+          return { data: 5 }
+        },
+      }),
+      mutationWithErrorQueryFn: build.mutation<string, string>({
+        queryFn(arg: string) {
+          return { error: `resultFrom(${arg})` }
+        },
+      }),
+      mutationWithInvalidErrorQueryFn: build.mutation<string, string>({
+        // @ts-expect-error
+        queryFn(arg: string) {
+          return { error: 5 }
+        },
+      }),
+      mutationWithThrowingQueryFn: build.mutation<string, string>({
+        queryFn(arg: string) {
+          throw new Error(`resultFrom(${arg})`)
+        },
+      }),
+      mutationWithAsyncQueryFn: build.mutation<string, string>({
+        async queryFn(arg: string) {
+          return { data: `resultFrom(${arg})` }
+        },
+      }),
+      mutationWithInvalidAsyncQueryFn: build.mutation<string, string>({
+        // @ts-expect-error
+        async queryFn(arg: string) {
+          return { data: 5 }
+        },
+      }),
+      mutationWithAsyncErrorQueryFn: build.mutation<string, string>({
+        async queryFn(arg: string) {
+          return { error: `resultFrom(${arg})` }
+        },
+      }),
+      mutationWithInvalidAsyncErrorQueryFn: build.mutation<string, string>({
+        // @ts-expect-error
+        async queryFn(arg: string) {
+          return { error: 5 }
+        },
+      }),
+      mutationWithAsyncThrowingQueryFn: build.mutation<string, string>({
+        async queryFn(arg: string) {
+          throw new Error(`resultFrom(${arg})`)
+        },
+      }),
+      // @ts-expect-error
+      withNeither: build.query<string, string>({}),
+      // @ts-expect-error
+      mutationWithNeither: build.mutation<string, string>({}),
+    }),
+  })
+
+  const {
+    withQuery,
+    withErrorQuery,
+    withQueryFn,
+    withErrorQueryFn,
+    withThrowingQueryFn,
+    withAsyncQueryFn,
+    withAsyncErrorQueryFn,
+    withAsyncThrowingQueryFn,
+    mutationWithQueryFn,
+    mutationWithErrorQueryFn,
+    mutationWithThrowingQueryFn,
+    mutationWithAsyncQueryFn,
+    mutationWithAsyncErrorQueryFn,
+    mutationWithAsyncThrowingQueryFn,
+    withNeither,
+    mutationWithNeither,
+  } = api.endpoints
+
+  const store = configureStore({
+    reducer: {
+      [api.reducerPath]: api.reducer,
+    },
+    middleware: (gDM) => gDM({}).concat(api.middleware),
+  })
+
+  test.each([
+    ['withQuery', withQuery, 'data'],
+    ['withErrorQuery', withErrorQuery, 'error'],
+    ['withQueryFn', withQueryFn, 'data'],
+    ['withErrorQueryFn', withErrorQueryFn, 'error'],
+    ['withThrowingQueryFn', withThrowingQueryFn, 'throw'],
+    ['withAsyncQueryFn', withAsyncQueryFn, 'data'],
+    ['withAsyncErrorQueryFn', withAsyncErrorQueryFn, 'error'],
+    ['withAsyncThrowingQueryFn', withAsyncThrowingQueryFn, 'throw'],
+  ])('%s', async (endpointName, endpoint, expectedResult) => {
+    const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+    const thunk = endpoint.initiate(endpointName)
+
+    const result: undefined | QuerySubState<any> = await store.dispatch(thunk)
+
+    if (endpointName.includes('Throw')) {
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        `An unhandled error occurred processing a request for the endpoint "${endpointName}".\nIn the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+        Error(`resultFrom(${endpointName})`),
+      )
+    } else {
+      expect(consoleErrorSpy).not.toHaveBeenCalled()
+    }
+
+    if (expectedResult === 'data') {
+      expect(result).toEqual(
+        expect.objectContaining({
+          data: `resultFrom(${endpointName})`,
+        }),
+      )
+    } else if (expectedResult === 'error') {
+      expect(result).toEqual(
+        expect.objectContaining({
+          error: `resultFrom(${endpointName})`,
+        }),
+      )
+    } else {
+      expect(result).toEqual(
+        expect.objectContaining({
+          error: expect.objectContaining({
+            message: `resultFrom(${endpointName})`,
+          }),
+        }),
+      )
+    }
+
+    consoleErrorSpy.mockRestore()
+  })
+
+  test.each([
+    ['mutationWithQueryFn', mutationWithQueryFn, 'data'],
+    ['mutationWithErrorQueryFn', mutationWithErrorQueryFn, 'error'],
+    ['mutationWithThrowingQueryFn', mutationWithThrowingQueryFn, 'throw'],
+    ['mutationWithAsyncQueryFn', mutationWithAsyncQueryFn, 'data'],
+    ['mutationWithAsyncErrorQueryFn', mutationWithAsyncErrorQueryFn, 'error'],
+    [
+      'mutationWithAsyncThrowingQueryFn',
+      mutationWithAsyncThrowingQueryFn,
+      'throw',
+    ],
+  ])('%s', async (endpointName, endpoint, expectedResult) => {
+    const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+    const thunk = endpoint.initiate(endpointName)
+
+    const result:
+      | undefined
+      | { data: string }
+      | { error: string | SerializedError } = await store.dispatch(thunk)
+
+    if (endpointName.includes('Throw')) {
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        `An unhandled error occurred processing a request for the endpoint "${endpointName}".\nIn the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+        Error(`resultFrom(${endpointName})`),
+      )
+    } else {
+      expect(consoleErrorSpy).not.toHaveBeenCalled()
+    }
+
+    if (expectedResult === 'data') {
+      expect(result).toEqual(
+        expect.objectContaining({
+          data: `resultFrom(${endpointName})`,
+        }),
+      )
+    } else if (expectedResult === 'error') {
+      expect(result).toEqual(
+        expect.objectContaining({
+          error: `resultFrom(${endpointName})`,
+        }),
+      )
+    } else {
+      expect(result).toEqual(
+        expect.objectContaining({
+          error: expect.objectContaining({
+            message: `resultFrom(${endpointName})`,
+          }),
+        }),
+      )
+    }
+
+    consoleErrorSpy.mockRestore()
+  })
+
+  test('neither provided', async () => {
+    const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+    {
+      const thunk = withNeither.initiate('withNeither')
+
+      const result: QuerySubState<any> = await store.dispatch(thunk)
+
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        `An unhandled error occurred processing a request for the endpoint "withNeither".\nIn the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+        TypeError('endpointDefinition.queryFn is not a function'),
+      )
+
+      expect(result.error).toEqual(
+        expect.objectContaining({
+          message: 'endpointDefinition.queryFn is not a function',
+        }),
+      )
+
+      consoleErrorSpy.mockClear()
+    }
+    {
+      const thunk = mutationWithNeither.initiate('mutationWithNeither')
+
+      const result:
+        | undefined
+        | { data: string }
+        | { error: string | SerializedError } = await store.dispatch(thunk)
+
+      expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+      expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+        `An unhandled error occurred processing a request for the endpoint "mutationWithNeither".\nIn the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+        TypeError('endpointDefinition.queryFn is not a function'),
+      )
+
+      if (!('error' in result)) {
+        expect.fail()
+      }
+
+      expect(result.error).toEqual(
+        expect.objectContaining({
+          message: 'endpointDefinition.queryFn is not a function',
+        }),
+      )
+    }
+
+    consoleErrorSpy.mockRestore()
+  })
+})
+
+describe('usage scenario tests', () => {
+  const mockData = { id: 1, name: 'Banana' }
+  const mockDocResult = {
+    exists: () => true,
+    data: () => mockData,
+  }
+  const get = vi.fn(() => Promise.resolve(mockDocResult))
+  const doc = vi.fn((name) => ({
+    get,
+  }))
+  const collection = vi.fn((name) => ({ get, doc }))
+  const firestore = () => {
+    return { collection, doc }
+  }
+
+  const baseQuery = fetchBaseQuery({ baseUrl: 'https://example.com/' })
+  const api = createApi({
+    baseQuery,
+    endpoints: (build) => ({
+      getRandomUser: build.query<Post, void>({
+        async queryFn(_arg: void, _queryApi, _extraOptions, fetchWithBQ) {
+          // get a random post
+          const randomResult = await fetchWithBQ('posts/random')
+          if (randomResult.error) {
+            throw randomResult.error
+          }
+          const post = randomResult.data as Post
+          const result = await fetchWithBQ(`/post/${post.id}`)
+          return result.data
+            ? { data: result.data as Post }
+            : { error: result.error as FetchBaseQueryError }
+        },
+      }),
+      getFirebaseUser: build.query<typeof mockData, number>({
+        async queryFn(arg: number) {
+          const getResult = await firestore().collection('users').doc(arg).get()
+          if (!getResult.exists()) {
+            throw new Error('Missing user')
+          }
+          return { data: getResult.data() }
+        },
+      }),
+      getMissingFirebaseUser: build.query<typeof mockData, number>({
+        async queryFn(arg: number) {
+          const getResult = await firestore().collection('users').doc(arg).get()
+          // intentionally throw if it exists to keep the mocking overhead low
+          if (getResult.exists()) {
+            throw new Error('Missing user')
+          }
+          return { data: getResult.data() }
+        },
+      }),
+    }),
+  })
+
+  const storeRef = setupApiStore(api, {
+    ...actionsReducer,
+  })
+
+  /**
+   * Allow for a scenario where you can chain X requests
+   * https://discord.com/channels/102860784329052160/103538784460615680/825430959247720449
+   * const resp1 = await api.get(url);
+   * const resp2 = await api.get(`${url2}/id=${resp1.data.id}`);
+   */
+
+  it('can chain multiple queries together', async () => {
+    const result = await storeRef.store.dispatch(
+      api.endpoints.getRandomUser.initiate(),
+    )
+    expect(result.data).toEqual(posts[1])
+  })
+
+  it('can wrap a service like Firebase', async () => {
+    const result = await storeRef.store.dispatch(
+      api.endpoints.getFirebaseUser.initiate(1),
+    )
+    expect(result.data).toEqual(mockData)
+  })
+
+  it('can wrap a service like Firebase and handle errors', async () => {
+    const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
+
+    const result: QuerySubState<any> = await storeRef.store.dispatch(
+      api.endpoints.getMissingFirebaseUser.initiate(1),
+    )
+
+    expect(consoleErrorSpy).toHaveBeenCalledOnce()
+
+    expect(consoleErrorSpy).toHaveBeenLastCalledWith(
+      `An unhandled error occurred processing a request for the endpoint "getMissingFirebaseUser".\nIn the case of an unhandled error, no tags will be "provided" or "invalidated".`,
+      Error('Missing user'),
+    )
+
+    expect(result.data).toBeUndefined()
+    expect(result.error).toEqual(
+      expect.objectContaining({
+        message: 'Missing user',
+        name: 'Error',
+      }),
+    )
+
+    consoleErrorSpy.mockRestore()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/queryLifecycle.test-d.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/queryLifecycle.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/queryLifecycle.test-d.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,371 @@
+import type { PatchCollection, Recipe } from '@internal/query/core/buildThunks'
+import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit'
+import type {
+  FetchBaseQueryError,
+  FetchBaseQueryMeta,
+  RootState,
+  TypedMutationOnQueryStarted,
+  TypedQueryOnQueryStarted,
+} from '@reduxjs/toolkit/query'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+
+const api = createApi({
+  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+  endpoints: () => ({}),
+})
+
+describe('type tests', () => {
+  test(`mutation: onStart and onSuccess`, async () => {
+    const extended = api.injectEndpoints({
+      overrideExisting: true,
+      endpoints: (build) => ({
+        injected: build.mutation<number, string>({
+          query: () => '/success',
+          async onQueryStarted(arg, { queryFulfilled }) {
+            // awaiting without catching like this would result in an `unhandledRejection` exception if there was an error
+            // unfortunately we cannot test for that in jest.
+            const result = await queryFulfilled
+
+            expectTypeOf(result).toMatchTypeOf<{
+              data: number
+              meta?: FetchBaseQueryMeta
+            }>()
+          },
+        }),
+      }),
+    })
+  })
+
+  test('query types', () => {
+    const extended = api.injectEndpoints({
+      overrideExisting: true,
+      endpoints: (build) => ({
+        injected: build.query<number, string>({
+          query: () => '/success',
+          async onQueryStarted(arg, { queryFulfilled }) {
+            queryFulfilled.then(
+              (result) => {
+                expectTypeOf(result).toMatchTypeOf<{
+                  data: number
+                  meta?: FetchBaseQueryMeta
+                }>()
+              },
+              (reason) => {
+                if (reason.isUnhandledError) {
+                  expectTypeOf(reason).toEqualTypeOf<{
+                    error: unknown
+                    meta?: undefined
+                    isUnhandledError: true
+                  }>()
+                } else {
+                  expectTypeOf(reason).toEqualTypeOf<{
+                    error: FetchBaseQueryError
+                    isUnhandledError: false
+                    meta: FetchBaseQueryMeta | undefined
+                  }>()
+                }
+              },
+            )
+
+            queryFulfilled.catch((reason) => {
+              if (reason.isUnhandledError) {
+                expectTypeOf(reason).toEqualTypeOf<{
+                  error: unknown
+                  meta?: undefined
+                  isUnhandledError: true
+                }>()
+              } else {
+                expectTypeOf(reason).toEqualTypeOf<{
+                  error: FetchBaseQueryError
+                  isUnhandledError: false
+                  meta: FetchBaseQueryMeta | undefined
+                }>()
+              }
+            })
+
+            const result = await queryFulfilled
+
+            expectTypeOf(result).toMatchTypeOf<{
+              data: number
+              meta?: FetchBaseQueryMeta
+            }>()
+          },
+        }),
+      }),
+    })
+  })
+
+  test('mutation types', () => {
+    const extended = api.injectEndpoints({
+      overrideExisting: true,
+      endpoints: (build) => ({
+        injected: build.query<number, string>({
+          query: () => '/success',
+          async onQueryStarted(arg, { queryFulfilled }) {
+            queryFulfilled.then(
+              (result) => {
+                expectTypeOf(result).toMatchTypeOf<{
+                  data: number
+                  meta?: FetchBaseQueryMeta
+                }>()
+              },
+              (reason) => {
+                if (reason.isUnhandledError) {
+                  expectTypeOf(reason).toEqualTypeOf<{
+                    error: unknown
+                    meta?: undefined
+                    isUnhandledError: true
+                  }>()
+                } else {
+                  expectTypeOf(reason).toEqualTypeOf<{
+                    error: FetchBaseQueryError
+                    isUnhandledError: false
+                    meta: FetchBaseQueryMeta | undefined
+                  }>()
+                }
+              },
+            )
+
+            queryFulfilled.catch((reason) => {
+              if (reason.isUnhandledError) {
+                expectTypeOf(reason).toEqualTypeOf<{
+                  error: unknown
+                  meta?: undefined
+                  isUnhandledError: true
+                }>()
+              } else {
+                expectTypeOf(reason).toEqualTypeOf<{
+                  error: FetchBaseQueryError
+                  isUnhandledError: false
+                  meta: FetchBaseQueryMeta | undefined
+                }>()
+              }
+            })
+
+            const result = await queryFulfilled
+
+            expectTypeOf(result).toMatchTypeOf<{
+              data: number
+              meta?: FetchBaseQueryMeta
+            }>()
+          },
+        }),
+      }),
+    })
+  })
+
+  describe('typed `onQueryStarted` function', () => {
+    test('TypedQueryOnQueryStarted creates a pre-typed version of onQueryStarted', () => {
+      type Post = {
+        id: number
+        title: string
+        userId: number
+      }
+
+      type PostsApiResponse = {
+        posts: Post[]
+        total: number
+        skip: number
+        limit: number
+      }
+
+      type QueryArgument = number | undefined
+
+      type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
+
+      const baseApiSlice = createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),
+        reducerPath: 'postsApi',
+        tagTypes: ['Posts'],
+        endpoints: (builder) => ({
+          getPosts: builder.query<PostsApiResponse, void>({
+            query: () => `/posts`,
+          }),
+
+          getPostById: builder.query<Post, QueryArgument>({
+            query: (postId) => `/posts/${postId}`,
+          }),
+        }),
+      })
+
+      const updatePostOnFulfilled: TypedQueryOnQueryStarted<
+        PostsApiResponse,
+        QueryArgument,
+        BaseQueryFunction,
+        'postsApi'
+      > = async (queryArgument, queryLifeCycleApi) => {
+        const {
+          dispatch,
+          extra,
+          getCacheEntry,
+          getState,
+          queryFulfilled,
+          requestId,
+          updateCachedData,
+        } = queryLifeCycleApi
+
+        expectTypeOf(queryArgument).toEqualTypeOf<QueryArgument>()
+
+        expectTypeOf(dispatch).toEqualTypeOf<
+          ThunkDispatch<any, any, UnknownAction>
+        >()
+
+        expectTypeOf(extra).toBeUnknown()
+
+        expectTypeOf(getState).toEqualTypeOf<
+          () => RootState<any, any, 'postsApi'>
+        >()
+
+        expectTypeOf(requestId).toBeString()
+
+        expectTypeOf(getCacheEntry).toBeFunction()
+
+        expectTypeOf(updateCachedData).toEqualTypeOf<
+          (updateRecipe: Recipe<PostsApiResponse>) => PatchCollection
+        >()
+
+        expectTypeOf(queryFulfilled).resolves.toEqualTypeOf<{
+          data: PostsApiResponse
+          meta: FetchBaseQueryMeta | undefined
+        }>()
+
+        const result = await queryFulfilled
+
+        const { posts } = result.data
+
+        dispatch(
+          baseApiSlice.util.upsertQueryEntries(
+            posts.map((post) => ({
+              // Without `as const` this will result in a TS error in TS 4.7.
+              endpointName: 'getPostById' as const,
+              arg: post.id,
+              value: post,
+            })),
+          ),
+        )
+      }
+
+      const extendedApiSlice = baseApiSlice.injectEndpoints({
+        endpoints: (builder) => ({
+          getPostsByUserId: builder.query<PostsApiResponse, QueryArgument>({
+            query: (userId) => `/posts/user/${userId}`,
+
+            onQueryStarted: updatePostOnFulfilled,
+          }),
+        }),
+      })
+    })
+
+    test('TypedMutationOnQueryStarted creates a pre-typed version of onQueryStarted', () => {
+      type Post = {
+        id: number
+        title: string
+        userId: number
+      }
+
+      type PostsApiResponse = {
+        posts: Post[]
+        total: number
+        skip: number
+        limit: number
+      }
+
+      type QueryArgument = Pick<Post, 'id'> & Partial<Post>
+
+      type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
+
+      const baseApiSlice = createApi({
+        baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),
+        reducerPath: 'postsApi',
+        tagTypes: ['Posts'],
+        endpoints: (builder) => ({
+          getPosts: builder.query<PostsApiResponse, void>({
+            query: () => `/posts`,
+          }),
+
+          getPostById: builder.query<Post, number>({
+            query: (postId) => `/posts/${postId}`,
+          }),
+        }),
+      })
+
+      const updatePostOnFulfilled: TypedMutationOnQueryStarted<
+        Post,
+        QueryArgument,
+        BaseQueryFunction,
+        'postsApi'
+      > = async (queryArgument, mutationLifeCycleApi) => {
+        const { id, ...patch } = queryArgument
+        const {
+          dispatch,
+          extra,
+          getCacheEntry,
+          getState,
+          queryFulfilled,
+          requestId,
+        } = mutationLifeCycleApi
+
+        const patchCollection = dispatch(
+          baseApiSlice.util.updateQueryData('getPostById', id, (draftPost) => {
+            Object.assign(draftPost, patch)
+          }),
+        )
+
+        expectTypeOf(queryFulfilled).resolves.toEqualTypeOf<{
+          data: Post
+          meta: FetchBaseQueryMeta | undefined
+        }>()
+
+        expectTypeOf(queryArgument).toEqualTypeOf<QueryArgument>()
+
+        expectTypeOf(dispatch).toEqualTypeOf<
+          ThunkDispatch<any, any, UnknownAction>
+        >()
+
+        expectTypeOf(extra).toBeUnknown()
+
+        expectTypeOf(getState).toEqualTypeOf<
+          () => RootState<any, any, 'postsApi'>
+        >()
+
+        expectTypeOf(requestId).toBeString()
+
+        expectTypeOf(getCacheEntry).toBeFunction()
+
+        expectTypeOf(mutationLifeCycleApi).not.toHaveProperty(
+          'updateCachedData',
+        )
+
+        try {
+          await queryFulfilled
+        } catch {
+          patchCollection.undo()
+        }
+      }
+
+      const extendedApiSlice = baseApiSlice.injectEndpoints({
+        endpoints: (builder) => ({
+          addPost: builder.mutation<Post, Omit<QueryArgument, 'id'>>({
+            query: (body) => ({
+              url: `posts/add`,
+              method: 'POST',
+              body,
+            }),
+
+            onQueryStarted: updatePostOnFulfilled,
+          }),
+
+          updatePost: builder.mutation<Post, QueryArgument>({
+            query: ({ id, ...patch }) => ({
+              url: `post/${id}`,
+              method: 'PATCH',
+              body: patch,
+            }),
+
+            onQueryStarted: updatePostOnFulfilled,
+          }),
+        }),
+      })
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/queryLifecycle.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/queryLifecycle.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/queryLifecycle.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,547 @@
+import { server } from '@internal/query/tests/mocks/server'
+import { setupApiStore } from '@internal/tests/utils/helpers'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
+import { waitFor } from '@testing-library/react'
+import { HttpResponse, http } from 'msw'
+import { vi } from 'vitest'
+
+const api = createApi({
+  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),
+  endpoints: () => ({}),
+})
+const storeRef = setupApiStore(api)
+
+const onStart = vi.fn()
+const onSuccess = vi.fn()
+const onError = vi.fn()
+
+beforeEach(() => {
+  onStart.mockClear()
+  onSuccess.mockClear()
+  onError.mockClear()
+})
+
+describe.each([['query'], ['mutation']] as const)(
+  'generic cases: %s',
+  (type) => {
+    test(`${type}: onStart only`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/success',
+            onQueryStarted(arg) {
+              onStart(arg)
+            },
+          }),
+        }),
+      })
+      storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))
+      expect(onStart).toHaveBeenCalledWith('arg')
+    })
+
+    test(`${type}: onStart and onSuccess`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<number, string>({
+            query: () => '/success',
+            async onQueryStarted(arg, { queryFulfilled }) {
+              onStart(arg)
+              // awaiting without catching like this would result in an `unhandledRejection` exception if there was an error
+              // unfortunately we cannot test for that in jest.
+              const result = await queryFulfilled
+              onSuccess(result)
+            },
+          }),
+        }),
+      })
+      storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))
+      expect(onStart).toHaveBeenCalledWith('arg')
+      await waitFor(() => {
+        expect(onSuccess).toHaveBeenCalledWith({
+          data: { value: 'success' },
+          meta: {
+            request: expect.any(Request),
+            response: expect.any(Object), // Response is not available in jest env
+          },
+        })
+      })
+    })
+
+    test(`${type}: onStart and onError`, async () => {
+      const extended = api.injectEndpoints({
+        overrideExisting: true,
+        endpoints: (build) => ({
+          injected: build[type as 'mutation']<unknown, string>({
+            query: () => '/error',
+            async onQueryStarted(arg, { queryFulfilled }) {
+              onStart(arg)
+              try {
+                const result = await queryFulfilled
+                onSuccess(result)
+              } catch (e) {
+                onError(e)
+              }
+            },
+          }),
+        }),
+      })
+      storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))
+      expect(onStart).toHaveBeenCalledWith('arg')
+      await waitFor(() => {
+        expect(onError).toHaveBeenCalledWith({
+          error: {
+            status: 500,
+            data: { value: 'error' },
+          },
+          isUnhandledError: false,
+          meta: {
+            request: expect.any(Request),
+            response: expect.any(Object), // Response is not available in jest env
+          },
+        })
+      })
+      expect(onSuccess).not.toHaveBeenCalled()
+    })
+  },
+)
+
+test('query: getCacheEntry (success)', async () => {
+  const snapshot = vi.fn()
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<unknown, string>({
+        query: () => '/success',
+        async onQueryStarted(
+          arg,
+          { dispatch, getState, getCacheEntry, queryFulfilled },
+        ) {
+          try {
+            snapshot(getCacheEntry())
+            const result = await queryFulfilled
+            onSuccess(result)
+            snapshot(getCacheEntry())
+          } catch (e) {
+            onError(e)
+            snapshot(getCacheEntry())
+          }
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+
+  await waitFor(() => {
+    expect(onSuccess).toHaveBeenCalled()
+  })
+
+  expect(snapshot).toHaveBeenCalledTimes(2)
+  expect(snapshot.mock.calls[0][0]).toMatchObject({
+    endpointName: 'injected',
+    isError: false,
+    isLoading: true,
+    isSuccess: false,
+    isUninitialized: false,
+    originalArgs: 'arg',
+    requestId: promise.requestId,
+    startedTimeStamp: expect.any(Number),
+    status: 'pending',
+  })
+  expect(snapshot.mock.calls[1][0]).toMatchObject({
+    data: {
+      value: 'success',
+    },
+    endpointName: 'injected',
+    fulfilledTimeStamp: expect.any(Number),
+    isError: false,
+    isLoading: false,
+    isSuccess: true,
+    isUninitialized: false,
+    originalArgs: 'arg',
+    requestId: promise.requestId,
+    startedTimeStamp: expect.any(Number),
+    status: 'fulfilled',
+  })
+})
+
+test('query: getCacheEntry (error)', async () => {
+  const snapshot = vi.fn()
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<unknown, string>({
+        query: () => '/error',
+        async onQueryStarted(
+          arg,
+          { dispatch, getState, getCacheEntry, queryFulfilled },
+        ) {
+          try {
+            snapshot(getCacheEntry())
+            const result = await queryFulfilled
+            onSuccess(result)
+            snapshot(getCacheEntry())
+          } catch (e) {
+            onError(e)
+            snapshot(getCacheEntry())
+          }
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+
+  await waitFor(() => {
+    expect(onError).toHaveBeenCalled()
+  })
+
+  expect(snapshot.mock.calls[0][0]).toMatchObject({
+    endpointName: 'injected',
+    isError: false,
+    isLoading: true,
+    isSuccess: false,
+    isUninitialized: false,
+    originalArgs: 'arg',
+    requestId: promise.requestId,
+    startedTimeStamp: expect.any(Number),
+    status: 'pending',
+  })
+  expect(snapshot.mock.calls[1][0]).toMatchObject({
+    error: {
+      data: { value: 'error' },
+      status: 500,
+    },
+    endpointName: 'injected',
+    isError: true,
+    isLoading: false,
+    isSuccess: false,
+    isUninitialized: false,
+    originalArgs: 'arg',
+    requestId: promise.requestId,
+    startedTimeStamp: expect.any(Number),
+    status: 'rejected',
+  })
+})
+
+test('mutation: getCacheEntry (success)', async () => {
+  const snapshot = vi.fn()
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.mutation<unknown, string>({
+        query: () => '/success',
+        async onQueryStarted(
+          arg,
+          { dispatch, getState, getCacheEntry, queryFulfilled },
+        ) {
+          try {
+            snapshot(getCacheEntry())
+            const result = await queryFulfilled
+            onSuccess(result)
+            snapshot(getCacheEntry())
+          } catch (e) {
+            onError(e)
+            snapshot(getCacheEntry())
+          }
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+
+  await waitFor(() => {
+    expect(onSuccess).toHaveBeenCalled()
+  })
+
+  expect(snapshot).toHaveBeenCalledTimes(2)
+  expect(snapshot.mock.calls[0][0]).toMatchObject({
+    endpointName: 'injected',
+    isError: false,
+    isLoading: true,
+    isSuccess: false,
+    isUninitialized: false,
+    startedTimeStamp: expect.any(Number),
+    status: 'pending',
+  })
+  expect(snapshot.mock.calls[1][0]).toMatchObject({
+    data: {
+      value: 'success',
+    },
+    endpointName: 'injected',
+    fulfilledTimeStamp: expect.any(Number),
+    isError: false,
+    isLoading: false,
+    isSuccess: true,
+    isUninitialized: false,
+    startedTimeStamp: expect.any(Number),
+    status: 'fulfilled',
+  })
+})
+
+test('mutation: getCacheEntry (error)', async () => {
+  const snapshot = vi.fn()
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.mutation<unknown, string>({
+        query: () => '/error',
+        async onQueryStarted(
+          arg,
+          { dispatch, getState, getCacheEntry, queryFulfilled },
+        ) {
+          try {
+            snapshot(getCacheEntry())
+            const result = await queryFulfilled
+            onSuccess(result)
+            snapshot(getCacheEntry())
+          } catch (e) {
+            onError(e)
+            snapshot(getCacheEntry())
+          }
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+
+  await waitFor(() => {
+    expect(onError).toHaveBeenCalled()
+  })
+
+  expect(snapshot.mock.calls[0][0]).toMatchObject({
+    endpointName: 'injected',
+    isError: false,
+    isLoading: true,
+    isSuccess: false,
+    isUninitialized: false,
+    startedTimeStamp: expect.any(Number),
+    status: 'pending',
+  })
+  expect(snapshot.mock.calls[1][0]).toMatchObject({
+    error: {
+      data: { value: 'error' },
+      status: 500,
+    },
+    endpointName: 'injected',
+    isError: true,
+    isLoading: false,
+    isSuccess: false,
+    isUninitialized: false,
+    startedTimeStamp: expect.any(Number),
+    status: 'rejected',
+  })
+})
+
+test('query: updateCachedData', async () => {
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<{ value: string }, string>({
+        query: () => '/success',
+        async onQueryStarted(
+          arg,
+          {
+            dispatch,
+            getState,
+            getCacheEntry,
+            updateCachedData,
+            queryFulfilled,
+          },
+        ) {
+          // calling `updateCachedData` when there is no data yet should not do anything
+          // but if there is a cache value it will be updated & overwritten by the next successful result
+          updateCachedData((draft) => {
+            draft.value += '.'
+          })
+
+          try {
+            await queryFulfilled
+            onSuccess(getCacheEntry().data)
+          } catch (error) {
+            updateCachedData((draft) => {
+              draft.value += 'x'
+            })
+            onError(getCacheEntry().data)
+          }
+        },
+      }),
+    }),
+  })
+
+  // request 1: success
+  expect(onSuccess).not.toHaveBeenCalled()
+  storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))
+
+  await waitFor(() => {
+    expect(onSuccess).toHaveBeenCalled()
+  })
+  expect(onSuccess).toHaveBeenCalledWith({ value: 'success' })
+  onSuccess.mockClear()
+
+  // request 2: error
+  expect(onError).not.toHaveBeenCalled()
+  server.use(
+    http.get(
+      'https://example.com/success',
+      () => {
+        return HttpResponse.json({ value: 'failed' }, { status: 500 })
+      },
+      { once: true },
+    ),
+  )
+  storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg', { forceRefetch: true }),
+  )
+
+  await waitFor(() => {
+    expect(onError).toHaveBeenCalled()
+  })
+  expect(onError).toHaveBeenCalledWith({ value: 'success.x' })
+
+  // request 3: success
+  expect(onSuccess).not.toHaveBeenCalled()
+
+  storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg', { forceRefetch: true }),
+  )
+
+  await waitFor(() => {
+    expect(onSuccess).toHaveBeenCalled()
+  })
+  expect(onSuccess).toHaveBeenCalledWith({ value: 'success' })
+  onSuccess.mockClear()
+})
+
+test('infinite query: updateCachedData', async () => {
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      infiniteInjected: build.infiniteQuery<{ value: string }, string, number>({
+        query: () => '/success',
+        infiniteQueryOptions: {
+          initialPageParam: 1,
+          getNextPageParam: (
+            lastPage,
+            allPages,
+            lastPageParam,
+            allPageParams,
+          ) => lastPageParam + 1,
+        },
+        async onQueryStarted(
+          arg,
+          {
+            dispatch,
+            getState,
+            getCacheEntry,
+            updateCachedData,
+            queryFulfilled,
+          },
+        ) {
+          // calling `updateCachedData` when there is no data yet should not do anything
+          // but if there is a cache value it will be updated & overwritten by the next successful result
+          updateCachedData((draft) => {
+            draft.pages = [{ value: '.' }]
+            draft.pageParams = [1]
+          })
+
+          try {
+            await queryFulfilled
+            onSuccess(getCacheEntry().data)
+          } catch (error) {
+            updateCachedData((draft) => {
+              draft.pages = [{ value: 'success.x' }]
+              draft.pageParams = [1]
+            })
+            onError(getCacheEntry().data)
+          }
+        },
+      }),
+    }),
+  })
+
+  // request 1: success
+  expect(onSuccess).not.toHaveBeenCalled()
+  storeRef.store.dispatch(extended.endpoints.infiniteInjected.initiate('arg'))
+
+  await waitFor(() => {
+    expect(onSuccess).toHaveBeenCalled()
+  })
+  expect(onSuccess).toHaveBeenCalledWith({
+    pages: [{ value: 'success' }],
+    pageParams: [1],
+  })
+  onSuccess.mockClear()
+
+  // request 2: error
+  expect(onError).not.toHaveBeenCalled()
+  server.use(
+    http.get(
+      'https://example.com/success',
+      () => {
+        return HttpResponse.json({ value: 'failed' }, { status: 500 })
+      },
+      { once: true },
+    ),
+  )
+  storeRef.store.dispatch(
+    extended.endpoints.infiniteInjected.initiate('arg', { forceRefetch: true }),
+  )
+
+  await waitFor(() => {
+    expect(onError).toHaveBeenCalled()
+  })
+  expect(onError).toHaveBeenCalledWith({
+    pages: [{ value: 'success.x' }],
+    pageParams: [1],
+  })
+
+  // request 3: success
+  expect(onSuccess).not.toHaveBeenCalled()
+
+  storeRef.store.dispatch(
+    extended.endpoints.infiniteInjected.initiate('arg', { forceRefetch: true }),
+  )
+
+  await waitFor(() => {
+    expect(onSuccess).toHaveBeenCalled()
+  })
+  expect(onSuccess).toHaveBeenCalledWith({
+    pages: [{ value: 'success' }],
+    pageParams: [1],
+  })
+  onSuccess.mockClear()
+})
+
+test('query: will only start lifecycle if query is not skipped due to `condition`', async () => {
+  const extended = api.injectEndpoints({
+    overrideExisting: true,
+    endpoints: (build) => ({
+      injected: build.query<unknown, string>({
+        query: () => '/success',
+        onQueryStarted(arg) {
+          onStart(arg)
+        },
+      }),
+    }),
+  })
+  const promise = storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg'),
+  )
+  expect(onStart).toHaveBeenCalledOnce()
+  storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))
+  expect(onStart).toHaveBeenCalledOnce()
+  await promise
+  storeRef.store.dispatch(
+    extended.endpoints.injected.initiate('arg', { forceRefetch: true }),
+  )
+  expect(onStart).toHaveBeenCalledTimes(2)
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/raceConditions.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/raceConditions.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/raceConditions.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,109 @@
+import { createApi, QueryStatus } from '@reduxjs/toolkit/query'
+import { delay } from 'msw'
+import { actionsReducer, setupApiStore } from '../../tests/utils/helpers'
+
+// We need to be able to control when which query resolves to simulate race
+// conditions properly, that's the purpose of this factory.
+const createPromiseFactory = () => {
+  const resolveQueue: (() => void)[] = []
+  const createPromise = () =>
+    new Promise<void>((resolve) => {
+      resolveQueue.push(resolve)
+    })
+  const resolveOldest = () => {
+    resolveQueue.shift()?.()
+  }
+  return { createPromise, resolveOldest }
+}
+
+const getEatenBananaPromises = createPromiseFactory()
+const eatBananaPromises = createPromiseFactory()
+
+let eatenBananas = 0
+const api = createApi({
+  invalidationBehavior: 'delayed',
+  baseQuery: () => undefined as any,
+  tagTypes: ['Banana'],
+  endpoints: (build) => ({
+    // Eat a banana.
+    eatBanana: build.mutation<unknown, void>({
+      queryFn: async () => {
+        await eatBananaPromises.createPromise()
+        eatenBananas += 1
+        return { data: null, meta: {} }
+      },
+      invalidatesTags: ['Banana'],
+    }),
+
+    // Get the number of eaten bananas.
+    getEatenBananas: build.query<number, void>({
+      queryFn: async (arg, arg1, arg2, arg3) => {
+        const result = eatenBananas
+        await getEatenBananaPromises.createPromise()
+        return { data: result }
+      },
+      providesTags: ['Banana'],
+    }),
+  }),
+})
+const { getEatenBananas, eatBanana } = api.endpoints
+
+const storeRef = setupApiStore(api, {
+  ...actionsReducer,
+})
+
+it('invalidates a query after a corresponding mutation', async () => {
+  eatenBananas = 0
+
+  const query = storeRef.store.dispatch(getEatenBananas.initiate())
+  const getQueryState = () =>
+    storeRef.store.getState().api.queries[query.queryCacheKey]
+  getEatenBananaPromises.resolveOldest()
+  await delay(2)
+
+  expect(getQueryState()?.data).toBe(0)
+  expect(getQueryState()?.status).toBe(QueryStatus.fulfilled)
+
+  const mutation = storeRef.store.dispatch(eatBanana.initiate())
+  const getMutationState = () =>
+    storeRef.store.getState().api.mutations[mutation.requestId]
+  eatBananaPromises.resolveOldest()
+  await delay(2)
+
+  expect(getMutationState()?.status).toBe(QueryStatus.fulfilled)
+  expect(getQueryState()?.data).toBe(0)
+  expect(getQueryState()?.status).toBe(QueryStatus.pending)
+
+  getEatenBananaPromises.resolveOldest()
+  await delay(2)
+
+  expect(getQueryState()?.data).toBe(1)
+  expect(getQueryState()?.status).toBe(QueryStatus.fulfilled)
+})
+
+it('invalidates a query whose corresponding mutation finished while the query was in flight', async () => {
+  eatenBananas = 0
+
+  const query = storeRef.store.dispatch(getEatenBananas.initiate())
+  const getQueryState = () =>
+    storeRef.store.getState().api.queries[query.queryCacheKey]
+
+  const mutation = storeRef.store.dispatch(eatBanana.initiate())
+  const getMutationState = () =>
+    storeRef.store.getState().api.mutations[mutation.requestId]
+  eatBananaPromises.resolveOldest()
+  await delay(2)
+  expect(getMutationState()?.status).toBe(QueryStatus.fulfilled)
+
+  getEatenBananaPromises.resolveOldest()
+  await delay(2)
+  expect(getQueryState()?.data).toBe(0)
+  expect(getQueryState()?.status).toBe(QueryStatus.pending)
+
+  // should already be refetching
+  getEatenBananaPromises.resolveOldest()
+  await delay(2)
+
+  expect(getQueryState()?.status).toBe(QueryStatus.fulfilled)
+  expect(getQueryState()?.data).toBe(1)
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/refetchingBehaviors.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/refetchingBehaviors.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/refetchingBehaviors.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,447 @@
+import { createApi, setupListeners } from '@reduxjs/toolkit/query/react'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { delay } from 'msw'
+import { setupApiStore } from '../../tests/utils/helpers'
+
+// Just setup a temporary in-memory counter for tests that `getIncrementedAmount`.
+// This can be used to test how many renders happen due to data changes or
+// the refetching behavior of components.
+let amount = 0
+
+const defaultApi = createApi({
+  baseQuery: async (arg: any) => {
+    await delay(150)
+    if ('amount' in arg?.body) {
+      amount += 1
+    }
+    return {
+      data: arg?.body
+        ? { ...arg.body, ...(amount ? { amount } : {}) }
+        : undefined,
+    }
+  },
+  endpoints: (build) => ({
+    getIncrementedAmount: build.query<any, void>({
+      query: () => ({
+        url: '',
+        body: {
+          amount,
+        },
+      }),
+    }),
+  }),
+  refetchOnFocus: true,
+  refetchOnReconnect: true,
+})
+
+const storeRef = setupApiStore(defaultApi)
+
+const getIncrementedAmountState = () =>
+  storeRef.store.getState().api.queries['getIncrementedAmount(undefined)']
+
+afterEach(() => {
+  amount = 0
+})
+
+describe('refetchOnFocus tests', () => {
+  test('useQuery hook respects refetchOnFocus: true when set in createApi options', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery())
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    fireEvent.focus(window)
+
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('2'),
+    )
+  })
+
+  test('useQuery hook respects refetchOnFocus: false from a hook and overrides createApi defaults', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnFocus: false,
+        }))
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    fireEvent.focus(window)
+
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+  })
+
+  test('useQuery hook prefers refetchOnFocus: true when multiple components have different configurations', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnFocus: false,
+        }))
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    function UserWithRefetchTrue() {
+      ;({ data, isFetching, isLoading } =
+      defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+        refetchOnFocus: true,
+        }))
+      return <div />
+    }
+
+    render(
+      <div>
+        <User />
+        <UserWithRefetchTrue />
+      </div>,
+      { wrapper: storeRef.wrapper },
+    )
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    fireEvent.focus(window)
+    expect(screen.getByTestId('isLoading').textContent).toBe('false')
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('2'),
+    )
+  })
+
+  test('useQuery hook cleans data if refetch without active subscribers', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnFocus: true,
+        }))
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    const { unmount } = render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    unmount()
+
+    expect(getIncrementedAmountState()).not.toBeUndefined()
+
+    fireEvent.focus(window)
+
+    await delay(1)
+    expect(getIncrementedAmountState()).toBeUndefined()
+  })
+})
+
+describe('refetchOnReconnect tests', () => {
+  test('useQuery hook respects refetchOnReconnect: true when set in createApi options', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery())
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    act(() => {
+      window.dispatchEvent(new Event('offline'))
+      window.dispatchEvent(new Event('online'))
+    })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('2'),
+    )
+  })
+
+  test('useQuery hook should not refetch when refetchOnReconnect: false from a hook and overrides createApi defaults', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnReconnect: false,
+        }))
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    render(<User />, { wrapper: storeRef.wrapper })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    act(() => {
+      window.dispatchEvent(new Event('offline'))
+      window.dispatchEvent(new Event('online'))
+    })
+    expect(screen.getByTestId('isFetching').textContent).toBe('false')
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+  })
+
+  test('useQuery hook prefers refetchOnReconnect: true when multiple components have different configurations', async () => {
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnReconnect: false,
+        }))
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    function UserWithRefetchTrue() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnReconnect: true,
+        }))
+      return <div />
+    }
+
+    render(
+      <div>
+        <User />
+        <UserWithRefetchTrue />
+      </div>,
+      { wrapper: storeRef.wrapper },
+    )
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    act(() => {
+      window.dispatchEvent(new Event('offline'))
+      window.dispatchEvent(new Event('online'))
+    })
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('2'),
+    )
+  })
+})
+
+describe('customListenersHandler', () => {
+  const storeRef = setupApiStore(defaultApi, undefined, {
+    withoutListeners: true,
+  })
+
+  test('setupListeners accepts a custom callback and executes it', async () => {
+    const consoleSpy = vi.spyOn(console, 'log')
+    consoleSpy.mockImplementation((...args: any[]) => {
+      // console.info(...args)
+    })
+    const dispatchSpy = vi.spyOn(storeRef.store, 'dispatch')
+
+    let unsubscribe = () => {}
+    unsubscribe = setupListeners(
+      storeRef.store.dispatch,
+      (dispatch, actions) => {
+        const handleOnline = () =>
+          dispatch(defaultApi.internalActions.onOnline())
+        window.addEventListener('online', handleOnline, false)
+        console.log('setup!')
+        return () => {
+          window.removeEventListener('online', handleOnline)
+          console.log('cleanup!')
+        }
+      },
+    )
+
+    await delay(150)
+
+    let data, isLoading, isFetching
+
+    function User() {
+      ;({ data, isFetching, isLoading } =
+        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {
+          refetchOnReconnect: true,
+        }))
+      return (
+        <div>
+          <div data-testid="isLoading">{String(isLoading)}</div>
+          <div data-testid="isFetching">{String(isFetching)}</div>
+          <div data-testid="amount">{String(data?.amount)}</div>
+        </div>
+      )
+    }
+
+    render(<User />, { wrapper: storeRef.wrapper })
+
+    expect(consoleSpy).toHaveBeenCalledWith('setup!')
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isLoading').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('1'),
+    )
+
+    act(() => {
+      window.dispatchEvent(new Event('offline'))
+      window.dispatchEvent(new Event('online'))
+    })
+    expect(dispatchSpy).toHaveBeenCalled()
+
+    // Ignore RTKQ middleware internal data calls
+    const mockCallsWithoutInternals = dispatchSpy.mock.calls.filter((call) => {
+      const type = (call[0] as any)?.type ?? ''
+      const reIsInternal = /internal/i
+      return !reIsInternal.test(type)
+    })
+
+    expect(
+      defaultApi.internalActions.onOnline.match(
+        mockCallsWithoutInternals[1][0] as any,
+      ),
+    ).toBe(true)
+
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('true'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('isFetching').textContent).toBe('false'),
+    )
+    await waitFor(() =>
+      expect(screen.getByTestId('amount').textContent).toBe('2'),
+    )
+
+    unsubscribe()
+    expect(consoleSpy).toHaveBeenCalledWith('cleanup!')
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/retry.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/retry.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/retry.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,46 @@
+import { retry, type RetryOptions } from '@internal/query/retry'
+import {
+  fetchBaseQuery,
+  type FetchBaseQueryError,
+  type FetchBaseQueryMeta,
+} from '@internal/query/fetchBaseQuery'
+
+describe('type tests', () => {
+  test('RetryOptions only accepts one of maxRetries or retryCondition', () => {
+    // Should not complain if only `maxRetries` exists
+    expectTypeOf({ maxRetries: 5 }).toMatchTypeOf<RetryOptions>()
+
+    // Should not complain if only `retryCondition` exists
+    expectTypeOf({ retryCondition: () => false }).toMatchTypeOf<RetryOptions>()
+
+    // Should complain if both `maxRetries` and `retryCondition` exist at once
+    expectTypeOf({
+      maxRetries: 5,
+      retryCondition: () => false,
+    }).not.toMatchTypeOf<RetryOptions>()
+  })
+  test('fail can be pretyped to only accept correct error and meta', () => {
+    expectTypeOf(retry.fail).parameter(0).toEqualTypeOf<unknown>()
+    expectTypeOf(retry.fail).parameter(1).toEqualTypeOf<{} | undefined>()
+    expectTypeOf(retry.fail).toBeCallableWith('Literally anything', {})
+
+    const myBaseQuery = fetchBaseQuery()
+    const typedFail = retry.fail<typeof myBaseQuery>
+
+    expectTypeOf(typedFail).parameter(0).toMatchTypeOf<FetchBaseQueryError>()
+    expectTypeOf(typedFail)
+      .parameter(1)
+      .toMatchTypeOf<FetchBaseQueryMeta | undefined>()
+
+    expectTypeOf(typedFail).toBeCallableWith(
+      {
+        status: 401,
+        data: 'Unauthorized',
+      },
+      { request: new Request('http://localhost') },
+    )
+
+    expectTypeOf(typedFail).parameter(0).not.toMatchTypeOf<string>()
+    expectTypeOf(typedFail).parameter(1).not.toMatchTypeOf<{}>()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/retry.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/retry.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/retry.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,921 @@
+import type { BaseQueryFn, FetchBaseQueryError } from '@reduxjs/toolkit/query'
+import { createApi, retry } from '@reduxjs/toolkit/query'
+import { setupApiStore } from '../../tests/utils/helpers'
+
+beforeEach(() => {
+  vi.useFakeTimers()
+})
+
+const loopTimers = async (max: number = 12) => {
+  let count = 0
+  while (count < max) {
+    await vi.advanceTimersByTimeAsync(1)
+    vi.advanceTimersByTime(120_000)
+    count++
+  }
+}
+
+describe('configuration', () => {
+  test('retrying without any config options', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(baseBaseQuery)
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(7)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(6)
+  })
+
+  test('retrying with baseQuery config that overrides default behavior (maxRetries: 5)', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(5)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(4)
+  })
+
+  test('retrying with endpoint config that overrides baseQuery config', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+        q2: build.query({
+          query: () => {},
+          extraOptions: { maxRetries: 8 },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+    await loopTimers(5)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(4)
+
+    baseBaseQuery.mockClear()
+
+    storeRef.store.dispatch(api.endpoints.q2.initiate({}))
+
+    await loopTimers(10)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(9)
+  })
+
+  test('stops retrying a query after a success', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery
+      .mockResolvedValueOnce({ error: 'rejected' })
+      .mockResolvedValueOnce({ error: 'rejected' })
+      .mockResolvedValue({ data: { success: true } })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 10 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.mutation({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(6)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(3)
+  })
+
+  test('retrying also works with mutations', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        m1: build.mutation({
+          query: () => ({ method: 'PUT' }),
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.m1.initiate({}))
+
+    await loopTimers(5)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(4)
+  })
+
+  test('retrying stops after a success from a mutation', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery
+      .mockRejectedValueOnce(new Error('rejected'))
+      .mockRejectedValueOnce(new Error('rejected'))
+      .mockResolvedValue({ data: { success: true } })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        m1: build.mutation({
+          query: () => ({ method: 'PUT' }),
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.m1.initiate({}))
+
+    await loopTimers(5)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(3)
+  })
+  test('non-error-cases should **not** retry', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ data: { success: true } })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(2)
+
+    expect(baseBaseQuery).toHaveBeenCalledOnce()
+  })
+  test('calling retry.fail(error) will skip retrying and expose the error directly', async () => {
+    const error = { message: 'banana' }
+
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockImplementation((input) => {
+      retry.fail(error)
+      return { data: `this won't happen` }
+    })
+
+    const baseQuery = retry(baseBaseQuery)
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    const result = await storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(2)
+
+    expect(baseBaseQuery).toHaveBeenCalledOnce()
+    expect(result.error).toEqual(error)
+    expect(result).toEqual({
+      endpointName: 'q1',
+      error,
+      isError: true,
+      isLoading: false,
+      isSuccess: false,
+      isUninitialized: false,
+      originalArgs: expect.any(Object),
+      requestId: expect.any(String),
+      startedTimeStamp: expect.any(Number),
+      status: 'rejected',
+    })
+  })
+
+  test('wrapping retry(retry(..., { maxRetries: 3 }), { maxRetries: 3 }) should retry 16 times', async () => {
+    /**
+     * Note:
+     * This will retry 16 total times because we try the initial + 3 retries (sum: 4), then retry that process 3 times (starting at 0 for a total of 4)... 4x4=16 (allegedly)
+     */
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(retry(baseBaseQuery, { maxRetries: 3 }), {
+      maxRetries: 3,
+    })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(18)
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(16)
+  })
+
+  test('accepts a custom backoff fn', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(baseBaseQuery, {
+      maxRetries: 8,
+      backoff: async (attempt, maxRetries) => {
+        const attempts = Math.min(attempt, maxRetries)
+        const timeout = attempts * 300 // Scale up by 300ms per request, ex: 300ms, 600ms, 900ms, 1200ms...
+        await new Promise((resolve) =>
+          setTimeout((res: any) => resolve(res), timeout),
+        )
+      },
+    })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers()
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(9)
+  })
+
+  test('accepts a custom retryCondition fn', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const overrideMaxRetries = 3
+
+    const baseQuery = retry(baseBaseQuery, {
+      retryCondition: (_, __, { attempt }) => attempt <= overrideMaxRetries,
+    })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers()
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(overrideMaxRetries + 1)
+  })
+
+  test('retryCondition with endpoint config that overrides baseQuery config', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(baseBaseQuery, {
+      maxRetries: 10,
+    })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+          extraOptions: {
+            retryCondition: (_, __, { attempt }) => attempt <= 5,
+          },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers()
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(6)
+  })
+
+  test('retryCondition also works with mutations', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+
+    baseBaseQuery
+      .mockRejectedValueOnce(new Error('rejected'))
+      .mockRejectedValueOnce(new Error('hello retryCondition'))
+      .mockRejectedValueOnce(new Error('rejected'))
+      .mockResolvedValue({ error: 'hello retryCondition' })
+
+    const baseQuery = retry(baseBaseQuery, {})
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        m1: build.mutation({
+          query: () => ({ method: 'PUT' }),
+          extraOptions: {
+            retryCondition: (e) =>
+              (e as FetchBaseQueryError).data === 'hello retryCondition',
+          },
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+    storeRef.store.dispatch(api.endpoints.m1.initiate({}))
+
+    await loopTimers()
+
+    expect(baseBaseQuery).toHaveBeenCalledTimes(4)
+  })
+
+  test('Specifying maxRetries as 0 in RetryOptions prevents retries', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery.mockResolvedValue({ error: 'rejected' })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 0 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+    await loopTimers(2)
+
+    expect(baseBaseQuery).toHaveBeenCalledOnce()
+  })
+
+  test('retryCondition receives abort signal and stops retrying when cache entry is removed', async () => {
+    let capturedSignal: AbortSignal | undefined
+    let retryAttempts = 0
+
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+
+    // Always return an error to trigger retries
+    baseBaseQuery.mockResolvedValue({ error: 'network error' })
+
+    let retryConditionCalled = false
+
+    const baseQuery = retry(baseBaseQuery, {
+      retryCondition: (error, args, { attempt, baseQueryApi }) => {
+        retryConditionCalled = true
+        retryAttempts = attempt
+        capturedSignal = baseQueryApi.signal
+
+        // Stop retrying if the signal is aborted
+        if (baseQueryApi.signal.aborted) {
+          return false
+        }
+
+        // Otherwise, retry up to 10 times
+        return attempt <= 10
+      },
+      backoff: async () => {
+        // Short backoff for faster test
+        await new Promise((resolve) => setTimeout(resolve, 10))
+      },
+    })
+
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        getTest: build.query<string, number>({
+          query: (id) => ({ url: `test/${id}` }),
+          keepUnusedDataFor: 0.01, // Very short timeout (10ms)
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    // Start the query
+    const queryPromise = storeRef.store.dispatch(
+      api.endpoints.getTest.initiate(1),
+    )
+
+    // Wait for the first retry to happen so we capture the signal
+    await loopTimers(2)
+
+    // Verify the retry condition was called and we have a signal
+    expect(retryConditionCalled).toBe(true)
+    expect(capturedSignal).toBeDefined()
+    expect(capturedSignal!.aborted).toBe(false)
+
+    // Unsubscribe to trigger cache removal
+    queryPromise.unsubscribe()
+
+    // Wait for the cache entry to be removed (keepUnusedDataFor: 0.01s = 10ms)
+    await vi.advanceTimersByTimeAsync(50)
+
+    // Allow some time for more retries to potentially happen
+    await loopTimers(3)
+
+    // The signal should now be aborted
+    expect(capturedSignal!.aborted).toBe(true)
+
+    // We should have stopped retrying early due to the abort signal
+    // If abort signal wasn't working, we'd see many more retry attempts
+    expect(retryAttempts).toBeLessThan(10)
+
+    // The base query should have been called at least once (initial attempt)
+    // but not the full 10+ times it would without abort signal
+    expect(baseBaseQuery).toHaveBeenCalled()
+    expect(baseBaseQuery.mock.calls.length).toBeLessThan(10)
+  })
+
+  // Tests for issue #4079: Thrown errors should respect maxRetries
+  test('thrown errors (not HandledError) should respect maxRetries', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    // Simulate network error that keeps throwing
+    baseBaseQuery.mockRejectedValue(new Error('Network timeout'))
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(5)
+
+    // Should try initial + 3 retries = 4 total, then stop
+    // Currently this will fail because it retries infinitely
+    expect(baseBaseQuery).toHaveBeenCalledTimes(4)
+  })
+
+  test('graphql-style thrown errors should respect maxRetries', async () => {
+    class ClientError extends Error {
+      constructor(message: string) {
+        super(message)
+        this.name = 'ClientError'
+      }
+    }
+
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    // Simulate graphql-request throwing ClientError
+    baseBaseQuery.mockImplementation(() => {
+      throw new ClientError('GraphQL network error')
+    })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 2 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(4)
+
+    // Should try initial + 2 retries = 3 total, then stop
+    // Currently this will fail because it retries infinitely
+    expect(baseBaseQuery).toHaveBeenCalledTimes(3)
+  })
+
+  test('handles mix of returned errors and thrown errors', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    baseBaseQuery
+      .mockResolvedValueOnce({ error: 'returned error' }) // HandledError
+      .mockRejectedValueOnce(new Error('thrown error')) // Not HandledError
+      .mockResolvedValueOnce({ error: 'returned error' }) // HandledError
+      .mockResolvedValue({ data: { success: true } })
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 5 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        q1: build.query({
+          query: () => {},
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+    await loopTimers(6)
+
+    // Should eventually succeed after 4 attempts
+    expect(baseBaseQuery).toHaveBeenCalledTimes(4)
+  })
+
+  test('thrown errors with mutations should respect maxRetries', async () => {
+    const baseBaseQuery = vi.fn<BaseQueryFn>()
+    // Simulate persistent network error
+    baseBaseQuery.mockRejectedValue(new Error('Connection refused'))
+
+    const baseQuery = retry(baseBaseQuery, { maxRetries: 2 })
+    const api = createApi({
+      baseQuery,
+      endpoints: (build) => ({
+        m1: build.mutation({
+          query: () => ({ method: 'POST' }),
+        }),
+      }),
+    })
+
+    const storeRef = setupApiStore(api, undefined, {
+      withoutTestLifecycles: true,
+    })
+
+    storeRef.store.dispatch(api.endpoints.m1.initiate({}))
+
+    await loopTimers(4)
+
+    // Should try initial + 2 retries = 3 total, then stop
+    // Currently this will fail because it retries infinitely
+    expect(baseBaseQuery).toHaveBeenCalledTimes(3)
+  })
+
+  // These tests validate the abort signal handling implementation
+  describe('abort signal handling', () => {
+    test('retry loop exits immediately when signal is aborted before retry', async () => {
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery.mockResolvedValue({ error: 'network error' })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 10 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      // Let first attempt fail
+      await loopTimers(1)
+      expect(baseBaseQuery).toHaveBeenCalledTimes(1)
+
+      // Abort the query
+      promise.abort()
+
+      // Advance timers to allow retry attempts
+      await loopTimers(5)
+
+      // Should not have retried after abort
+      expect(baseBaseQuery).toHaveBeenCalledTimes(1)
+    })
+
+    test('abort during active request prevents retry', async () => {
+      let requestInProgress = false
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+
+      baseBaseQuery.mockImplementation(async () => {
+        requestInProgress = true
+        await new Promise((resolve) => setTimeout(resolve, 100))
+        requestInProgress = false
+        return { error: 'network error' }
+      })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 5 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      // Wait for request to start
+      await vi.advanceTimersByTimeAsync(50)
+      expect(requestInProgress).toBe(true)
+
+      // Abort while request is in progress
+      promise.abort()
+
+      // Let request complete
+      await loopTimers(2)
+
+      // Should not retry after abort
+      expect(baseBaseQuery).toHaveBeenCalledTimes(1)
+    })
+
+    test('custom backoff without signal parameter still works', async () => {
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery.mockResolvedValue({ error: 'network error' })
+
+      // Custom backoff that doesn't accept signal (backward compatibility)
+      const customBackoff = async (attempt: number, maxRetries: number) => {
+        await new Promise((resolve) => setTimeout(resolve, 100))
+      }
+
+      const baseQuery = retry(baseBaseQuery, {
+        maxRetries: 3,
+        backoff: customBackoff,
+      })
+
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      await loopTimers(5)
+
+      // Should complete all retries (not cancellable without signal)
+      expect(baseBaseQuery).toHaveBeenCalledTimes(4)
+    })
+
+    test('abort signal is checked before each retry attempt', async () => {
+      const attemptNumbers: number[] = []
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery.mockImplementation(async () => {
+        attemptNumbers.push(attemptNumbers.length + 1)
+        return { error: 'network error' }
+      })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 10 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      // Let 3 attempts happen
+      await loopTimers(3)
+      expect(attemptNumbers).toEqual([1, 2, 3])
+
+      // Abort
+      promise.abort()
+
+      // Try to let more attempts happen
+      await loopTimers(5)
+
+      // Should not have any more attempts
+      expect(attemptNumbers).toEqual([1, 2, 3])
+    })
+
+    test('mutations respect abort signal during retry', async () => {
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery.mockResolvedValue({ error: 'network error' })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 5 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          m1: build.mutation({ query: () => ({ method: 'POST' }) }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const promise = storeRef.store.dispatch(api.endpoints.m1.initiate({}))
+
+      // Let first attempt fail
+      await loopTimers(1)
+      expect(baseBaseQuery).toHaveBeenCalledTimes(1)
+
+      // Abort
+      promise.abort()
+
+      // Try to let retries happen
+      await loopTimers(5)
+
+      // Should not have retried
+      expect(baseBaseQuery).toHaveBeenCalledTimes(1)
+    })
+
+    test('abort after successful retry does not affect result', async () => {
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery
+        .mockResolvedValueOnce({ error: 'network error' })
+        .mockResolvedValue({ data: { success: true } })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 5 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      // Let it succeed on retry
+      await loopTimers(3)
+      expect(baseBaseQuery).toHaveBeenCalledTimes(2)
+
+      const result = await promise
+
+      // Abort after success
+      promise.abort()
+
+      // Result should still be successful
+      expect(result.isSuccess).toBe(true)
+      expect(result.data).toEqual({ success: true })
+    })
+
+    test('multiple aborts are handled gracefully', async () => {
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery.mockResolvedValue({ error: 'network error' })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 10 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      await loopTimers(1)
+
+      // Call abort multiple times
+      promise.abort()
+      promise.abort()
+      promise.abort()
+
+      await loopTimers(3)
+
+      // Should handle gracefully
+      expect(baseBaseQuery).toHaveBeenCalledTimes(1)
+    })
+
+    test('abort signal already aborted before retry starts', async () => {
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery.mockResolvedValue({ error: 'network error' })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 5 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      // Abort immediately
+      promise.abort()
+
+      await loopTimers(5)
+
+      // May have started the first attempt before abort was processed
+      // but should not retry
+      expect(baseBaseQuery.mock.calls.length).toBeLessThanOrEqual(1)
+    })
+
+    test('resetApiState aborts retrying queries', async () => {
+      const baseBaseQuery = vi.fn<BaseQueryFn>()
+      baseBaseQuery.mockResolvedValue({ error: 'network error' })
+
+      const baseQuery = retry(baseBaseQuery, { maxRetries: 10 })
+      const api = createApi({
+        baseQuery,
+        endpoints: (build) => ({
+          q1: build.query({ query: () => {} }),
+        }),
+      })
+
+      const storeRef = setupApiStore(api, undefined, {
+        withoutTestLifecycles: true,
+      })
+      storeRef.store.dispatch(api.endpoints.q1.initiate({}))
+
+      // Let first attempt fail and start retrying
+      await loopTimers(2)
+      expect(baseBaseQuery).toHaveBeenCalledTimes(2)
+
+      // Reset API state (should abort the retry loop)
+      storeRef.store.dispatch(api.util.resetApiState())
+
+      // Try to let more retries happen
+      await loopTimers(5)
+
+      // Should not have retried after resetApiState
+      expect(baseBaseQuery).toHaveBeenCalledTimes(2)
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/unionTypes.test-d.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/unionTypes.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/unionTypes.test-d.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,914 @@
+import type { UseQueryStateOptions } from '@internal/query/react/buildHooks'
+import type { SerializedError } from '@reduxjs/toolkit'
+import type {
+  FetchBaseQueryError,
+  QueryDefinition,
+  TypedUseMutationResult,
+  TypedUseQueryHookResult,
+  TypedUseQueryState,
+  TypedUseQueryStateResult,
+  TypedUseQuerySubscriptionResult,
+  TypedLazyQueryTrigger,
+  TypedUseLazyQueryStateResult,
+  TypedUseLazyQuery,
+  TypedUseLazyQuerySubscription,
+  TypedUseMutation,
+  TypedMutationTrigger,
+  TypedUseQuerySubscription,
+  TypedUseQuery,
+  TypedUseQueryStateOptions,
+} from '@reduxjs/toolkit/query/react'
+import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
+
+const baseQuery = fetchBaseQuery()
+
+const api = createApi({
+  baseQuery,
+  endpoints: (build) => ({
+    getTest: build.query<string, void>({ query: () => '' }),
+    mutation: build.mutation<string, void>({ query: () => '' }),
+  }),
+})
+
+describe('union types', () => {
+  test('query selector union', () => {
+    const result = api.endpoints.getTest.select()({} as any)
+
+    if (result.isUninitialized) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isLoading) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isError) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isSuccess) {
+      expectTypeOf(result.data).toBeString()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+    }
+
+    expectTypeOf(result).not.toBeNever()
+
+    // is always one of those four
+    if (
+      !result.isUninitialized &&
+      !result.isLoading &&
+      !result.isError &&
+      !result.isSuccess
+    ) {
+      expectTypeOf(result).toBeNever()
+    }
+  })
+
+  test('useQuery union', () => {
+    const result = api.endpoints.getTest.useQuery()
+
+    if (result.isUninitialized) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isLoading) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isError) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isSuccess) {
+      expectTypeOf(result.data).toBeString()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isFetching) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toBeBoolean()
+
+      expectTypeOf(result.isSuccess).toBeBoolean()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+    }
+
+    expectTypeOf(result.currentData).toEqualTypeOf<string | undefined>()
+
+    if (result.isSuccess) {
+      if (!result.isFetching) {
+        expectTypeOf(result.currentData).toBeString()
+      } else {
+        expectTypeOf(result.currentData).toEqualTypeOf<string | undefined>()
+      }
+    }
+
+    expectTypeOf(result).not.toBeNever()
+
+    // is always one of those four
+    if (
+      !result.isUninitialized &&
+      !result.isLoading &&
+      !result.isError &&
+      !result.isSuccess
+    ) {
+      expectTypeOf(result).toBeNever()
+    }
+  })
+  test('useQuery TS4.1 union', () => {
+    const result = api.useGetTestQuery()
+
+    if (result.isUninitialized) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isLoading) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isError) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isSuccess) {
+      expectTypeOf(result.data).toBeString()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isFetching) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toBeBoolean()
+
+      expectTypeOf(result.isSuccess).toBeBoolean()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+    }
+
+    expectTypeOf(result).not.toBeNever()
+
+    // is always one of those four
+    if (
+      !result.isUninitialized &&
+      !result.isLoading &&
+      !result.isError &&
+      !result.isSuccess
+    ) {
+      expectTypeOf(result).toBeNever()
+    }
+  })
+
+  test('useLazyQuery union', () => {
+    const [_trigger, result] = api.endpoints.getTest.useLazyQuery()
+
+    if (result.isUninitialized) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isLoading) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isError) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isSuccess) {
+      expectTypeOf(result.data).toBeString()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isFetching) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toBeBoolean()
+
+      expectTypeOf(result.isSuccess).toBeBoolean()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+    }
+
+    expectTypeOf(result).not.toBeNever()
+
+    // is always one of those four
+    if (
+      !result.isUninitialized &&
+      !result.isLoading &&
+      !result.isError &&
+      !result.isSuccess
+    ) {
+      expectTypeOf(result).toBeNever()
+    }
+  })
+
+  test('useLazyQuery TS4.1 union', () => {
+    const [_trigger, result] = api.useLazyGetTestQuery()
+
+    if (result.isUninitialized) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isLoading) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isError) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toEqualTypeOf<false>()
+    }
+
+    if (result.isSuccess) {
+      expectTypeOf(result.data).toBeString()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isFetching).toBeBoolean()
+    }
+
+    if (result.isFetching) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toBeBoolean()
+
+      expectTypeOf(result.isSuccess).toBeBoolean()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+    }
+
+    expectTypeOf(result).not.toBeNever()
+
+    // is always one of those four
+    if (
+      !result.isUninitialized &&
+      !result.isLoading &&
+      !result.isError &&
+      !result.isSuccess
+    ) {
+      expectTypeOf(result).toBeNever()
+    }
+  })
+
+  test('queryHookResult (without selector) union', async () => {
+    const useQueryStateResult = api.endpoints.getTest.useQueryState()
+
+    const useQueryResult = api.endpoints.getTest.useQuery()
+
+    const useQueryStateWithSelectFromResult =
+      api.endpoints.getTest.useQueryState(undefined, {
+        selectFromResult: () => ({ x: true }),
+      })
+
+    const { refetch, ...useQueryResultWithoutMethods } = useQueryResult
+
+    assertType<typeof useQueryResultWithoutMethods>(useQueryStateResult)
+
+    expectTypeOf(useQueryStateResult).toMatchTypeOf(
+      useQueryResultWithoutMethods,
+    )
+
+    expectTypeOf(useQueryStateWithSelectFromResult)
+      .parameter(0)
+      .not.toMatchTypeOf(useQueryResultWithoutMethods)
+
+    expectTypeOf(api.endpoints.getTest.select).returns.returns.toEqualTypeOf<
+      Awaited<ReturnType<typeof refetch>>
+    >()
+  })
+
+  test('useQueryState (with selectFromResult)', () => {
+    const result = api.endpoints.getTest.useQueryState(undefined, {
+      selectFromResult({
+        data,
+        isLoading,
+        isFetching,
+        isError,
+        isSuccess,
+        isUninitialized,
+      }) {
+        return {
+          data: data ?? 1,
+          isLoading,
+          isFetching,
+          isError,
+          isSuccess,
+          isUninitialized,
+        }
+      },
+    })
+
+    expectTypeOf({
+      data: '' as string | number,
+      isUninitialized: false,
+      isLoading: true,
+      isFetching: true,
+      isSuccess: false,
+      isError: false,
+    }).toEqualTypeOf(result)
+  })
+
+  test('useQuery (with selectFromResult)', async () => {
+    const { refetch, ...result } = api.endpoints.getTest.useQuery(undefined, {
+      selectFromResult({
+        data,
+        isLoading,
+        isFetching,
+        isError,
+        isSuccess,
+        isUninitialized,
+      }) {
+        return {
+          data: data ?? 1,
+          isLoading,
+          isFetching,
+          isError,
+          isSuccess,
+          isUninitialized,
+        }
+      },
+    })
+
+    expectTypeOf({
+      data: '' as string | number,
+      isUninitialized: false,
+      isLoading: true,
+      isFetching: true,
+      isSuccess: false,
+      isError: false,
+    }).toEqualTypeOf(result)
+
+    expectTypeOf(api.endpoints.getTest.select).returns.returns.toEqualTypeOf<
+      Awaited<ReturnType<typeof refetch>>
+    >()
+  })
+
+  test('useMutation union', () => {
+    const [_trigger, result] = api.endpoints.mutation.useMutation()
+
+    if (result.isUninitialized) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isLoading) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isError) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isSuccess) {
+      expectTypeOf(result.data).toBeString()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+    }
+
+    expectTypeOf(result).not.toBeNever()
+
+    // is always one of those four
+    if (
+      !result.isUninitialized &&
+      !result.isLoading &&
+      !result.isError &&
+      !result.isSuccess
+    ) {
+      expectTypeOf(result).toBeNever()
+    }
+  })
+
+  test('useMutation (with selectFromResult)', () => {
+    const [_trigger, result] = api.endpoints.mutation.useMutation({
+      selectFromResult({
+        data,
+        isLoading,
+        isError,
+        isSuccess,
+        isUninitialized,
+      }) {
+        return {
+          data: data ?? 'hi',
+          isLoading,
+          isError,
+          isSuccess,
+          isUninitialized,
+        }
+      },
+    })
+
+    expectTypeOf({
+      data: '' as string,
+      isUninitialized: false,
+      isLoading: true,
+      isSuccess: false,
+      isError: false,
+      reset: () => {},
+    }).toMatchTypeOf(result)
+  })
+
+  test('useMutation TS4.1 union', () => {
+    const [_trigger, result] = api.useMutationMutation()
+
+    if (result.isUninitialized) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isLoading) {
+      expectTypeOf(result.data).toBeUndefined()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError | undefined
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isError) {
+      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()
+
+      expectTypeOf(result.error).toEqualTypeOf<
+        SerializedError | FetchBaseQueryError
+      >()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()
+    }
+
+    if (result.isSuccess) {
+      expectTypeOf(result.data).toBeString()
+
+      expectTypeOf(result.error).toBeUndefined()
+
+      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isLoading).toEqualTypeOf<false>()
+
+      expectTypeOf(result.isError).toEqualTypeOf<false>()
+    }
+
+    expectTypeOf(result).not.toBeNever()
+
+    // is always one of those four
+    if (
+      !result.isUninitialized &&
+      !result.isLoading &&
+      !result.isError &&
+      !result.isSuccess
+    ) {
+      expectTypeOf(result).toBeNever()
+    }
+  })
+})
+
+describe('"Typed" helper types', () => {
+  test('useQuery', () => {
+    expectTypeOf<TypedUseQuery<string, void, typeof baseQuery>>().toMatchTypeOf(
+      api.endpoints.getTest.useQuery,
+    )
+
+    const result = api.endpoints.getTest.useQuery()
+
+    expectTypeOf<
+      TypedUseQueryHookResult<string, void, typeof baseQuery>
+    >().toEqualTypeOf(result)
+  })
+
+  test('useQuery with selectFromResult', () => {
+    const result = api.endpoints.getTest.useQuery(undefined, {
+      selectFromResult: () => ({ x: true }),
+    })
+
+    expectTypeOf<
+      TypedUseQueryHookResult<string, void, typeof baseQuery, { x: boolean }>
+    >().toEqualTypeOf(result)
+  })
+
+  test('useQueryState', () => {
+    expectTypeOf<
+      TypedUseQueryState<string, void, typeof baseQuery>
+    >().toMatchTypeOf(api.endpoints.getTest.useQueryState)
+
+    const result = api.endpoints.getTest.useQueryState()
+
+    expectTypeOf<
+      TypedUseQueryStateResult<string, void, typeof baseQuery>
+    >().toEqualTypeOf(result)
+  })
+
+  test('useQueryState with selectFromResult', () => {
+    const result = api.endpoints.getTest.useQueryState(undefined, {
+      selectFromResult: () => ({ x: true }),
+    })
+
+    expectTypeOf<
+      TypedUseQueryStateResult<string, void, typeof baseQuery, { x: boolean }>
+    >().toEqualTypeOf(result)
+  })
+
+  test('useQueryState options', () => {
+    expectTypeOf<
+      TypedUseQueryStateOptions<string, void, typeof baseQuery>
+    >().toMatchTypeOf<
+      Parameters<typeof api.endpoints.getTest.useQueryState>[1]
+    >()
+
+    expectTypeOf<
+      UseQueryStateOptions<
+        QueryDefinition<void, typeof baseQuery, string, string>,
+        { x: boolean }
+      >
+    >().toEqualTypeOf<
+      TypedUseQueryStateOptions<string, void, typeof baseQuery, { x: boolean }>
+    >()
+  })
+
+  test('useQuerySubscription', () => {
+    expectTypeOf<
+      TypedUseQuerySubscription<string, void, typeof baseQuery>
+    >().toMatchTypeOf(api.endpoints.getTest.useQuerySubscription)
+
+    const result = api.endpoints.getTest.useQuerySubscription()
+
+    expectTypeOf<
+      TypedUseQuerySubscriptionResult<string, void, typeof baseQuery>
+    >().toEqualTypeOf(result)
+  })
+
+  test('useLazyQuery', () => {
+    expectTypeOf<
+      TypedUseLazyQuery<string, void, typeof baseQuery>
+    >().toMatchTypeOf(api.endpoints.getTest.useLazyQuery)
+
+    const [trigger, result] = api.endpoints.getTest.useLazyQuery()
+
+    expectTypeOf<
+      TypedLazyQueryTrigger<string, void, typeof baseQuery>
+    >().toMatchTypeOf(trigger)
+
+    expectTypeOf<
+      TypedUseLazyQueryStateResult<string, void, typeof baseQuery>
+    >().toMatchTypeOf(result)
+  })
+
+  test('useLazyQuery with selectFromResult', () => {
+    const [trigger, result] = api.endpoints.getTest.useLazyQuery({
+      selectFromResult: () => ({ x: true }),
+    })
+
+    expectTypeOf<
+      TypedLazyQueryTrigger<string, void, typeof baseQuery>
+    >().toMatchTypeOf(trigger)
+
+    expectTypeOf<
+      TypedUseLazyQueryStateResult<
+        string,
+        void,
+        typeof baseQuery,
+        { x: boolean }
+      >
+    >().toMatchTypeOf(result)
+  })
+
+  test('useLazyQuerySubscription', () => {
+    expectTypeOf<
+      TypedUseLazyQuerySubscription<string, void, typeof baseQuery>
+    >().toMatchTypeOf(api.endpoints.getTest.useLazyQuerySubscription)
+
+    const [trigger] = api.endpoints.getTest.useLazyQuerySubscription()
+
+    expectTypeOf<
+      TypedLazyQueryTrigger<string, void, typeof baseQuery>
+    >().toMatchTypeOf(trigger)
+  })
+
+  test('useMutation', () => {
+    expectTypeOf<
+      TypedUseMutation<string, void, typeof baseQuery>
+    >().toMatchTypeOf(api.endpoints.mutation.useMutation)
+
+    const [trigger, result] = api.endpoints.mutation.useMutation()
+
+    expectTypeOf<
+      TypedMutationTrigger<string, void, typeof baseQuery>
+    >().toMatchTypeOf(trigger)
+
+    expectTypeOf<
+      TypedUseMutationResult<string, void, typeof baseQuery>
+    >().toMatchTypeOf(result)
+  })
+
+  test('useQuery - defining selectFromResult separately', () => {
+    const selectFromResult = (
+      result: TypedUseQueryStateResult<string, void, typeof baseQuery>,
+    ) => ({ x: true })
+
+    const result = api.endpoints.getTest.useQuery(undefined, {
+      selectFromResult,
+    })
+
+    expectTypeOf(result).toEqualTypeOf<
+      TypedUseQueryHookResult<
+        string,
+        void,
+        typeof baseQuery,
+        ReturnType<typeof selectFromResult>
+      >
+    >()
+  })
+
+  test('useMutation - defining selectFromResult separately', () => {
+    const selectFromResult = (
+      result: Omit<
+        TypedUseMutationResult<string, void, typeof baseQuery>,
+        'reset' | 'originalArgs'
+      >,
+    ) => ({ x: true })
+
+    const [trigger, result] = api.endpoints.mutation.useMutation({
+      selectFromResult,
+    })
+    expectTypeOf(result).toEqualTypeOf<
+      TypedUseMutationResult<
+        string,
+        void,
+        typeof baseQuery,
+        ReturnType<typeof selectFromResult>
+      >
+    >()
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/useMutation-fixedCacheKey.test.tsx
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/useMutation-fixedCacheKey.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/useMutation-fixedCacheKey.test.tsx	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,394 @@
+import { createApi } from '@reduxjs/toolkit/query/react'
+import {
+  act,
+  getByTestId,
+  render,
+  screen,
+  waitFor,
+} from '@testing-library/react'
+import { delay } from 'msw'
+import { vi } from 'vitest'
+import { setupApiStore } from '../../tests/utils/helpers'
+
+describe('fixedCacheKey', () => {
+  const onNewCacheEntry = vi.fn()
+
+  const api = createApi({
+    async baseQuery(arg: string | Promise<string>) {
+      return { data: await arg }
+    },
+    endpoints: (build) => ({
+      send: build.mutation<string, string | Promise<string>>({
+        query: (arg) => arg,
+      }),
+    }),
+  })
+  const storeRef = setupApiStore(api)
+
+  function Component({
+    name,
+    fixedCacheKey,
+    value = name,
+  }: {
+    name: string
+    fixedCacheKey?: string
+    value?: string | Promise<string>
+  }) {
+    const [trigger, result] = api.endpoints.send.useMutation({ fixedCacheKey })
+
+    return (
+      <div data-testid={name}>
+        <div data-testid="status">{result.status}</div>
+        <div data-testid="data">{result.data}</div>
+        <div data-testid="originalArgs">{String(result.originalArgs)}</div>
+        <button data-testid="trigger" onClick={() => trigger(value)}>
+          trigger
+        </button>
+        <button data-testid="reset" onClick={result.reset}>
+          reset
+        </button>
+      </div>
+    )
+  }
+
+  test('two mutations without `fixedCacheKey` do not influence each other', async () => {
+    render(
+      <>
+        <Component name="C1" />
+        <Component name="C2" />
+      </>,
+      { wrapper: storeRef.wrapper },
+    )
+    const c1 = screen.getByTestId('C1')
+    const c2 = screen.getByTestId('C2')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+
+    act(() => {
+      getByTestId(c1, 'trigger').click()
+    })
+
+    await waitFor(() =>
+      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'),
+    )
+    expect(getByTestId(c1, 'data').textContent).toBe('C1')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+  })
+
+  test('two mutations with the same `fixedCacheKey` do influence each other', async () => {
+    render(
+      <>
+        <Component name="C1" fixedCacheKey="test" />
+        <Component name="C2" fixedCacheKey="test" />
+      </>,
+      { wrapper: storeRef.wrapper },
+    )
+    const c1 = screen.getByTestId('C1')
+    const c2 = screen.getByTestId('C2')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+
+    act(() => {
+      getByTestId(c1, 'trigger').click()
+    })
+
+    await waitFor(() => {
+      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled')
+      expect(getByTestId(c1, 'data').textContent).toBe('C1')
+      expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')
+      expect(getByTestId(c2, 'data').textContent).toBe('C1')
+    })
+
+    // test reset from the other component
+    act(() => {
+      getByTestId(c2, 'reset').click()
+    })
+    await waitFor(() => {
+      expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+      expect(getByTestId(c1, 'data').textContent).toBe('')
+      expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+      expect(getByTestId(c2, 'data').textContent).toBe('')
+    })
+  })
+
+  test('resetting from the component that triggered the mutation resets for each shared result', async () => {
+    render(
+      <>
+        <Component name="C1" fixedCacheKey="test-A" />
+        <Component name="C2" fixedCacheKey="test-A" />
+        <Component name="C3" fixedCacheKey="test-B" />
+        <Component name="C4" fixedCacheKey="test-B" />
+      </>,
+      { wrapper: storeRef.wrapper },
+    )
+    const c1 = screen.getByTestId('C1')
+    const c2 = screen.getByTestId('C2')
+    const c3 = screen.getByTestId('C3')
+    const c4 = screen.getByTestId('C4')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c3, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c4, 'status').textContent).toBe('uninitialized')
+
+    // trigger with a component using the first cache key
+
+    act(() => {
+      getByTestId(c1, 'trigger').click()
+    })
+
+    await waitFor(() =>
+      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'),
+    )
+
+    // the components with the first cache key should be affected
+    expect(getByTestId(c1, 'data').textContent).toBe('C1')
+    expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')
+    expect(getByTestId(c2, 'data').textContent).toBe('C1')
+    expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')
+
+    // the components with the second cache key should be unaffected
+    expect(getByTestId(c3, 'data').textContent).toBe('')
+    expect(getByTestId(c3, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c4, 'data').textContent).toBe('')
+    expect(getByTestId(c4, 'status').textContent).toBe('uninitialized')
+
+    // trigger with a component using the second cache key
+
+    act(() => {
+      getByTestId(c3, 'trigger').click()
+    })
+
+    await waitFor(() =>
+      expect(getByTestId(c3, 'status').textContent).toBe('fulfilled'),
+    )
+
+    // the components with the first cache key should be unaffected
+    await waitFor(() => {
+      expect(getByTestId(c1, 'data').textContent).toBe('C1')
+      expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')
+      expect(getByTestId(c2, 'data').textContent).toBe('C1')
+      expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')
+
+      // the component with the second cache key should be affected
+      expect(getByTestId(c3, 'data').textContent).toBe('C3')
+      expect(getByTestId(c3, 'status').textContent).toBe('fulfilled')
+      expect(getByTestId(c4, 'data').textContent).toBe('C3')
+      expect(getByTestId(c4, 'status').textContent).toBe('fulfilled')
+    })
+
+    // test reset from the component that triggered the mutation for the first cache key
+
+    act(() => {
+      getByTestId(c1, 'reset').click()
+    })
+
+    await waitFor(() => {
+      // the components with the first cache key should be affected
+      expect(getByTestId(c1, 'data').textContent).toBe('')
+      expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+      expect(getByTestId(c2, 'data').textContent).toBe('')
+      expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+
+      // the components with the second cache key should be unaffected
+      expect(getByTestId(c3, 'data').textContent).toBe('C3')
+      expect(getByTestId(c3, 'status').textContent).toBe('fulfilled')
+      expect(getByTestId(c4, 'data').textContent).toBe('C3')
+      expect(getByTestId(c4, 'status').textContent).toBe('fulfilled')
+    })
+  })
+
+  test('two mutations with different `fixedCacheKey` do not influence each other', async () => {
+    render(
+      <>
+        <Component name="C1" fixedCacheKey="test" />
+        <Component name="C2" fixedCacheKey="toast" />
+      </>,
+      { wrapper: storeRef.wrapper },
+    )
+    const c1 = screen.getByTestId('C1')
+    const c2 = screen.getByTestId('C2')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+
+    act(() => {
+      getByTestId(c1, 'trigger').click()
+    })
+
+    await waitFor(() =>
+      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'),
+    )
+    expect(getByTestId(c1, 'data').textContent).toBe('C1')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+  })
+
+  test('unmounting and remounting keeps data intact', async () => {
+    const { rerender } = render(<Component name="C1" fixedCacheKey="test" />, {
+      wrapper: storeRef.wrapper,
+    })
+    let c1 = screen.getByTestId('C1')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+
+    act(() => {
+      getByTestId(c1, 'trigger').click()
+    })
+
+    await waitFor(() =>
+      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'),
+    )
+    expect(getByTestId(c1, 'data').textContent).toBe('C1')
+
+    rerender(<div />)
+    expect(screen.queryByTestId('C1')).toBe(null)
+
+    rerender(<Component name="C1" fixedCacheKey="test" />)
+    c1 = screen.getByTestId('C1')
+    expect(getByTestId(c1, 'status').textContent).toBe('fulfilled')
+    expect(getByTestId(c1, 'data').textContent).toBe('C1')
+  })
+
+  test('(limitation) mutations using `fixedCacheKey` do not return `originalArgs`', async () => {
+    render(
+      <>
+        <Component name="C1" fixedCacheKey="test" />
+        <Component name="C2" fixedCacheKey="test" />
+      </>,
+      { wrapper: storeRef.wrapper },
+    )
+    const c1 = screen.getByTestId('C1')
+    const c2 = screen.getByTestId('C2')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+
+    act(() => {
+      getByTestId(c1, 'trigger').click()
+    })
+
+    await waitFor(() =>
+      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'),
+    )
+    expect(getByTestId(c1, 'data').textContent).toBe('C1')
+    expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')
+    expect(getByTestId(c2, 'data').textContent).toBe('C1')
+  })
+
+  test('a component without `fixedCacheKey` has `originalArgs`', async () => {
+    render(<Component name="C1" />, {
+      wrapper: storeRef.wrapper,
+    })
+    let c1 = screen.getByTestId('C1')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c1, 'originalArgs').textContent).toBe('undefined')
+
+    await act(async () => {
+      getByTestId(c1, 'trigger').click()
+      await Promise.resolve()
+    })
+
+    expect(getByTestId(c1, 'originalArgs').textContent).toBe('C1')
+  })
+
+  test('a component with `fixedCacheKey` does never have `originalArgs`', async () => {
+    render(<Component name="C1" fixedCacheKey="test" />, {
+      wrapper: storeRef.wrapper,
+    })
+    let c1 = screen.getByTestId('C1')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c1, 'originalArgs').textContent).toBe('undefined')
+
+    await act(async () => {
+      getByTestId(c1, 'trigger').click()
+    })
+
+    expect(getByTestId(c1, 'originalArgs').textContent).toBe('undefined')
+  })
+
+  test('using `fixedCacheKey` will always use the latest dispatched thunk, prevent races', async () => {
+    let resolve1: (str: string) => void, resolve2: (str: string) => void
+    const p1 = new Promise<string>((resolve) => {
+      resolve1 = resolve
+    })
+    const p2 = new Promise<string>((resolve) => {
+      resolve2 = resolve
+    })
+    render(
+      <>
+        <Component name="C1" fixedCacheKey="test" value={p1} />
+        <Component name="C2" fixedCacheKey="test" value={p2} />
+      </>,
+      { wrapper: storeRef.wrapper },
+    )
+    const c1 = screen.getByTestId('C1')
+    const c2 = screen.getByTestId('C2')
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')
+
+    await act(async () => {
+      getByTestId(c1, 'trigger').click()
+      await Promise.resolve()
+    })
+
+    expect(getByTestId(c1, 'status').textContent).toBe('pending')
+    expect(getByTestId(c1, 'data').textContent).toBe('')
+
+    act(() => {
+      getByTestId(c2, 'trigger').click()
+    })
+
+    expect(getByTestId(c1, 'status').textContent).toBe('pending')
+    expect(getByTestId(c1, 'data').textContent).toBe('')
+
+    await act(async () => {
+      resolve1!('this should not show up any more')
+      await Promise.resolve()
+    })
+
+    await delay(150)
+
+    expect(getByTestId(c1, 'status').textContent).toBe('pending')
+    expect(getByTestId(c1, 'data').textContent).toBe('')
+
+    await act(async () => {
+      resolve2!('this should be visible')
+      await Promise.resolve()
+    })
+
+    await delay(150)
+
+    expect(getByTestId(c1, 'status').textContent).toBe('fulfilled')
+    expect(getByTestId(c1, 'data').textContent).toBe('this should be visible')
+  })
+
+  test('using fixedCacheKey should create a new cache entry', async () => {
+    api.enhanceEndpoints({
+      endpoints: {
+        send: {
+          onCacheEntryAdded: (arg) => onNewCacheEntry(arg),
+        },
+      },
+    })
+
+    render(<Component name="C1" fixedCacheKey={'testKey'} />, {
+      wrapper: storeRef.wrapper,
+    })
+
+    let c1 = screen.getByTestId('C1')
+
+    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')
+    expect(getByTestId(c1, 'originalArgs').textContent).toBe('undefined')
+
+    await act(async () => {
+      getByTestId(c1, 'trigger').click()
+      await Promise.resolve()
+    })
+
+    expect(onNewCacheEntry).toHaveBeenCalledWith('C1')
+
+    api.enhanceEndpoints({
+      endpoints: {
+        send: {
+          onCacheEntryAdded: undefined,
+        },
+      },
+    })
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tests/utils.test.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tests/utils.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tests/utils.test.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,93 @@
+import { vi } from 'vitest'
+import { isOnline, isDocumentVisible, joinUrls } from '@internal/query/utils'
+
+afterAll(() => {
+  vi.restoreAllMocks()
+})
+
+describe('isOnline', () => {
+  test('Assumes online=true in a node env', () => {
+    vi.spyOn(window, 'navigator', 'get').mockImplementation(
+      () => undefined as any,
+    )
+
+    expect(navigator).toBeUndefined()
+    expect(isOnline()).toBe(true)
+  })
+
+  test('Returns false if navigator isOnline=false', () => {
+    vi.spyOn(window, 'navigator', 'get').mockImplementation(
+      () => ({ onLine: false }) as any,
+    )
+    expect(isOnline()).toBe(false)
+  })
+
+  test('Returns true if navigator isOnline=true', () => {
+    vi.spyOn(window, 'navigator', 'get').mockImplementation(
+      () => ({ onLine: true }) as any,
+    )
+    expect(isOnline()).toBe(true)
+  })
+})
+
+describe('isDocumentVisible', () => {
+  test('Assumes true when in a non-browser env', () => {
+    vi.spyOn(window, 'document', 'get').mockImplementation(
+      () => undefined as any,
+    )
+    expect(window.document).toBeUndefined()
+    expect(isDocumentVisible()).toBe(true)
+  })
+
+  test('Returns false when hidden=true', () => {
+    vi.spyOn(window, 'document', 'get').mockImplementation(
+      () => ({ visibilityState: 'hidden' }) as any,
+    )
+    expect(isDocumentVisible()).toBe(false)
+  })
+
+  test('Returns true when visibilityState=prerender', () => {
+    vi.spyOn(window, 'document', 'get').mockImplementation(
+      () => ({ visibilityState: 'prerender' }) as any,
+    )
+    expect(document.visibilityState).toBe('prerender')
+    expect(isDocumentVisible()).toBe(true)
+  })
+  test('Returns true when visibilityState=visible', () => {
+    vi.spyOn(window, 'document', 'get').mockImplementation(
+      () => ({ visibilityState: 'visible' }) as any,
+    )
+    expect(document.visibilityState).toBe('visible')
+    expect(isDocumentVisible()).toBe(true)
+  })
+  test('Returns true when visibilityState=undefined', () => {
+    vi.spyOn(window, 'document', 'get').mockImplementation(
+      () => ({ visibilityState: undefined }) as any,
+    )
+    expect(document.visibilityState).toBeUndefined()
+    expect(isDocumentVisible()).toBe(true)
+  })
+})
+
+describe('joinUrls', () => {
+  test.each([
+    ['/api/', '/banana', '/api/banana'],
+    ['/api/', 'banana', '/api/banana'],
+    ['/api', '/banana', '/api/banana'],
+    ['/api', 'banana', '/api/banana'],
+    ['', '/banana', '/banana'],
+    ['', 'banana', 'banana'],
+    ['api', '?a=1', 'api?a=1'],
+    ['api/', '?a=1', 'api/?a=1'],
+    ['api', 'banana?a=1', 'api/banana?a=1'],
+    ['api/', 'banana?a=1', 'api/banana?a=1'],
+    ['https://example.com/api', 'banana', 'https://example.com/api/banana'],
+    ['https://example.com/api', '/banana', 'https://example.com/api/banana'],
+    ['https://example.com/api/', 'banana', 'https://example.com/api/banana'],
+    ['https://example.com/api/', '/banana', 'https://example.com/api/banana'],
+    ['https://example.com/api/', 'https://example.org', 'https://example.org'],
+    ['https://example.com/api/', '//example.org', '//example.org'],
+  ])('%s and %s join to %s', (base, url, expected) => {
+    expect(joinUrls(base, url)).toBe(expected)
+  })
+})
Index: node_modules/@reduxjs/toolkit/src/query/tsHelpers.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/tsHelpers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/tsHelpers.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,50 @@
+export type Id<T> = { [K in keyof T]: T[K] } & {}
+export type WithRequiredProp<T, K extends keyof T> = Omit<T, K> &
+  Required<Pick<T, K>>
+export type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never
+export function assertCast<T>(v: any): asserts v is T {}
+
+export function safeAssign<T extends object>(
+  target: T,
+  ...args: Array<Partial<NoInfer<T>>>
+): T {
+  return Object.assign(target, ...args)
+}
+
+/**
+ * Convert a Union type `(A|B)` to an intersection type `(A&B)`
+ */
+export type UnionToIntersection<U> = (
+  U extends any ? (k: U) => void : never
+) extends (k: infer I) => void
+  ? I
+  : never
+
+export type NonOptionalKeys<T> = {
+  [K in keyof T]-?: undefined extends T[K] ? never : K
+}[keyof T]
+
+export type HasRequiredProps<T, True, False> =
+  NonOptionalKeys<T> extends never ? False : True
+
+export type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>
+
+export type NoInfer<T> = [T][T extends any ? 0 : never]
+
+export type NonUndefined<T> = T extends undefined ? never : T
+
+export type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T
+
+export type MaybePromise<T> = T | PromiseLike<T>
+
+export type OmitFromUnion<T, K extends keyof T> = T extends any
+  ? Omit<T, K>
+  : never
+
+export type IsAny<T, True, False = never> = true | false extends (
+  T extends never ? true : false
+)
+  ? True
+  : False
+
+export type CastAny<T, CastTo> = IsAny<T, CastTo, T>
Index: node_modules/@reduxjs/toolkit/src/query/utils/capitalize.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/capitalize.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/capitalize.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,3 @@
+export function capitalize(str: string) {
+  return str.replace(str[0], str[0].toUpperCase())
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/copyWithStructuralSharing.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/copyWithStructuralSharing.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/copyWithStructuralSharing.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,27 @@
+import { isPlainObject as _iPO } from '../core/rtkImports'
+
+// remove type guard
+const isPlainObject: (_: any) => boolean = _iPO
+
+export function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T
+export function copyWithStructuralSharing(oldObj: any, newObj: any): any {
+  if (
+    oldObj === newObj ||
+    !(
+      (isPlainObject(oldObj) && isPlainObject(newObj)) ||
+      (Array.isArray(oldObj) && Array.isArray(newObj))
+    )
+  ) {
+    return newObj
+  }
+  const newKeys = Object.keys(newObj)
+  const oldKeys = Object.keys(oldObj)
+
+  let isSameObject = newKeys.length === oldKeys.length
+  const mergeObj: any = Array.isArray(newObj) ? [] : {}
+  for (const key of newKeys) {
+    mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key])
+    if (isSameObject) isSameObject = oldObj[key] === mergeObj[key]
+  }
+  return isSameObject ? oldObj : mergeObj
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/countObjectKeys.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/countObjectKeys.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/countObjectKeys.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,14 @@
+// Fast method for counting an object's keys
+// without resorting to `Object.keys(obj).length
+// Will this make a big difference in perf? Probably not
+// But we can save a few allocations.
+
+export function countObjectKeys(obj: Record<any, any>) {
+  let count = 0
+
+  for (const _key in obj) {
+    count++
+  }
+
+  return count
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/filterMap.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/filterMap.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/filterMap.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,27 @@
+// Preserve type guard predicate behavior when passing to mapper
+export function filterMap<T, U, S extends T = T>(
+  array: readonly T[],
+  predicate: (item: T, index: number) => item is S,
+  mapper: (item: S, index: number) => U | U[],
+): U[]
+
+export function filterMap<T, U>(
+  array: readonly T[],
+  predicate: (item: T, index: number) => boolean,
+  mapper: (item: T, index: number) => U | U[],
+): U[]
+
+export function filterMap<T, U>(
+  array: readonly T[],
+  predicate: (item: T, index: number) => boolean,
+  mapper: (item: T, index: number) => U | U[],
+): U[] {
+  return array
+    .reduce<(U | U[])[]>((acc, item, i) => {
+      if (predicate(item as any, i)) {
+        acc.push(mapper(item as any, i))
+      }
+      return acc
+    }, [])
+    .flat() as U[]
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/getCurrent.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/getCurrent.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/getCurrent.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,6 @@
+import type { Draft } from 'immer'
+import { current, isDraft } from '../utils/immerImports'
+
+export function getCurrent<T>(value: T | Draft<T>): T {
+  return (isDraft(value) ? current(value) : value) as T
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/getOrInsert.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/getOrInsert.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/getOrInsert.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,41 @@
+// Duplicate some of the utils in `/src/utils` to ensure
+// we don't end up dragging in larger chunks of the RTK core
+// into the RTKQ bundle
+
+export function getOrInsert<K extends object, V>(
+  map: WeakMap<K, V>,
+  key: K,
+  value: V,
+): V
+export function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V
+export function getOrInsert<K extends object, V>(
+  map: Map<K, V> | WeakMap<K, V>,
+  key: K,
+  value: V,
+): V {
+  if (map.has(key)) return map.get(key) as V
+
+  return map.set(key, value).get(key) as V
+}
+
+export function getOrInsertComputed<K extends object, V>(
+  map: WeakMap<K, V>,
+  key: K,
+  compute: (key: K) => V,
+): V
+export function getOrInsertComputed<K, V>(
+  map: Map<K, V>,
+  key: K,
+  compute: (key: K) => V,
+): V
+export function getOrInsertComputed<K extends object, V>(
+  map: Map<K, V> | WeakMap<K, V>,
+  key: K,
+  compute: (key: K) => V,
+): V {
+  if (map.has(key)) return map.get(key) as V
+
+  return map.set(key, compute(key)).get(key) as V
+}
+
+export const createNewMap = () => new Map()
Index: node_modules/@reduxjs/toolkit/src/query/utils/immerImports.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/immerImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/immerImports.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,9 @@
+export {
+  current,
+  isDraft,
+  applyPatches,
+  original,
+  isDraftable,
+  produceWithPatches,
+  enablePatches,
+} from 'immer'
Index: node_modules/@reduxjs/toolkit/src/query/utils/index.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/index.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,11 @@
+export * from './capitalize'
+export * from './copyWithStructuralSharing'
+export * from './countObjectKeys'
+export * from './filterMap'
+export * from './isAbsoluteUrl'
+export * from './isDocumentVisible'
+export * from './isNotNullish'
+export * from './isOnline'
+export * from './isValidUrl'
+export * from './joinUrls'
+export * from './getOrInsert'
Index: node_modules/@reduxjs/toolkit/src/query/utils/isAbsoluteUrl.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/isAbsoluteUrl.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/isAbsoluteUrl.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,9 @@
+/**
+ * If either :// or // is present consider it to be an absolute url
+ *
+ * @param url string
+ */
+
+export function isAbsoluteUrl(url: string) {
+  return new RegExp(`(^|:)//`).test(url)
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/isDocumentVisible.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/isDocumentVisible.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/isDocumentVisible.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,12 @@
+/**
+ * Assumes true for a non-browser env, otherwise makes a best effort
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState
+ */
+export function isDocumentVisible(): boolean {
+  // `document` may not exist in non-browser envs (like RN)
+  if (typeof document === 'undefined') {
+    return true
+  }
+  // Match true for visible, prerender, undefined
+  return document.visibilityState !== 'hidden'
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/isNotNullish.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/isNotNullish.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/isNotNullish.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,7 @@
+export function isNotNullish<T>(v: T | null | undefined): v is T {
+  return v != null
+}
+
+export function filterNullishValues<T>(map?: Map<any, T>) {
+  return [...(map?.values() ?? [])].filter(isNotNullish) as NonNullable<T>[]
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/isOnline.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/isOnline.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/isOnline.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,12 @@
+/**
+ * Assumes a browser is online if `undefined`, otherwise makes a best effort
+ * @link https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine
+ */
+export function isOnline() {
+  // We set the default config value in the store, so we'd need to check for this in a SSR env
+  return typeof navigator === 'undefined'
+    ? true
+    : navigator.onLine === undefined
+      ? true
+      : navigator.onLine
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/isValidUrl.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/isValidUrl.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/isValidUrl.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,9 @@
+export function isValidUrl(string: string) {
+  try {
+    new URL(string)
+  } catch (_) {
+    return false
+  }
+
+  return true
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/joinUrls.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/joinUrls.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/joinUrls.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,26 @@
+import { isAbsoluteUrl } from './isAbsoluteUrl'
+
+const withoutTrailingSlash = (url: string) => url.replace(/\/$/, '')
+const withoutLeadingSlash = (url: string) => url.replace(/^\//, '')
+
+export function joinUrls(
+  base: string | undefined,
+  url: string | undefined,
+): string {
+  if (!base) {
+    return url!
+  }
+  if (!url) {
+    return base
+  }
+
+  if (isAbsoluteUrl(url)) {
+    return url
+  }
+
+  const delimiter = base.endsWith('/') || !url.startsWith('?') ? '/' : ''
+  base = withoutTrailingSlash(base)
+  url = withoutLeadingSlash(url)
+
+  return `${base}${delimiter}${url}`
+}
Index: node_modules/@reduxjs/toolkit/src/query/utils/signals.ts
===================================================================
--- node_modules/@reduxjs/toolkit/src/query/utils/signals.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
+++ node_modules/@reduxjs/toolkit/src/query/utils/signals.ts	(revision a762898ecd37a452c782821d4c2c4955c6ed2521)
@@ -0,0 +1,33 @@
+// AbortSignal.timeout() is currently baseline 2024
+export const timeoutSignal = (milliseconds: number) => {
+  const abortController = new AbortController()
+  setTimeout(() => {
+    const message = 'signal timed out'
+    const name = 'TimeoutError'
+    abortController.abort(
+      // some environments (React Native, Node) don't have DOMException
+      typeof DOMException !== 'undefined'
+        ? new DOMException(message, name)
+        : Object.assign(new Error(message), { name }),
+    )
+  }, milliseconds)
+  return abortController.signal
+}
+
+// AbortSignal.any() is currently baseline 2024
+export const anySignal = (...signals: AbortSignal[]) => {
+  // if any are already aborted, return an already aborted signal
+  for (const signal of signals)
+    if (signal.aborted) return AbortSignal.abort(signal.reason)
+
+  // otherwise, create a new signal that aborts when any of the given signals abort
+  const abortController = new AbortController()
+  for (const signal of signals) {
+    signal.addEventListener(
+      'abort',
+      () => abortController.abort(signal.reason),
+      { signal: abortController.signal, once: true },
+    )
+  }
+  return abortController.signal
+}
